@typesol/cli 0.27.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 (42) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +3 -1
  3. package/dist/compiler/analyze.d.ts +5 -1
  4. package/dist/compiler/analyze.js +53 -15
  5. package/dist/compiler/emit/alias.d.ts +48 -0
  6. package/dist/compiler/emit/alias.js +166 -0
  7. package/dist/compiler/emit/base.d.ts +1 -0
  8. package/dist/compiler/emit/borsh.js +6 -3
  9. package/dist/compiler/emit/calls.js +23 -4
  10. package/dist/compiler/emit/cpi-core.d.ts +70 -0
  11. package/dist/compiler/emit/cpi-core.js +356 -0
  12. package/dist/compiler/emit/cpi.d.ts +10 -175
  13. package/dist/compiler/emit/cpi.js +71 -2716
  14. package/dist/compiler/emit/create.d.ts +39 -0
  15. package/dist/compiler/emit/create.js +548 -0
  16. package/dist/compiler/emit/function.d.ts +11 -2
  17. package/dist/compiler/emit/function.js +55 -12
  18. package/dist/compiler/emit/metaplex.d.ts +78 -0
  19. package/dist/compiler/emit/metaplex.js +1345 -0
  20. package/dist/compiler/emit/program.js +24 -4
  21. package/dist/compiler/emit/shared.d.ts +5 -1
  22. package/dist/compiler/emit/shared.js +11 -2
  23. package/dist/compiler/emit/statements.d.ts +0 -9
  24. package/dist/compiler/emit/statements.js +2 -53
  25. package/dist/compiler/emit/storage.d.ts +5 -20
  26. package/dist/compiler/emit/storage.js +55 -100
  27. package/dist/compiler/emit/token.d.ts +8 -0
  28. package/dist/compiler/emit/token.js +493 -0
  29. package/dist/compiler/idl.js +1 -1
  30. package/dist/compiler/model.d.ts +12 -2
  31. package/dist/compiler/model.js +7 -1
  32. package/dist/tools/portgen.js +3 -0
  33. package/docs/architecture.md +31 -2
  34. package/docs/audit.md +4 -2
  35. package/docs/case-study-multisig.md +169 -0
  36. package/docs/errors.md +6 -4
  37. package/docs/language.md +22 -6
  38. package/docs/migrate-from-anchor.md +7 -2
  39. package/docs/security-model.md +5 -1
  40. package/lib/typesol.d.ts +51 -7
  41. package/package.json +1 -1
  42. package/runtime/typesol_rt.h +93 -3
@@ -1,2579 +1,10 @@
1
1
  import ts from "typescript";
2
- import { discriminator, snakeCase } from "../analyze.js";
3
- import { borshMinSize } from "./borsh.js";
4
- import { INT_INFO, isScalar, isWritable, optionKey, sameType, scalarSize, typeName, } from "../model.js";
5
- import { MAX_ACCOUNTS, MAX_SEEDS, MAX_CPI_DATA, MAX_EVENT, U64, U8, BOOL, PUBKEY, STRING, cBytes, isStable, cString, scalarStorageC, optC, valueC, emptySizeC, fixedVecC, vecCount, } from "./shared.js";
6
- import { CallEmitter } from "./calls.js";
7
- /**
8
- * Bubblegum instructions that replace a leaf: discriminator, accounts in order ([label, writable, signer, optional,
9
- * either-signs]) and the leaf's shape. Optional accounts take `null` (the program id). The Merkle proof follows the
10
- * leaf (and metadata) as remaining accounts.
11
- */
12
- const BUBBLEGUM_OPS = {
13
- delegateV2: {
14
- disc: [95, 87, 125, 140, 181, 131, 128, 227],
15
- leaf: "delegate",
16
- accounts: [
17
- ["treeConfig", true, false],
18
- ["payer", true, true],
19
- ["leafOwner", false, true, true],
20
- ["previousLeafDelegate", false, false, true],
21
- ["newLeafDelegate", false, false],
22
- ["merkleTree", true, false],
23
- ["logWrapper", false, false],
24
- ["compressionProgram", false, false],
25
- ["systemProgram", false, false],
26
- ],
27
- },
28
- ...Object.fromEntries([
29
- ["freezeV2", [200, 151, 244, 102, 16, 195, 255, 3], false],
30
- ["thawV2", [96, 133, 101, 93, 82, 220, 146, 191], false],
31
- ["setNonTransferableV2", [181, 141, 206, 58, 242, 199, 152, 168], true],
32
- ].map(([name, disc, needsCollection]) => [
33
- name,
34
- {
35
- disc: disc,
36
- leaf: "v2",
37
- accounts: [
38
- ["treeConfig", true, false],
39
- ["payer", true, true],
40
- ["authority", false, true, true],
41
- ["leafOwner", false, false],
42
- ["leafDelegate", false, false, name === "setNonTransferableV2"],
43
- ["merkleTree", true, false],
44
- ["coreCollection", false, false, !needsCollection],
45
- ["logWrapper", false, false],
46
- ["compressionProgram", false, false],
47
- ["systemProgram", false, false],
48
- ],
49
- },
50
- ])),
51
- updateMetadataV2: {
52
- disc: [43, 103, 89, 42, 121, 242, 62, 72],
53
- leaf: "meta",
54
- accounts: [
55
- ["treeConfig", true, false],
56
- ["payer", true, true],
57
- ["authority", false, true, true],
58
- ["leafOwner", false, false],
59
- ["leafDelegate", false, false, true],
60
- ["merkleTree", true, false],
61
- ["coreCollection", false, false, true],
62
- ["logWrapper", false, false],
63
- ["compressionProgram", false, false],
64
- ["systemProgram", false, false],
65
- ],
66
- },
67
- ...Object.fromEntries([
68
- ["verifyCreatorV2", [85, 138, 140, 42, 22, 241, 118, 102]],
69
- ["unverifyCreatorV2", [174, 112, 29, 142, 230, 100, 239, 7]],
70
- ].map(([name, disc]) => [
71
- name,
72
- {
73
- disc: disc,
74
- leaf: "meta",
75
- accounts: [
76
- ["treeConfig", true, false],
77
- ["payer", true, true],
78
- ["creator", false, true, true],
79
- ["leafOwner", false, false],
80
- ["leafDelegate", false, false, true],
81
- ["merkleTree", true, false],
82
- ["logWrapper", false, false],
83
- ["compressionProgram", false, false],
84
- ["systemProgram", false, false],
85
- ],
86
- },
87
- ])),
88
- setCollectionV2: {
89
- disc: [229, 35, 61, 91, 15, 14, 99, 160],
90
- leaf: "meta",
91
- accounts: [
92
- ["treeConfig", true, false],
93
- ["payer", true, true],
94
- ["authority", false, true, true],
95
- ["newCollectionAuthority", false, true, true],
96
- ["leafOwner", false, false],
97
- ["leafDelegate", false, false, true],
98
- ["merkleTree", true, false],
99
- ["coreCollection", true, false, true],
100
- ["newCoreCollection", true, false, true],
101
- ["mplCoreCpiSigner", false, false, true],
102
- ["logWrapper", false, false],
103
- ["compressionProgram", false, false],
104
- ["mplCoreProgram", false, false],
105
- ["systemProgram", false, false],
106
- ],
107
- },
108
- // V1 trees (SPL Account Compression, SPL Noop).
109
- transfer: {
110
- disc: [163, 52, 200, 231, 140, 3, 69, 186],
111
- leaf: "v1",
112
- accounts: [
113
- ["treeConfig", false, false],
114
- ["leafOwner", false, false, false, "owner"],
115
- ["leafDelegate", false, false, false, "delegate"],
116
- ["newLeafOwner", false, false],
117
- ["merkleTree", true, false],
118
- ["logWrapper", false, false],
119
- ["compressionProgram", false, false],
120
- ["systemProgram", false, false],
121
- ],
122
- },
123
- burn: {
124
- disc: [116, 110, 29, 56, 107, 219, 42, 93],
125
- leaf: "v1",
126
- accounts: [
127
- ["treeConfig", false, false],
128
- ["leafOwner", false, false, false, "owner"],
129
- ["leafDelegate", false, false, false, "delegate"],
130
- ["merkleTree", true, false],
131
- ["logWrapper", false, false],
132
- ["compressionProgram", false, false],
133
- ["systemProgram", false, false],
134
- ],
135
- },
136
- delegate: {
137
- disc: [90, 147, 75, 178, 85, 88, 4, 137],
138
- leaf: "v1",
139
- accounts: [
140
- ["treeConfig", false, false],
141
- ["leafOwner", false, false, false, "owner"],
142
- ["previousLeafDelegate", false, false],
143
- ["newLeafDelegate", false, false],
144
- ["merkleTree", true, false],
145
- ["logWrapper", false, false],
146
- ["compressionProgram", false, false],
147
- ["systemProgram", false, false],
148
- ],
149
- },
150
- };
151
- /** Metaplex Core's Plugin / PluginType enums, in order (MasterEdition, VerifiedCreators and Autograph values are refused). */
152
- const CORE_PLUGINS = [
153
- "Royalties",
154
- "FreezeDelegate",
155
- "BurnDelegate",
156
- "TransferDelegate",
157
- "UpdateDelegate",
158
- "PermanentFreezeDelegate",
159
- "Attributes",
160
- "PermanentTransferDelegate",
161
- "PermanentBurnDelegate",
162
- "Edition",
163
- "MasterEdition",
164
- "AddBlocker",
165
- "ImmutableMetadata",
166
- "VerifiedCreators",
167
- "Autograph",
168
- "BubblegumV2",
169
- "FreezeExecute",
170
- "PermanentFreezeExecute",
171
- "Groups",
172
- ];
173
- const CORE_PLUGIN_FIELDS = {
174
- Royalties: ["basisPoints", "creators", "ruleSet"],
175
- MasterEdition: ["maxSupply", "name", "uri"],
176
- VerifiedCreators: ["signatures"],
177
- Autograph: ["signatures"],
178
- FreezeExecute: ["frozen"],
179
- PermanentFreezeExecute: ["frozen"],
180
- FreezeDelegate: ["frozen"],
181
- PermanentFreezeDelegate: ["frozen"],
182
- UpdateDelegate: ["additionalDelegates"],
183
- Attributes: ["attributes"],
184
- Edition: ["number"],
185
- };
186
- /**
187
- * Other programs: PDAs and seeds, account creation, System/Token/ATA/Metaplex CPIs, generic invoke, Borsh
188
- * serialization and events.
189
- */
190
- export class CpiEmitter extends CallEmitter {
191
- /**
192
- * Lower a seeds array literal into a `SolSignerSeed[]` with `extra` spare slots. Also describes
193
- * the seeds in Anchor IDL terms when every element is a constant, an argument or an account path.
194
- */
195
- seeds(node, extra) {
196
- if (!ts.isArrayLiteralExpression(node))
197
- this.fail(node, "seeds must be an array literal");
198
- if (node.elements.length > MAX_SEEDS)
199
- this.fail(node, `at most ${MAX_SEEDS} seeds`);
200
- const parts = [];
201
- let idl = [];
202
- // Without calls or writes among the seeds, nothing can change a seed before the CPI reads it: account fields are
203
- // then passed in place instead of copied.
204
- const mutates = (n) => ts.isCallExpression(n) ||
205
- (ts.isBinaryExpression(n) && n.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && n.operatorToken.kind <= ts.SyntaxKind.LastAssignment) ||
206
- ts.isPrefixUnaryExpression(n) ||
207
- ts.isPostfixUnaryExpression(n) ||
208
- ts.forEachChild(n, mutates) === true;
209
- const inPlace = !node.elements.some(mutates);
210
- const mark = this.lines.length;
211
- for (const el of node.elements) {
212
- const desc = this.describeSeed(el);
213
- if (!desc)
214
- idl = undefined;
215
- else
216
- idl?.push(desc);
217
- if (ts.isStringLiteral(el)) {
218
- const len = Buffer.byteLength(el.text, "utf8");
219
- if (len > 32)
220
- this.fail(el, "a seed can be at most 32 bytes");
221
- parts.push(`{(const uint8_t *)${cString(el.text)}, ${len}}`);
222
- continue;
223
- }
224
- // Each seed is copied when it is evaluated, so later seeds (helper calls) cannot change earlier ones.
225
- const v = this.expr(el);
226
- if (v.type.kind === "pubkey" && (isStable(v.c) || (inPlace && /^\(&d_\w+(->\w+)+\)$/.test(v.c))))
227
- parts.push(`{(const uint8_t *)${v.c.startsWith("(") ? v.c : `(${v.c})`}, 32}`);
228
- else if (v.type.kind === "int" && inPlace && v.literal === undefined && /^d_\w+(->\w+)+$/.test(v.c))
229
- parts.push(`{(const uint8_t *)&${v.c}, ${INT_INFO[v.type.name].bytes}}`);
230
- else if (v.type.kind === "pubkey") {
231
- const t = this.tmp("seed");
232
- this.line(`SolPubkey ${t} = *(${v.c});`);
233
- parts.push(`{(const uint8_t *)&${t}, 32}`);
234
- }
235
- else if (v.type.kind === "string") {
236
- const t = this.tmp("seed");
237
- this.line(`TS_Str ${t} = ${this.ownedString(v).c};`);
238
- parts.push(`{${t}.ptr, ${t}.len}`);
239
- }
240
- else if (v.type.kind === "int") {
241
- const typed = v.literal !== undefined ? this.literal(v.literal, U64, el) : v;
242
- const info = INT_INFO[typed.type.name];
243
- const t = this.tmp("seed");
244
- this.line(`${info.c} ${t} = ${typed.c};`);
245
- parts.push(`{(const uint8_t *)&${t}, ${info.bytes}}`);
246
- }
247
- else if (v.type.kind === "enum") {
248
- // A unit enum value is its variant index, one byte (as in Seeds<…> and Borsh).
249
- const t = this.tmp("seed");
250
- this.line(`uint8_t ${t} = (uint8_t)(${v.c});`);
251
- parts.push(`{(const uint8_t *)&${t}, 1}`);
252
- }
253
- else
254
- this.fail(el, "seeds can be strings, Pubkeys, integers or unit enum values");
255
- }
256
- // The same list again (escrow: the vault transfer, then its close) reuses the array declared for the first, when
257
- // nothing was copied into temporaries (every entry points at a literal or at the place itself, so the array reads
258
- // what a new one would), it has no spare slot (callers never write into those arrays) and it is still in scope.
259
- const key = parts.join(", ");
260
- const reusable = extra === 0 && parts.length > 0 && this.lines.length === mark;
261
- const known = reusable ? this.seedArrays.get(key) : undefined;
262
- if (known && this.scopes.includes(known.scope) && this.lines[known.at]?.trim() === known.text)
263
- return { name: known.name, count: parts.length, idl };
264
- const name = this.tmp("seeds");
265
- const slots = parts.length + extra;
266
- this.line(`SolSignerSeed ${name}[${Math.max(slots, 1)}] = {${parts.join(", ")}};`);
267
- if (reusable)
268
- this.seedArrays.set(key, { name, scope: this.scopes[this.scopes.length - 1], at: this.lines.length - 1, text: this.lines.at(-1).trim() });
269
- return { name, count: parts.length, idl };
270
- }
271
- describeSeed(el) {
272
- if (ts.isStringLiteral(el))
273
- return { kind: "const", value: [...Buffer.from(el.text, "utf8")] };
274
- if (ts.isBigIntLiteral(el)) {
275
- const value = BigInt(el.text.slice(0, -1).replace(/_/g, ""));
276
- if (value > INT_INFO.u64.max)
277
- this.fail(el, `${value} does not fit in u64`);
278
- const b = Buffer.alloc(8);
279
- b.writeBigUInt64LE(value);
280
- return { kind: "const", value: [...b] };
281
- }
282
- // Only the argument itself, not a local that shadows its name.
283
- if (ts.isIdentifier(el) && this.ix?.args.some((a) => a.name === el.text) && this.lookup(el.text) === this.args.get(el.text))
284
- return { kind: "arg", path: snakeCase(el.text) };
285
- if (ts.isIdentifier(el) && !this.lookup(el.text)) {
286
- const k = this.model.constants.get(el.text);
287
- if (k && typeof k.value === "string")
288
- return { kind: "const", value: [...Buffer.from(k.value, "utf8")] };
289
- if (k && typeof k.value === "object")
290
- return { kind: "const", value: k.value.pubkey };
291
- if (k && typeof k.value === "bigint") {
292
- // Little-endian two's complement in the constant's width (16 bytes for u128/i128), as the program hashes it.
293
- const bytes = k.type ? scalarSize(k.type) : 8;
294
- const v = BigInt.asUintN(bytes * 8, k.value);
295
- return { kind: "const", value: Array.from({ length: bytes }, (_, i) => Number((v >> BigInt(8 * i)) & 0xffn)) };
296
- }
297
- }
298
- if (ts.isPropertyAccessExpression(el) && ts.isIdentifier(el.expression)) {
299
- const a = this.accounts.get(el.expression.text);
300
- if (a && el.name.text === "key")
301
- return { kind: "account", path: snakeCase(a.name) };
302
- if (a && (a.kind.kind === "account" || a.kind.kind === "init" || a.kind.kind === "zeroed" || a.kind.kind === "initIfNeeded")) {
303
- const f = a.kind.struct.fields.find((x) => x.name === el.name.text);
304
- if (f && isScalar(f.type))
305
- return { kind: "account", path: `${snakeCase(a.name)}.${snakeCase(f.name)}`, account: a.kind.struct.name };
306
- }
307
- }
308
- return undefined;
309
- }
310
- recordPda(account, idl) {
311
- if (this.ix && idl && !this.ix.pdas.has(account.name))
312
- this.ix.pdas.set(account.name, idl);
313
- }
314
- create(node, target, topLevel, ifNeeded = false) {
315
- const call = `${target.name}.${ifNeeded ? "createIfNeeded" : "create"}`;
316
- if (!topLevel)
317
- this.fail(node, `${call}(...) must be a top-level statement of the instruction`);
318
- if (this.created.has(target.name))
319
- this.fail(node, `${target.name} is already created`);
320
- if (node.arguments.length !== 2 && node.arguments.length !== 3)
321
- this.fail(node, `${call}(payer, seeds | null, space?) takes two or three arguments`);
322
- const payer = this.accountParam(node.arguments[0], "the payer");
323
- if (payer.kind.kind !== "signer" || !payer.kind.mut)
324
- this.fail(node.arguments[0], "the payer must be a Mut<Signer>");
325
- const s = target.kind.struct;
326
- const keypair = node.arguments[1].kind === ts.SyntaxKind.NullKeyword;
327
- if (keypair && ifNeeded)
328
- this.fail(node.arguments[1], "createIfNeeded takes seeds: a keypair account cannot be checked to be the one meant");
329
- const seeds = keypair ? undefined : this.seeds(node.arguments[1], 1);
330
- if (seeds)
331
- this.recordPda(target, seeds.idl);
332
- const b = this.tmp("bump");
333
- // The account's size: the struct's (8 + its fixed size, Anchor's InitSpace for @layout borsh), or Anchor's
334
- // `space = …` when given, which must hold the struct.
335
- const need = s.layout === "borsh" ? `8 + sizeof(TSS_${s.name})` : `8 + ${emptySizeC(s)}`;
336
- let space = need;
337
- const spaceArg = node.arguments[2];
338
- if (spaceArg) {
339
- if (s.vec)
340
- this.fail(spaceArg, `${s.name} has a growable Vec: its size follows the Vec's length, so it takes no space argument`);
341
- const raw = this.expr(spaceArg);
342
- const v = this.expect(raw, U64, spaceArg);
343
- const min = 8 + this.fieldBytes({ kind: "struct", name: s.name });
344
- if (raw.literal !== undefined && raw.literal < BigInt(min))
345
- this.fail(spaceArg, `${s.name} needs at least ${min} bytes (8 + its size)`);
346
- space = this.tmp("space");
347
- this.line(`uint64_t ${space} = ${v.c};`);
348
- this.line(`if (${space} < ${need} || ${space} > 10240) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: space must hold the account and be at most 10240 bytes");`);
349
- }
350
- this.line(`uint8_t ${b};`);
351
- const done = () => {
352
- this.created.add(target.name);
353
- this.pendingInit.delete(target.name);
354
- this.bumps.set(target.name, b);
355
- };
356
- if (!seeds) {
357
- // A new keypair account that signs the transaction (Anchor's `init` without seeds).
358
- target.signsInit = true;
359
- this.line(`TS_TRY(ts_create_owned(params, a_${payer.name}, a_${target.name}, NULL, 0, params->program_id, ${space}, &${b}));`);
360
- this.line(`a_${target.name}->data_len = ${space};`);
361
- this.line(`ts_memcpy(a_${target.name}->data, TS_DISC_${s.name}, 8);`);
362
- done();
363
- return { c: b, type: U8 };
364
- }
365
- if (ifNeeded) {
366
- // Returns whether it was created now; an existing account must be this PDA, ours, and a ${s.name}.
367
- const created = this.tmp("created");
368
- this.line(`bool ${created};`);
369
- this.line(`TS_TRY(ts_create_pda_if_needed(params, a_${payer.name}, a_${target.name}, ${seeds.name}, ${seeds.count}, TS_DISC_${s.name}, ${space}, 8 + ${s.layout === "borsh" ? borshMinSize(s, this.model) : `sizeof(TSS_${s.name})`}, &${b}, &${created}));`);
370
- // An existing @layout borsh account is unpacked now (a new one starts from the zeroed struct).
371
- if (s.layout === "borsh")
372
- this.line(`if (!${created}) TS_TRY(ts_unpack_${s.name}(a_${target.name}->data + 8, a_${target.name}->data_len - 8, d_${target.name}, NULL));`);
373
- done();
374
- return { c: created, type: BOOL };
375
- }
376
- this.line(`TS_TRY(ts_create_pda(params, a_${payer.name}, a_${target.name}, ${seeds.name}, ${seeds.count}, TS_DISC_${s.name}, ${space}, &${b}));`);
377
- done();
378
- return { c: b, type: U8 };
379
- }
380
- /**
381
- * `vault.create(payer, seeds | null, mint, authority)` on `Init<TokenAccount>` and `mint.create(payer, seeds | null,
382
- * decimals, authority, freezeAuthority | null)` on `Init<Mint>` (Anchor's `init` with `token::` / `mint::`
383
- * constraints): a PDA of this program (or, with `null`, a new keypair account that signs), created owned by the
384
- * instruction's token program and initialized. `createIfNeeded` on `InitIfNeeded<…>` does that unless the account
385
- * exists, and then checks it is that PDA, owned by the token program, and has that mint and owner / those
386
- * authorities and decimals (Anchor's init_if_needed checks). create returns the bump (0 for a keypair),
387
- * createIfNeeded whether it created the account.
388
- */
389
- createToken(node, target, topLevel) {
390
- const isMint = target.kind.kind === "mint";
391
- const ifNeeded = target.kind.init === "ifNeeded";
392
- const call = `${target.name}.${ifNeeded ? "createIfNeeded" : "create"}`;
393
- const usage = isMint
394
- ? `${call}(payer, seeds | null, decimals, mintAuthority, freezeAuthority | null, extensions?, tokenProgram?)`
395
- : `${call}(payer, seeds | null, mint, authority, tokenProgram?)`;
396
- if (!topLevel)
397
- this.fail(node, `${call}(...) must be a top-level statement of the instruction`);
398
- if (this.created.has(target.name))
399
- this.fail(node, `${target.name} is already created`);
400
- const a = node.arguments;
401
- if (!isMint && a.length === 1)
402
- this.fail(node, `${call}(payer) creates an associated token account: wrap it in Ata<…, "owner", "mint">; or call ${usage.slice(call.length)}`);
403
- // A mint may list its Token-2022 extensions next (Anchor's `extensions::…`), as an object literal.
404
- const bare = (e) => e && (ts.isAsExpression(e) || ts.isParenthesizedExpression(e) || ts.isSatisfiesExpression(e)) ? bare(e.expression) : e;
405
- const ext5 = bare(a[5]);
406
- const extArg = isMint && ext5 && ts.isObjectLiteralExpression(ext5) ? ext5 : undefined;
407
- const fixedArgs = isMint ? (extArg ? 6 : 5) : 4;
408
- if (a.length !== fixedArgs && a.length !== fixedArgs + 1)
409
- this.fail(node, usage);
410
- const payer = this.accountParam(a[0], "the payer");
411
- if (payer.kind.kind !== "signer" || !payer.kind.mut)
412
- this.fail(a[0], "the payer must be a Mut<Signer>");
413
- // The token program: named as the last argument, or the instruction's only token program parameter.
414
- let programs = this.ix.accounts.filter((p) => p.kind.kind === "tokenProgram");
415
- if (a[fixedArgs]) {
416
- const named = this.accountParam(a[fixedArgs], "the token program");
417
- if (named.kind.kind !== "tokenProgram")
418
- this.fail(a[fixedArgs], "pass a TokenProgram, Token2022Program or TokenInterface parameter");
419
- programs = [named];
420
- }
421
- if (programs.length !== 1)
422
- this.fail(node, `${call}(...) needs one token program: pass it as the last argument, or have exactly one token program parameter`);
423
- if (programs[0].optional)
424
- this.fail(programs[0].node, `${call}(...) needs "${programs[0].name}": it cannot be optional`);
425
- if (!this.ix.accounts.some((p) => p.kind.kind === "system" && !p.optional))
426
- this.fail(node, `${call}(...) needs a SystemProgram parameter`);
427
- const tp = `a_${programs[0].name}`;
428
- const acct = `a_${target.name}`;
429
- // Seeds, then the values, in source order.
430
- let seeds = { name: "NULL", count: 0 };
431
- if (a[1].kind !== ts.SyntaxKind.NullKeyword) {
432
- const s = this.seeds(a[1], 1);
433
- this.recordPda(target, s.idl);
434
- seeds = s;
435
- }
436
- else
437
- target.signsInit = true;
438
- const vals = [];
439
- const take = (n, t) => {
440
- const mark = this.lines.length;
441
- // The account's own address is known before it exists (`vault.create(payer, seeds, mint, vault.key)`).
442
- const own = ts.isPropertyAccessExpression(n) && n.name.text === "key" && ts.isIdentifier(n.expression) && n.expression.text === target.name;
443
- const v = own ? { c: `(&${acct}->key)`, type: PUBKEY } : this.expect(this.expr(n, t), t, n);
444
- for (let j = 0; j < vals.length; j++)
445
- vals[j] = this.settle(vals[j], mark);
446
- vals.push(v);
447
- };
448
- let mint;
449
- const extLines = [];
450
- const extChecks = [];
451
- let mintSpace = "TS_MINT_LEN";
452
- if (isMint) {
453
- take(a[2], U8);
454
- take(a[3], PUBKEY);
455
- if (a[4].kind !== ts.SyntaxKind.NullKeyword)
456
- take(a[4], PUBKEY);
457
- if (extArg) {
458
- if (programs[0].kind.kind === "tokenProgram" && programs[0].kind.flavor === "token")
459
- this.fail(extArg, "mint extensions are Token-2022's; use Token2022Program or TokenInterface");
460
- const ext = this.mintExtensions(extArg, tp, acct, ifNeeded);
461
- mintSpace = String(ext.space);
462
- extLines.push(...ext.lines);
463
- extChecks.push(...ext.checks);
464
- }
465
- }
466
- else {
467
- mint = this.accountParam(a[2], "the mint");
468
- if (mint.kind.kind !== "mint")
469
- this.fail(a[2], "pass the Mint parameter the account will hold");
470
- take(a[3], PUBKEY);
471
- }
472
- const b = this.tmp("bump");
473
- this.line(`uint8_t ${b};`);
474
- const created = this.tmp("created");
475
- const createLines = [];
476
- if (isMint) {
477
- const [decimals, authority, freeze] = vals;
478
- createLines.push(`TS_TRY(ts_create_owned(params, a_${payer.name}, ${acct}, ${seeds.name}, ${seeds.count}, &${tp}->key, ${mintSpace}, &${b}));`, ...extLines, `TS_TRY(ts_token_init_mint(params, ${tp}, ${acct}, (uint8_t)(${decimals.c}), ${authority.c}, ${freeze ? freeze.c : "NULL"}));`);
479
- if (ifNeeded) {
480
- this.line(`bool ${created} = ts_key_eq(&${acct}->owner, &TS_SYSTEM_PROGRAM_ID);`);
481
- this.line(`if (${created}) {`);
482
- for (const l of createLines)
483
- this.line(` ${l}`);
484
- this.line(`} else {`);
485
- this.line(` TS_TRY(ts_token_existing(params, ${acct}, ${tp}, ${seeds.name}, ${seeds.count}, &${b}));`);
486
- this.line(` TS_TRY(ts_check_mint(${acct}));`);
487
- this.line(` TS_TRY(ts_check_mint_is(${acct}, (uint8_t)(${decimals.c}), ${authority.c}, ${freeze ? freeze.c : "NULL"}));`);
488
- for (const l of extChecks)
489
- this.line(` ${l}`);
490
- this.line(`}`);
491
- }
492
- else
493
- for (const l of createLines)
494
- this.line(l);
495
- }
496
- else {
497
- const [authority] = vals;
498
- const space = this.tmp("space");
499
- createLines.push(`uint64_t ${space};`, `TS_TRY(ts_token_account_space(params, ${tp}, a_${mint.name}, &${space}));`, `TS_TRY(ts_create_owned(params, a_${payer.name}, ${acct}, ${seeds.name}, ${seeds.count}, &${tp}->key, ${space}, &${b}));`, `TS_TRY(ts_token_init_account(params, ${tp}, ${acct}, a_${mint.name}, ${authority.c}));`);
500
- if (ifNeeded) {
501
- this.line(`bool ${created} = ts_key_eq(&${acct}->owner, &TS_SYSTEM_PROGRAM_ID);`);
502
- this.line(`if (${created}) {`);
503
- for (const l of createLines)
504
- this.line(` ${l}`);
505
- this.line(`} else {`);
506
- this.line(` TS_TRY(ts_token_existing(params, ${acct}, ${tp}, ${seeds.name}, ${seeds.count}, &${b}));`);
507
- this.line(` TS_TRY(ts_check_token_account(${acct}));`);
508
- this.line(` if (!ts_key_eq(ts_token_mint(${acct}), &a_${mint.name}->key)) TS_FAIL(TS_ERR_TOKEN_MINT, "TypeSOL: ${target.name} is not a token account of ${mint.name}");`);
509
- this.line(` if (!ts_key_eq(ts_token_owner(${acct}), ${authority.c})) TS_FAIL(TS_ERR_TOKEN_OWNER, "TypeSOL: ${target.name} has another owner");`);
510
- this.line(`}`);
511
- }
512
- else
513
- for (const l of createLines)
514
- this.line(l);
515
- }
516
- this.created.add(target.name);
517
- this.pendingInit.delete(target.name);
518
- this.bumps.set(target.name, b);
519
- return ifNeeded ? { c: created, type: BOOL } : { c: b, type: U8 };
520
- }
521
- /**
522
- * The extensions in `mint.create(…, { … })` (Anchor's `extensions::…` constraints): their values are evaluated now,
523
- * in source order; the returned lines (each extension's Token-2022 initializer, mint writable, before
524
- * InitializeMint2) run after the account is created, sized for exactly these extensions.
525
- */
526
- mintExtensions(lit, tp, acct, ifNeeded = false) {
527
- const optKey = { kind: "option", inner: PUBKEY };
528
- this.model.options.set("pubkey", PUBKEY);
529
- // name: [extension type length, initializer tag, the fields an object value takes ([] for a plain value)]
530
- const KINDS = {
531
- transferFee: { len: 108, fields: ["configAuthority", "withdrawAuthority", "basisPoints", "maximumFee"] },
532
- closeAuthority: { len: 32, fields: [] },
533
- defaultAccountState: { len: 1, fields: [] },
534
- nonTransferable: { len: 0, fields: [] },
535
- interestBearing: { len: 52, fields: ["rateAuthority", "rate"] },
536
- permanentDelegate: { len: 32, fields: [] },
537
- transferHook: { len: 64, fields: ["authority", "programId"] },
538
- metadataPointer: { len: 64, fields: ["authority", "metadataAddress"] },
539
- groupPointer: { len: 64, fields: ["authority", "groupAddress"] },
540
- groupMemberPointer: { len: 64, fields: ["authority", "memberAddress"] },
541
- };
542
- const given = new Map();
543
- for (const p of lit.properties) {
544
- const value = ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) ? p.initializer : ts.isShorthandPropertyAssignment(p) ? p.name : undefined;
545
- if (!value || !p.name || !ts.isIdentifier(p.name))
546
- this.fail(p, "write the extensions as `name: value` entries");
547
- if (!KINDS[p.name.text])
548
- this.fail(p.name, `mint extensions: ${Object.keys(KINDS).join(", ")}`);
549
- given.set(p.name.text, value);
550
- }
551
- const U16 = { kind: "int", name: "u16" };
552
- const I16 = { kind: "int", name: "i16" };
553
- // Values in source order, held in temporaries; the CPIs come later.
554
- const held = new Map();
555
- const keyTmp = (e, nonZero) => {
556
- // OptionalNonZeroPubkey (32 bytes, zero for none) or COption (a tag byte, then 32).
557
- const v = this.expect(this.expr(e, optKey), optKey, e);
558
- const t = this.tmp("xk");
559
- this.line(`${optC(PUBKEY)} ${t} = ${v.c};`);
560
- if (!nonZero)
561
- return t;
562
- const z = this.tmp("xz");
563
- this.line(`SolPubkey ${z};`);
564
- this.line(`if (${t}.some) ${z} = ${t}.v; else ts_memzero(&${z}, 32);`);
565
- return z;
566
- };
567
- const scalarTmp = (e, t) => {
568
- const v = this.expect(this.expr(e, t), t, e);
569
- const n = this.tmp("xv");
570
- this.line(`${scalarStorageC(t)} ${n} = ${v.c};`);
571
- return n;
572
- };
573
- for (const [name, e] of given) {
574
- const k = KINDS[name];
575
- const vals = new Map();
576
- if (k.fields.length) {
577
- if (!ts.isObjectLiteralExpression(e))
578
- this.fail(e, `${name}: { ${k.fields.join(", ")} }`);
579
- const props = new Map();
580
- for (const p of e.properties) {
581
- const value = ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) ? p.initializer : ts.isShorthandPropertyAssignment(p) ? p.name : undefined;
582
- if (!value || !p.name || !ts.isIdentifier(p.name) || !k.fields.includes(p.name.text))
583
- this.fail(p, `${name}: { ${k.fields.join(", ")} }`);
584
- props.set(p.name.text, value);
585
- }
586
- for (const f of k.fields)
587
- if (!props.has(f))
588
- this.fail(e, `${name} needs ${f}`);
589
- for (const [f, v] of props) {
590
- if (f === "basisPoints") {
591
- const t = scalarTmp(v, U16);
592
- this.line(`if (${t} > 10000) TS_FAIL(TS_ERR_INSTRUCTION_DATA, "TypeSOL: transfer fee above 10000 basis points");`);
593
- vals.set(f, t);
594
- }
595
- else if (f === "maximumFee")
596
- vals.set(f, scalarTmp(v, U64));
597
- else if (f === "rate")
598
- vals.set(f, scalarTmp(v, I16));
599
- else
600
- vals.set(f, keyTmp(v, name !== "transferFee"));
601
- }
602
- }
603
- else if (name === "closeAuthority")
604
- vals.set("v", keyTmp(e, false));
605
- else if (name === "permanentDelegate") {
606
- const v = this.expect(this.expr(e, PUBKEY), PUBKEY, e);
607
- const t = this.tmp("xk");
608
- this.line(`SolPubkey ${t} = *(${v.c});`);
609
- vals.set("v", t);
610
- }
611
- else if (name === "defaultAccountState") {
612
- const v = this.expect(this.expr(e, BOOL), BOOL, e);
613
- const t = this.tmp("xs");
614
- this.line(`uint8_t ${t} = (${v.c}) ? 2 : 1;`); // frozen: AccountState::Frozen, else Initialized
615
- vals.set("v", t);
616
- }
617
- else if (!(e.kind === ts.SyntaxKind.TrueKeyword))
618
- this.fail(e, "nonTransferable: true");
619
- held.set(name, vals);
620
- }
621
- // Each initializer: its bytes, then a CPI with the mint as the only (writable) account.
622
- const lines = [];
623
- const cpi = (bytes) => {
624
- const total = bytes.reduce((n, [, k]) => n + k, 0);
625
- const buf = this.tmp("xd");
626
- lines.push(`{ uint8_t ${buf}[${total}]; uint64_t at = 0;`);
627
- for (const [src, n] of bytes)
628
- lines.push(` ts_memcpy(${buf} + at, ${src}, ${n}); at += ${n};`);
629
- lines.push(` SolAccountMeta m[1] = {{&${acct}->key, true, false}};`, ` TS_TRY(ts_cpi(params, ${tp}, ${buf}, at, m, 1, NULL, 0)); }`);
630
- };
631
- const tag = (n) => `(const uint8_t[]){${n}}`;
632
- const coption = (t) => [
633
- [`(const uint8_t[]){${t}.some ? 1 : 0}`, 1],
634
- [`&${t}.v`, 32],
635
- ];
636
- let space = 0;
637
- for (const name of Object.keys(KINDS)) {
638
- const v = held.get(name);
639
- if (!v)
640
- continue;
641
- space += 4 + KINDS[name].len;
642
- switch (name) {
643
- case "transferFee":
644
- cpi([
645
- [tag(26), 1],
646
- [tag(0), 1],
647
- ...coption(v.get("configAuthority")),
648
- ...coption(v.get("withdrawAuthority")),
649
- [`&${v.get("basisPoints")}`, 2],
650
- [`&${v.get("maximumFee")}`, 8],
651
- ]);
652
- break;
653
- case "closeAuthority":
654
- cpi([[tag(25), 1], ...coption(v.get("v"))]);
655
- break;
656
- case "defaultAccountState":
657
- cpi([
658
- [tag(28), 1],
659
- [tag(0), 1],
660
- [`&${v.get("v")}`, 1],
661
- ]);
662
- break;
663
- case "nonTransferable":
664
- cpi([[tag(32), 1]]);
665
- break;
666
- case "interestBearing":
667
- cpi([
668
- [tag(33), 1],
669
- [tag(0), 1],
670
- [`&${v.get("rateAuthority")}`, 32],
671
- [`&${v.get("rate")}`, 2],
672
- ]);
673
- break;
674
- case "permanentDelegate":
675
- cpi([
676
- [tag(35), 1],
677
- [`&${v.get("v")}`, 32],
678
- ]);
679
- break;
680
- default: {
681
- const t = { transferHook: 36, metadataPointer: 39, groupPointer: 40, groupMemberPointer: 41 }[name];
682
- const [f1, f2] = KINDS[name].fields;
683
- cpi([
684
- [tag(t), 1],
685
- [tag(0), 1],
686
- [`&${v.get(f1)}`, 32],
687
- [`&${v.get(f2)}`, 32],
688
- ]);
689
- }
690
- }
691
- }
692
- // An existing mint (createIfNeeded) is checked as Anchor's `extensions::…` constraints check it: the extension must
693
- // be there (its Anchor code) and each key must match (the next codes). Anchor has constraints for these six only.
694
- const CHECKS = {
695
- groupPointer: {
696
- type: 20,
697
- code: 2024,
698
- fields: [
699
- ["authority", 0],
700
- ["groupAddress", 32],
701
- ],
702
- },
703
- groupMemberPointer: {
704
- type: 21,
705
- code: 2027,
706
- fields: [
707
- ["authority", 0],
708
- ["memberAddress", 32],
709
- ],
710
- },
711
- metadataPointer: {
712
- type: 18,
713
- code: 2030,
714
- fields: [
715
- ["authority", 0],
716
- ["metadataAddress", 32],
717
- ],
718
- },
719
- closeAuthority: { type: 3, code: 2033, fields: [["v", 0]] },
720
- permanentDelegate: { type: 12, code: 2035, fields: [["v", 0]] },
721
- transferHook: {
722
- type: 14,
723
- code: 2037,
724
- fields: [
725
- ["authority", 0],
726
- ["programId", 32],
727
- ],
728
- },
729
- };
730
- const checks = [];
731
- if (ifNeeded)
732
- for (const [name, v] of held) {
733
- const c = CHECKS[name];
734
- if (!c)
735
- this.fail(lit, `${name} cannot be checked on an existing mint (Anchor has no constraint for it): create the mint with create(…)`);
736
- checks.push(`{ uint64_t eo, el; if (!ts_t22_ext(${acct}, ${c.type}, &eo, &el)) TS_FAIL(${c.code}, "TypeSOL: the mint has no ${name} extension"); }`);
737
- c.fields.forEach(([f, at], i) => {
738
- const held = v.get(f);
739
- // The value given: a nonzero-or-zero key, a COption (close authority) or a plain key (permanent delegate).
740
- const want = name === "closeAuthority" ? `(${held}.some ? ${held}.v : (SolPubkey){0})` : held;
741
- checks.push(`{ SolPubkey k, w = ${want}; if (!ts_t22_key(${acct}, ${c.type}, ${at}, &k)) ts_memzero(&k, 32); if (!ts_key_eq(&k, &w)) TS_FAIL(${c.code + 1 + i}, "TypeSOL: the mint's ${name} ${f === "v" ? "key" : f} differs"); }`);
742
- });
743
- }
744
- // Base account (165, the mint padded to an account's size), the account type byte, then each TLV entry.
745
- return { space: 165 + 1 + space, lines, checks };
746
- }
747
- /**
748
- * `ata.create(payer)` / `ata.createIfNeeded(payer)` on `Ata<Init|InitIfNeeded<TokenAccount>, "owner", "mint">`
749
- * (Anchor's `init` / `init_if_needed` with `associated_token::…`). create always calls the ATA program's Create, which
750
- * fails if the account exists. createIfNeeded calls it only when the account is still a System account (Anchor's
751
- * test) and otherwise checks that the existing account is that ATA. Either way the account is then checked as an
752
- * initialized token account of that mint and owner, and is a TokenAccount from here on.
753
- */
754
- createAta(node, target, topLevel) {
755
- const ifNeeded = target.kind.init === "ifNeeded";
756
- const call = `${target.name}.${ifNeeded ? "createIfNeeded" : "create"}`;
757
- if (!topLevel)
758
- this.fail(node, `${call}(...) must be a top-level statement of the instruction`);
759
- if (this.created.has(target.name))
760
- this.fail(node, `${target.name} is already created`);
761
- if (node.arguments.length !== 1)
762
- this.fail(node, `${call}(payer) takes the payer`);
763
- const payer = this.accountParam(node.arguments[0], "the payer");
764
- if (payer.kind.kind !== "signer" || !payer.kind.mut)
765
- this.fail(node.arguments[0], "the payer must be a Mut<Signer>");
766
- const need = (kind, what) => {
767
- const p = this.ix.accounts.find((o) => o.kind.kind === kind);
768
- if (!p)
769
- this.fail(node, `${call}(...) needs ${what} parameter`);
770
- if (p.optional)
771
- this.fail(p.node, `${call}(...) needs "${p.name}": it cannot be optional`);
772
- return p;
773
- };
774
- const ataProgram = need("ataProgram", "an AssociatedTokenProgram");
775
- const system = need("system", "a SystemProgram");
776
- const tokenProgram = need("tokenProgram", "a token program (TokenProgram, Token2022Program or TokenInterface)");
777
- // The address is derived under the token program: with two, which one the mint uses is not known here.
778
- const tokenPrograms = this.ix.accounts.filter((o) => o.kind.kind === "tokenProgram");
779
- if (tokenPrograms.length > 1)
780
- this.fail(node, `${call}(...) needs exactly one token program parameter (found ${tokenPrograms.map((o) => o.name).join(", ")}); use TokenInterface`);
781
- const { owner, mint } = target.constraints.ata;
782
- const a = `a_${target.name}`;
783
- const create = `TS_TRY(ts_ata_create(params, a_${ataProgram.name}, a_${payer.name}, ${a}, a_${owner}, a_${mint}, a_${system.name}, a_${tokenProgram.name}, false));`;
784
- let result;
785
- if (ifNeeded) {
786
- const created = this.tmp("created");
787
- this.line(`bool ${created} = ts_key_eq(&${a}->owner, &TS_SYSTEM_PROGRAM_ID);`);
788
- this.line(`if (${created}) {`);
789
- this.line(` ${create}`);
790
- this.line(`} else {`);
791
- this.line(` SolPubkey ata_${target.name};`);
792
- this.line(` TS_TRY(ts_ata_address(&a_${owner}->key, &a_${mint}->key, &a_${tokenProgram.name}->key, &ata_${target.name}));`);
793
- this.line(` if (!ts_key_eq(&ata_${target.name}, &${a}->key)) TS_FAIL(TS_ERR_ASSOCIATED, "TypeSOL: ${target.name} is not the associated token account of ${owner} and ${mint}");`);
794
- this.line(`}`);
795
- result = { c: created, type: BOOL };
796
- }
797
- else
798
- this.line(create);
799
- this.line(`TS_TRY(ts_check_token_account(${a}));`);
800
- this.line(`if (!ts_key_eq(ts_token_mint(${a}), &a_${mint}->key)) TS_FAIL(TS_ERR_TOKEN_MINT, "TypeSOL: ${target.name} is not a token account of ${mint}");`);
801
- this.line(`if (!ts_key_eq(ts_token_owner(${a}), &a_${owner}->key)) TS_FAIL(TS_ERR_TOKEN_OWNER, "TypeSOL: ${target.name} is not owned by ${owner}");`);
802
- this.created.add(target.name);
803
- this.pendingInit.delete(target.name);
804
- return result;
805
- }
806
- systemTransfer(node) {
807
- if (node.arguments.length !== 3)
808
- this.fail(node, "transfer(from, to, lamports) takes three arguments");
809
- const [fromN, toN, amtN] = node.arguments;
810
- const from = this.accountParam(fromN, "transfer's source");
811
- if (from.kind.kind !== "signer" || !from.kind.mut)
812
- this.fail(fromN, "the source must be a Mut<Signer>");
813
- const to = this.accountParam(toN, "transfer's destination");
814
- if (!isWritable(to.kind))
815
- this.fail(toN, "the destination must be writable (Mut<...>)");
816
- const amt = this.expect(this.expr(amtN, U64), U64, amtN);
817
- this.line(`TS_TRY(ts_system_transfer(params, a_${from.name}, a_${to.name}, ${amt.c}));`);
818
- return undefined;
819
- }
820
- /** systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?) */
821
- createAccount(node, system) {
822
- const a = node.arguments;
823
- if (a.length !== 5 && a.length !== 6)
824
- this.fail(node, "createAccount(payer, account, lamports, space, owner, signerSeeds?)");
825
- const payer = this.accountParam(a[0], "the payer");
826
- if (payer.kind.kind !== "signer" || !payer.kind.mut)
827
- this.fail(a[0], "the payer must be a Mut<Signer>");
828
- const acct = this.accountParam(a[1], "the new account");
829
- if (!isWritable(acct.kind))
830
- this.fail(a[1], "the new account must be writable (Mut<Signer> or Mut<AccountInfo>)");
831
- if (acct.kind.kind !== "signer" && a.length !== 6)
832
- this.fail(a[1], "the new account must sign: a Mut<Signer> keypair, or pass signerSeeds for a PDA");
833
- const { buf, len, put, finish } = this.byteBuffer("sys", 52, "TS_ERR_INSTRUCTION_DATA", "system instruction");
834
- const tag = this.tmp("tag");
835
- this.line(`uint32_t ${tag} = 0; /* CreateAccount */`);
836
- put(`&${tag}`, "4", 4);
837
- this.serialize(this.expect(this.expr(a[2], U64), U64, a[2]), a[2], put);
838
- this.serialize(this.expect(this.expr(a[3], U64), U64, a[3]), a[3], put);
839
- this.serialize(this.expect(this.expr(a[4], PUBKEY), PUBKEY, a[4]), a[4], put);
840
- finish(node);
841
- const seeds = a.length === 6 ? this.signingSeeds(a[5]) : { name: "NULL", count: 0 };
842
- this.cpi(`a_${system.name}`, [
843
- [`a_${payer.name}`, true, true],
844
- [`a_${acct.name}`, true, true],
845
- ], buf, len, seeds);
846
- return undefined;
847
- }
848
- /**
849
- * Emit a CPI to the program account `program` with these metas (account, writable, signer), and then (`tail`) a range
850
- * of the remaining accounts, read-only (a Merkle proof).
851
- */
852
- cpi(program, metas, buf, len, seeds, tail) {
853
- const m = this.tmp("metas");
854
- const fixed = metas.map(([acc, w, sg]) => `{&${acc}->key, ${w}, ${sg}}`).join(", ");
855
- if (!tail) {
856
- this.line(`SolAccountMeta ${m}[${metas.length}] = {${fixed}};`);
857
- this.line(`TS_TRY(ts_cpi(params, ${program}, ${buf}, ${len}, ${m}, ${metas.length}, ${seeds.name}, ${seeds.count}));`);
858
- return;
859
- }
860
- const n = this.ix.accounts.length;
861
- const cnt = this.tmp("nmetas");
862
- const i = this.tmp("ri");
863
- this.line(`if (${metas.length} + (${tail.to} - ${tail.from}) > TS_MAX_ACCOUNTS) TS_FAIL(TS_ERR_TOO_MANY_ACCOUNTS, "TypeSOL: the CPI lists more than ${MAX_ACCOUNTS} accounts");`);
864
- this.line(`SolAccountMeta ${m}[TS_MAX_ACCOUNTS] = {${fixed}};`);
865
- this.line(`uint64_t ${cnt} = ${metas.length};`);
866
- this.line(`for (uint64_t ${i} = ${n} + ${tail.from}; ${i} < ${n} + ${tail.to}; ${i}++) ${m}[${cnt}++] = (SolAccountMeta){&params->ka[${i}]->key, ${tail.asPassed ? `params->ka[${i}]->is_writable` : 0}, 0};`);
867
- this.line(`TS_TRY(ts_cpi(params, ${program}, ${buf}, ${len}, ${m}, ${cnt}, ${seeds.name}, ${seeds.count}));`);
868
- }
869
- signerSeeds(node, authority, at) {
870
- if (!node) {
871
- if (authority.kind.kind !== "signer")
872
- this.fail(at, "the authority must be a Signer, or pass signerSeeds for a PDA authority");
873
- return { name: "NULL", count: 0 };
874
- }
875
- return this.signingSeeds(node);
876
- }
877
- /** Seeds to sign a CPI with: an array literal, or a helper's SignerSeeds parameter. */
878
- signingSeeds(node) {
879
- if (ts.isIdentifier(node)) {
880
- const l = this.lookup(node.text);
881
- if (l?.type.kind === "signerSeeds")
882
- return { name: l.c, count: `${l.c}__n` };
883
- }
884
- return this.seeds(node, 0);
885
- }
886
- tokenOp(node, program, method) {
887
- const a = node.arguments;
888
- const p = `a_${program.name}`;
889
- const want = (n, kind, mut, what) => {
890
- const acct = this.accountParam(n, what);
891
- if (acct.kind.kind !== kind || (mut && !acct.kind.mut))
892
- this.fail(n, `${what} must be a ${mut ? "Mut<" : ""}${kind === "token" ? "TokenAccount" : "Mint"}${mut ? ">" : ""}`);
893
- return acct;
894
- };
895
- const arity = (fixed) => {
896
- if (a.length !== fixed && a.length !== fixed + 1)
897
- this.fail(node, `${method} takes ${fixed} arguments plus optional signerSeeds`);
898
- };
899
- const amount = (n) => this.expect(this.expr(n, U64), U64, n).c;
900
- switch (method) {
901
- case "transfer": {
902
- arity(4);
903
- const from = want(a[0], "token", true, "the source");
904
- const to = want(a[1], "token", true, "the destination");
905
- const auth = this.accountParam(a[2], "the authority");
906
- const amt = amount(a[3]);
907
- const s = this.signerSeeds(a[4], auth, a[2]);
908
- this.line(`TS_TRY(ts_token_transfer(params, ${p}, a_${from.name}, a_${to.name}, a_${auth.name}, ${amt}, ${s.name}, ${s.count}));`);
909
- return undefined;
910
- }
911
- case "transferChecked": {
912
- arity(5);
913
- const from = want(a[0], "token", true, "the source");
914
- const mint = want(a[1], "mint", false, "the mint");
915
- const to = want(a[2], "token", true, "the destination");
916
- const auth = this.accountParam(a[3], "the authority");
917
- const amt = amount(a[4]);
918
- const s = this.signerSeeds(a[5], auth, a[3]);
919
- this.line(`TS_TRY(ts_token_transfer_checked(params, ${p}, a_${from.name}, a_${mint.name}, a_${to.name}, a_${auth.name}, ${amt}, ${s.name}, ${s.count}));`);
920
- return undefined;
921
- }
922
- case "mintTo": {
923
- arity(4);
924
- // A Mut<Mint>, or a mint created and initialized earlier in this instruction (Mut<Signer> / Mut<AccountInfo>).
925
- const mint = this.accountParam(a[0], "the mint");
926
- if (!isWritable(mint.kind) || (mint.kind.kind !== "mint" && mint.kind.kind !== "signer" && mint.kind.kind !== "info"))
927
- this.fail(a[0], "the mint must be a Mut<Mint>, or a Mut<Signer> / Mut<AccountInfo> mint this instruction created");
928
- const to = want(a[1], "token", true, "the destination");
929
- const auth = this.accountParam(a[2], "the mint authority");
930
- const amt = amount(a[3]);
931
- const s = this.signerSeeds(a[4], auth, a[2]);
932
- this.line(`TS_TRY(ts_token_mint_to(params, ${p}, a_${mint.name}, a_${to.name}, a_${auth.name}, ${amt}, ${s.name}, ${s.count}));`);
933
- return undefined;
934
- }
935
- case "burn": {
936
- arity(4);
937
- const from = want(a[0], "token", true, "the burned account");
938
- const mint = want(a[1], "mint", true, "the mint");
939
- const auth = this.accountParam(a[2], "the authority");
940
- const amt = amount(a[3]);
941
- const s = this.signerSeeds(a[4], auth, a[2]);
942
- this.line(`TS_TRY(ts_token_burn(params, ${p}, a_${from.name}, a_${mint.name}, a_${auth.name}, ${amt}, ${s.name}, ${s.count}));`);
943
- return undefined;
944
- }
945
- case "initializeMetadata": {
946
- if (program.kind.kind === "tokenProgram" && program.kind.flavor === "token")
947
- this.fail(node, "metadata lives in Token-2022 mints; use Token2022Program or TokenInterface");
948
- if (a.length !== 6 && a.length !== 7)
949
- this.fail(node, "initializeMetadata(mint, updateAuthority, mintAuthority, name, symbol, uri, signerSeeds?)");
950
- // The mint may have been created and initialized earlier in this instruction (a Mut<Signer> or Mut<AccountInfo>).
951
- const mint = this.accountParam(a[0], "the mint");
952
- if (!isWritable(mint.kind))
953
- this.fail(a[0], "the mint must be writable (Mut<...>)");
954
- const ua = this.accountParam(a[1], "the update authority");
955
- const ma = this.accountParam(a[2], "the mint authority");
956
- const [nm, sym, uri] = [a[3], a[4], a[5]].map((n) => this.expect(this.expr(n, STRING), STRING, n).c);
957
- const s = this.signerSeeds(a[6], ma, a[2]);
958
- this.line(`TS_TRY(ts_t22_init_metadata(params, ${p}, a_${mint.name}, a_${ua.name}, a_${ma.name}, ${nm}, ${sym}, ${uri}, ${s.name}, ${s.count}));`);
959
- return undefined;
960
- }
961
- case "closeAccount": {
962
- arity(3);
963
- // A token account, or (Token-2022, with a MintCloseAuthority and no supply left) a mint.
964
- const acct = this.accountParam(a[0], "the closed account");
965
- if (!((acct.kind.kind === "token" || acct.kind.kind === "mint") && acct.kind.mut))
966
- this.fail(a[0], "the closed account must be a Mut<TokenAccount> or a Mut<Mint>");
967
- const dest = this.accountParam(a[1], "the destination");
968
- if (!isWritable(dest.kind))
969
- this.fail(a[1], "the destination must be writable (Mut<...>)");
970
- const auth = this.accountParam(a[2], "the authority");
971
- const s = this.signerSeeds(a[3], auth, a[2]);
972
- this.line(`TS_TRY(ts_token_close(params, ${p}, a_${acct.name}, a_${dest.name}, a_${auth.name}, ${s.name}, ${s.count}));`);
973
- return undefined;
974
- }
975
- }
976
- // The remaining SPL Token instructions share one shape: a tag, a few fixed fields, and fixed account metas.
977
- const anyAcct = (n, what, mut) => {
978
- const acct = this.accountParam(n, what);
979
- if (mut && !isWritable(acct.kind))
980
- this.fail(n, `${what} must be writable (Mut<...>)`);
981
- return acct;
982
- };
983
- const simple = (tag, fields, metas, seeds) => {
984
- const { buf, len, put, finish } = this.byteBuffer("tok", 128, "TS_ERR_INSTRUCTION_DATA", "token instruction");
985
- const t = this.tmp("tag");
986
- this.line(`uint8_t ${t} = ${tag};`);
987
- put(`&${t}`, "1", 1);
988
- for (const f of fields)
989
- f(put);
990
- finish(node);
991
- this.cpi(p, metas.map(([acc, w, sg]) => [`a_${acc.name}`, w, sg]), buf, len, seeds);
992
- };
993
- const value = (n, t) => (put) => this.serialize(this.expect(this.expr(n, t), t, n), n, put);
994
- const optKey = { kind: "option", inner: PUBKEY };
995
- const U16 = { kind: "int", name: "u16" };
996
- const I16 = { kind: "int", name: "i16" };
997
- const byte = (k) => (put) => {
998
- const t = this.tmp("b");
999
- this.line(`uint8_t ${t} = ${k};`);
1000
- put(`&${t}`, "1", 1);
1001
- };
1002
- /** Token-2022's OptionalNonZeroPubkey: 32 bytes, all zero for none. */
1003
- const nonZeroKey = (n) => (put) => {
1004
- this.model.options.set("pubkey", PUBKEY);
1005
- const v = this.expect(this.expr(n, optKey), optKey, n);
1006
- const t = this.tmp("nzk");
1007
- this.line(`SolPubkey ${t};`);
1008
- this.line(`{ ${optC(PUBKEY)} o = ${v.c}; if (o.some) ${t} = o.v; else ts_memzero(&${t}, 32); }`);
1009
- put(`&${t}`, "32", 32);
1010
- };
1011
- const token2022Only = () => {
1012
- if (program.kind.kind === "tokenProgram" && program.kind.flavor === "token")
1013
- this.fail(node, `${method} is a Token-2022 extension; use Token2022Program or TokenInterface`);
1014
- };
1015
- const mintOnly = (n, usage) => {
1016
- token2022Only();
1017
- if (a.length !== n)
1018
- this.fail(node, usage);
1019
- return anyAcct(a[0], "the mint", true);
1020
- };
1021
- const none = { name: "NULL", count: 0 };
1022
- switch (method) {
1023
- case "initializeTransferFeeConfig": {
1024
- const mint = mintOnly(5, "initializeTransferFeeConfig(mint, configAuthority | null, withdrawAuthority | null, basisPoints, maximumFee)");
1025
- this.model.options.set("pubkey", PUBKEY);
1026
- // Arguments in source order, as JS evaluates them: the basis points are checked when they are read.
1027
- const bps = (put) => {
1028
- const v = this.expect(this.expr(a[3], U16), U16, a[3]);
1029
- this.line(`if (${v.c} > 10000) TS_FAIL(TS_ERR_INSTRUCTION_DATA, "TypeSOL: transfer fee above 10000 basis points");`);
1030
- this.serialize(v, a[3], put);
1031
- };
1032
- simple(26, [byte(0), value(a[1], optKey), value(a[2], optKey), bps, value(a[4], U64)], [[mint, true, false]], none);
1033
- return undefined;
1034
- }
1035
- case "initializeMintCloseAuthority": {
1036
- const mint = mintOnly(2, "initializeMintCloseAuthority(mint, closeAuthority | null)");
1037
- this.model.options.set("pubkey", PUBKEY);
1038
- simple(25, [value(a[1], optKey)], [[mint, true, false]], none);
1039
- return undefined;
1040
- }
1041
- case "initializeNonTransferableMint": {
1042
- const mint = mintOnly(1, "initializeNonTransferableMint(mint)");
1043
- simple(32, [], [[mint, true, false]], none);
1044
- return undefined;
1045
- }
1046
- case "initializePermanentDelegate": {
1047
- const mint = mintOnly(2, "initializePermanentDelegate(mint, delegate)");
1048
- simple(35, [value(a[1], PUBKEY)], [[mint, true, false]], none);
1049
- return undefined;
1050
- }
1051
- case "initializeDefaultAccountState": {
1052
- const mint = mintOnly(2, "initializeDefaultAccountState(mint, frozen)");
1053
- const frozen = this.expect(this.expr(a[1], BOOL), BOOL, a[1]);
1054
- const st = this.tmp("st");
1055
- this.line(`uint8_t ${st} = (${frozen.c}) ? 2 : 1;`); // AccountState::Frozen / Initialized
1056
- simple(28, [byte(0), (put) => put(`&${st}`, "1", 1)], [[mint, true, false]], none);
1057
- return undefined;
1058
- }
1059
- case "initializeMetadataPointer":
1060
- case "initializeGroupPointer":
1061
- case "initializeGroupMemberPointer":
1062
- case "initializeTransferHook": {
1063
- const tag = { initializeMetadataPointer: 39, initializeGroupPointer: 40, initializeGroupMemberPointer: 41, initializeTransferHook: 36 }[method];
1064
- const second = {
1065
- initializeMetadataPointer: "metadataAddress",
1066
- initializeGroupPointer: "groupAddress",
1067
- initializeGroupMemberPointer: "memberAddress",
1068
- initializeTransferHook: "programId",
1069
- }[method];
1070
- const mint = mintOnly(3, `${method}(mint, authority | null, ${second} | null)`);
1071
- simple(tag, [byte(0), nonZeroKey(a[1]), nonZeroKey(a[2])], [[mint, true, false]], none);
1072
- return undefined;
1073
- }
1074
- case "initializeInterestBearingMint": {
1075
- const mint = mintOnly(3, "initializeInterestBearingMint(mint, rateAuthority | null, rate)");
1076
- simple(33, [byte(0), nonZeroKey(a[1]), value(a[2], I16)], [[mint, true, false]], none);
1077
- return undefined;
1078
- }
1079
- case "initializeImmutableOwner": {
1080
- token2022Only();
1081
- if (a.length !== 1)
1082
- this.fail(node, "initializeImmutableOwner(account)");
1083
- const acct = anyAcct(a[0], "the token account", true);
1084
- simple(22, [], [[acct, true, false]], none);
1085
- return undefined;
1086
- }
1087
- case "updateDefaultAccountState": {
1088
- token2022Only();
1089
- if (a.length !== 3 && a.length !== 4)
1090
- this.fail(node, "updateDefaultAccountState(mint, freezeAuthority, frozen, signerSeeds?)");
1091
- const mint = anyAcct(a[0], "the mint", true);
1092
- const auth = this.accountParam(a[1], "the freeze authority");
1093
- const frozen = this.expect(this.expr(a[2], BOOL), BOOL, a[2]);
1094
- const st = this.tmp("st");
1095
- this.line(`uint8_t ${st} = (${frozen.c}) ? 2 : 1;`);
1096
- simple(28, [byte(1), (put) => put(`&${st}`, "1", 1)], [
1097
- [mint, true, false],
1098
- [auth, false, true],
1099
- ], this.signerSeeds(a[3], auth, a[1]));
1100
- return undefined;
1101
- }
1102
- case "enableRequiredMemoTransfers":
1103
- case "disableRequiredMemoTransfers": {
1104
- token2022Only();
1105
- if (a.length !== 2 && a.length !== 3)
1106
- this.fail(node, `${method}(account, owner, signerSeeds?)`);
1107
- const acct = anyAcct(a[0], "the token account", true);
1108
- const owner = this.accountParam(a[1], "the owner");
1109
- simple(30, [byte(method === "enableRequiredMemoTransfers" ? 0 : 1)], [
1110
- [acct, true, false],
1111
- [owner, false, true],
1112
- ], this.signerSeeds(a[2], owner, a[1]));
1113
- return undefined;
1114
- }
1115
- case "updateTransferHook": {
1116
- token2022Only();
1117
- if (a.length !== 3 && a.length !== 4)
1118
- this.fail(node, "updateTransferHook(mint, authority, programId | null, signerSeeds?)");
1119
- const mint = anyAcct(a[0], "the mint", true);
1120
- const auth = this.accountParam(a[1], "the transfer hook authority");
1121
- simple(36, [byte(1), nonZeroKey(a[2])], [
1122
- [mint, true, false],
1123
- [auth, false, true],
1124
- ], this.signerSeeds(a[3], auth, a[1]));
1125
- return undefined;
1126
- }
1127
- case "updateInterestRate": {
1128
- token2022Only();
1129
- if (a.length !== 3 && a.length !== 4)
1130
- this.fail(node, "updateInterestRate(mint, rateAuthority, rate, signerSeeds?)");
1131
- const mint = anyAcct(a[0], "the mint", true);
1132
- const auth = this.accountParam(a[1], "the rate authority");
1133
- simple(33, [byte(1), value(a[2], I16)], [
1134
- [mint, true, false],
1135
- [auth, false, true],
1136
- ], this.signerSeeds(a[3], auth, a[1]));
1137
- return undefined;
1138
- }
1139
- case "transferCheckedWithFee": {
1140
- token2022Only();
1141
- if (a.length !== 6 && a.length !== 7)
1142
- this.fail(node, "transferCheckedWithFee(from, mint, to, authority, amount, fee, signerSeeds?)");
1143
- const from = want(a[0], "token", true, "the source");
1144
- const mint = want(a[1], "mint", false, "the mint");
1145
- const to = want(a[2], "token", true, "the destination");
1146
- const auth = this.accountParam(a[3], "the authority");
1147
- // The decimals are the mint's own (checked when the mint was), as transferChecked does.
1148
- const dec = (put) => {
1149
- const t = this.tmp("dec");
1150
- this.line(`uint8_t ${t} = a_${mint.name}->data[44];`);
1151
- put(`&${t}`, "1", 1);
1152
- };
1153
- simple(26, [byte(1), value(a[4], U64), dec, value(a[5], U64)], [
1154
- [from, true, false],
1155
- [mint, false, false],
1156
- [to, true, false],
1157
- [auth, false, true],
1158
- ], this.signerSeeds(a[6], auth, a[3]));
1159
- return undefined;
1160
- }
1161
- case "harvestWithheldTokensToMint": {
1162
- token2022Only();
1163
- if (a.length !== 2)
1164
- this.fail(node, "harvestWithheldTokensToMint(mint, sources): sources is remainingAccounts() or rest.slice(a, b)");
1165
- if (!this.ix)
1166
- this.fail(node, "harvestWithheldTokensToMint takes remaining accounts, so only instructions can call it");
1167
- const mint = anyAcct(a[0], "the mint", true);
1168
- const range = this.remainingRange(a[1]) ?? this.fail(a[1], "pass the source token accounts as remainingAccounts() or rest.slice(a, b)");
1169
- const { buf, len, put, finish } = this.byteBuffer("tok", 2, "TS_ERR_INSTRUCTION_DATA", "token instruction");
1170
- byte(26)(put);
1171
- byte(4)(put);
1172
- finish(node);
1173
- // The sources go as they were passed (Token-2022 skips any it cannot harvest from).
1174
- this.cpi(p, [[`a_${mint.name}`, true, false]], buf, len, none, { ...range, asPassed: true });
1175
- return undefined;
1176
- }
1177
- case "withdrawWithheldTokensFromMint": {
1178
- token2022Only();
1179
- if (a.length !== 3 && a.length !== 4)
1180
- this.fail(node, "withdrawWithheldTokensFromMint(mint, destination, authority, signerSeeds?)");
1181
- const mint = anyAcct(a[0], "the mint", true);
1182
- const dest = want(a[1], "token", true, "the destination");
1183
- const auth = this.accountParam(a[2], "the withdraw authority");
1184
- simple(26, [byte(2)], [
1185
- [mint, true, false],
1186
- [dest, true, false],
1187
- [auth, false, true],
1188
- ], this.signerSeeds(a[3], auth, a[2]));
1189
- return undefined;
1190
- }
1191
- case "setTransferFee": {
1192
- token2022Only();
1193
- if (a.length !== 4 && a.length !== 5)
1194
- this.fail(node, "setTransferFee(mint, configAuthority, basisPoints, maximumFee, signerSeeds?)");
1195
- const mint = anyAcct(a[0], "the mint", true);
1196
- const auth = this.accountParam(a[1], "the config authority");
1197
- const bps = (put) => {
1198
- const v = this.expect(this.expr(a[2], U16), U16, a[2]);
1199
- this.line(`if (${v.c} > 10000) TS_FAIL(TS_ERR_INSTRUCTION_DATA, "TypeSOL: transfer fee above 10000 basis points");`);
1200
- this.serialize(v, a[2], put);
1201
- };
1202
- simple(26, [byte(5), bps, value(a[3], U64)], [
1203
- [mint, true, false],
1204
- [auth, false, true],
1205
- ], this.signerSeeds(a[4], auth, a[1]));
1206
- return undefined;
1207
- }
1208
- case "updateMetadataField":
1209
- case "removeMetadataKey":
1210
- case "updateMetadataAuthority":
1211
- case "emitMetadata": {
1212
- token2022Only();
1213
- // The Token Metadata interface (spl-token-metadata-interface), served by Token-2022 for metadata in the mint.
1214
- const usage = {
1215
- updateMetadataField: "updateMetadataField(mint, updateAuthority, field, value, signerSeeds?)",
1216
- removeMetadataKey: "removeMetadataKey(mint, updateAuthority, key, idempotent, signerSeeds?)",
1217
- updateMetadataAuthority: "updateMetadataAuthority(mint, updateAuthority, newAuthority | null, signerSeeds?)",
1218
- emitMetadata: "emitMetadata(mint)",
1219
- }[method];
1220
- const fixedArgs = { updateMetadataField: 4, removeMetadataKey: 4, updateMetadataAuthority: 3, emitMetadata: 1 }[method];
1221
- if (a.length !== fixedArgs && (method === "emitMetadata" || a.length !== fixedArgs + 1))
1222
- this.fail(node, usage);
1223
- const disc = {
1224
- updateMetadataField: "dde9312db5cadcc8",
1225
- removeMetadataKey: "ea122038598d25b5",
1226
- updateMetadataAuthority: "d7e4a6e45464567b",
1227
- emitMetadata: "faa6b4fa0d0cb846",
1228
- }[method];
1229
- const mint = anyAcct(a[0], "the mint", method !== "emitMetadata");
1230
- const auth = method === "emitMetadata" ? undefined : this.accountParam(a[1], "the update authority");
1231
- const { buf, len, put, finish } = this.byteBuffer("tmd", 1232, "TS_ERR_INSTRUCTION_DATA", "token metadata instruction");
1232
- const d = this.tmp("disc");
1233
- this.line(`static const uint8_t ${d}[8] = ${cBytes([...Buffer.from(disc, "hex")])};`);
1234
- put(d, "8", 8);
1235
- if (method === "updateMetadataField") {
1236
- // Field: Name / Symbol / Uri for those names, otherwise Key(field), as the Token-2022 CLI reads them.
1237
- const f = this.expect(this.expr(a[2], STRING), STRING, a[2]);
1238
- const ft = this.tmp("field");
1239
- const tag = this.tmp("ftag");
1240
- this.line(`TS_Str ${ft} = ${f.c};`);
1241
- this.line(`uint8_t ${tag} = ts_str_eq(${ft}, ts_str((const uint8_t *)"name", 4)) ? 0 : ts_str_eq(${ft}, ts_str((const uint8_t *)"symbol", 6)) ? 1 : ts_str_eq(${ft}, ts_str((const uint8_t *)"uri", 3)) ? 2 : 3;`);
1242
- put(`&${tag}`, "1", 1);
1243
- const kl = this.tmp("klen");
1244
- this.line(`uint32_t ${kl} = (uint32_t)${ft}.len;`);
1245
- put(`&${kl}`, `(${tag} == 3 ? 4 : 0)`);
1246
- put(`${ft}.ptr`, `(${tag} == 3 ? ${ft}.len : 0)`);
1247
- this.serialize(this.expect(this.expr(a[3], STRING), STRING, a[3]), a[3], put);
1248
- }
1249
- else if (method === "removeMetadataKey") {
1250
- const key = this.expect(this.expr(a[2], STRING), STRING, a[2]);
1251
- const idem = this.expect(this.expr(a[3], BOOL), BOOL, a[3]);
1252
- const t = this.tmp("idem");
1253
- this.line(`uint8_t ${t} = (${idem.c}) ? 1 : 0;`);
1254
- put(`&${t}`, "1", 1);
1255
- this.serialize(key, a[2], put);
1256
- }
1257
- else if (method === "updateMetadataAuthority") {
1258
- nonZeroKey(a[2])(put);
1259
- }
1260
- else {
1261
- // start: None, end: None (the whole TokenMetadata as return data).
1262
- byte(0)(put);
1263
- byte(0)(put);
1264
- }
1265
- finish(node);
1266
- const seeds = auth ? this.signerSeeds(a[fixedArgs], auth, a[1]) : none;
1267
- this.cpi(p, auth
1268
- ? [
1269
- [`a_${mint.name}`, true, false],
1270
- [`a_${auth.name}`, false, true],
1271
- ]
1272
- : [[`a_${mint.name}`, false, false]], buf, len, seeds);
1273
- return undefined;
1274
- }
1275
- case "approve": {
1276
- arity(4);
1277
- const src = want(a[0], "token", true, "the source");
1278
- const delegate = this.accountParam(a[1], "the delegate");
1279
- const owner = this.accountParam(a[2], "the owner");
1280
- const s = this.signerSeeds(a[4], owner, a[2]);
1281
- const amt = value(a[3], U64);
1282
- simple(4, [amt], [
1283
- [src, true, false],
1284
- [delegate, false, false],
1285
- [owner, false, true],
1286
- ], s);
1287
- return undefined;
1288
- }
1289
- case "revoke": {
1290
- arity(2);
1291
- const src = want(a[0], "token", true, "the source");
1292
- const owner = this.accountParam(a[1], "the owner");
1293
- simple(5, [], [
1294
- [src, true, false],
1295
- [owner, false, true],
1296
- ], this.signerSeeds(a[2], owner, a[1]));
1297
- return undefined;
1298
- }
1299
- case "setAuthority": {
1300
- arity(4);
1301
- const target = anyAcct(a[0], "the mint or token account", true);
1302
- const current = this.accountParam(a[1], "the current authority");
1303
- this.model.options.set("pubkey", PUBKEY);
1304
- const s = this.signerSeeds(a[4], current, a[1]);
1305
- simple(6, [value(a[2], U8), value(a[3], optKey)], [
1306
- [target, true, false],
1307
- [current, false, true],
1308
- ], s);
1309
- return undefined;
1310
- }
1311
- case "freezeAccount":
1312
- case "thawAccount": {
1313
- arity(3);
1314
- const acct = want(a[0], "token", true, "the token account");
1315
- const mint = this.accountParam(a[1], "the mint");
1316
- const auth = this.accountParam(a[2], "the freeze authority");
1317
- simple(method === "freezeAccount" ? 10 : 11, [], [
1318
- [acct, true, false],
1319
- [mint, false, false],
1320
- [auth, false, true],
1321
- ], this.signerSeeds(a[3], auth, a[2]));
1322
- return undefined;
1323
- }
1324
- case "syncNative": {
1325
- if (a.length !== 1)
1326
- this.fail(node, "syncNative(account) takes the wrapped-SOL token account");
1327
- const acct = anyAcct(a[0], "the token account", true);
1328
- simple(17, [], [[acct, true, false]], { name: "NULL", count: 0 });
1329
- return undefined;
1330
- }
1331
- case "initializeMint2": {
1332
- if (a.length !== 4)
1333
- this.fail(node, "initializeMint2(mint, decimals, mintAuthority, freezeAuthority | null)");
1334
- const mint = anyAcct(a[0], "the mint", true);
1335
- this.model.options.set("pubkey", PUBKEY);
1336
- simple(20, [value(a[1], U8), value(a[2], PUBKEY), value(a[3], optKey)], [[mint, true, false]], { name: "NULL", count: 0 });
1337
- return undefined;
1338
- }
1339
- case "initializeAccount3": {
1340
- if (a.length !== 3)
1341
- this.fail(node, "initializeAccount3(account, mint, owner)");
1342
- const acct = anyAcct(a[0], "the token account", true);
1343
- const mint = this.accountParam(a[1], "the mint");
1344
- simple(18, [value(a[2], PUBKEY)], [
1345
- [acct, true, false],
1346
- [mint, false, false],
1347
- ], { name: "NULL", count: 0 });
1348
- return undefined;
1349
- }
1350
- }
1351
- this.fail(node.expression, `token programs support transfer, transferChecked, mintTo, burn, closeAccount, approve, revoke, setAuthority, freezeAccount, thawAccount, syncNative, initializeMint2, initializeAccount3, initializeMetadata, updateMetadataField, removeMetadataKey, updateMetadataAuthority, emitMetadata, the Token-2022 extension instructions (updateDefaultAccountState, updateTransferHook, enableRequiredMemoTransfers, disableRequiredMemoTransfers, updateInterestRate, transferCheckedWithFee, harvestWithheldTokensToMint, withdrawWithheldTokensFromMint, setTransferFee) and initializers (initializeTransferFeeConfig, initializeMintCloseAuthority, initializeNonTransferableMint, initializePermanentDelegate, initializeDefaultAccountState, initializeMetadataPointer, initializeGroupPointer, initializeGroupMemberPointer, initializeTransferHook, initializeInterestBearingMint, initializeImmutableOwner), not ${method}`);
1352
- }
1353
- ataOp(node, program, method) {
1354
- if (method !== "create" && method !== "createIdempotent")
1355
- this.fail(node.expression, "the Associated Token program supports create and createIdempotent");
1356
- const a = node.arguments;
1357
- if (a.length !== 6)
1358
- this.fail(node, `${method}(payer, ata, owner, mint, systemProgram, tokenProgram) takes six accounts`);
1359
- const payer = this.accountParam(a[0], "the payer");
1360
- if (payer.kind.kind !== "signer" || !payer.kind.mut)
1361
- this.fail(a[0], "the payer must be a Mut<Signer>");
1362
- const ata = this.accountParam(a[1], "the token account");
1363
- if (!isWritable(ata.kind))
1364
- this.fail(a[1], "the token account must be Mut<AccountInfo>");
1365
- const [owner, mint, sys, tp] = [a[2], a[3], a[4], a[5]].map((n, i) => this.accountParam(n, ["the owner", "the mint", "the system program", "the token program"][i]));
1366
- if (sys.kind.kind !== "system")
1367
- this.fail(a[4], "pass the SystemProgram parameter");
1368
- if (tp.kind.kind !== "tokenProgram")
1369
- this.fail(a[5], "pass a token program parameter");
1370
- this.line(`TS_TRY(ts_ata_create(params, a_${program.name}, a_${payer.name}, a_${ata.name}, a_${owner.name}, a_${mint.name}, a_${sys.name}, a_${tp.name}, ${method === "createIdempotent"}));`);
1371
- return undefined;
1372
- }
1373
- metadataOp(node, program, method) {
1374
- if (method === "createMasterEditionV3" || method === "verifyCollection")
1375
- return this.metadataCollectionOp(node, program, method);
1376
- if (method !== "createV3")
1377
- this.fail(node.expression, `the Token Metadata program supports createV3, createMasterEditionV3 and verifyCollection, not ${method}`);
1378
- const a = node.arguments;
1379
- const usage = "createV3(metadata, mint, mintAuthority, payer, updateAuthority, systemProgram, name, symbol, uri, sellerFeeBasisPoints, isMutable, { creators?, collection?, isCollection? }?, signerSeeds?)";
1380
- // An object literal after isMutable carries the optional creators / collection; signerSeeds stays last.
1381
- const extras = a[11] && ts.isObjectLiteralExpression(a[11]) ? a[11] : undefined;
1382
- const seedsArg = extras ? a[12] : a[11];
1383
- if (a.length < 11 || a.length > (extras ? 13 : 12))
1384
- this.fail(node, usage);
1385
- const [metadata, mint, mintAuth, payer, updateAuth, sys] = a.slice(0, 6).map((n, i) => this.accountParam(n, `account #${i + 1}`));
1386
- if (!isWritable(metadata.kind))
1387
- this.fail(a[0], "the metadata account must be Mut<AccountInfo>");
1388
- if (payer.kind.kind !== "signer" || !payer.kind.mut)
1389
- this.fail(a[3], "the payer must be a Mut<Signer>");
1390
- if (sys.kind.kind !== "system")
1391
- this.fail(a[5], "pass the SystemProgram parameter");
1392
- // Arguments in source order, as JS evaluates them: a later one that runs statements (a helper changing account
1393
- // text) must not change what an earlier one read.
1394
- const vals = [];
1395
- const inOrder = (n, t) => {
1396
- const mark = this.lines.length;
1397
- const v = this.expect(this.expr(n, t), t, n);
1398
- for (let j = 0; j < vals.length; j++)
1399
- vals[j] = this.settle(vals[j], mark);
1400
- vals.push(v);
1401
- return vals.length - 1;
1402
- };
1403
- const slots = [...a.slice(6, 9).map((n) => inOrder(n, STRING)), inOrder(a[9], { kind: "int", name: "u16" }), inOrder(a[10], BOOL)];
1404
- const settleAll = (mark) => {
1405
- for (let j = 0; j < vals.length; j++)
1406
- vals[j] = this.settle(vals[j], mark);
1407
- };
1408
- const extrasMark = this.lines.length;
1409
- let creators = "NULL";
1410
- let ncreators = "-1";
1411
- let collection = "NULL";
1412
- let sized = "false";
1413
- if (extras) {
1414
- for (const p of extras.properties) {
1415
- if (!ts.isPropertyAssignment(p) || !ts.isIdentifier(p.name))
1416
- this.fail(p, "use creators: [...], collection: key and isCollection: boolean");
1417
- if (p.name.text === "creators") {
1418
- if (!ts.isArrayLiteralExpression(p.initializer))
1419
- this.fail(p.initializer, "creators: [{ address, verified, share }, …] (an array literal)");
1420
- const list = p.initializer.elements;
1421
- if (list.length < 1 || list.length > 5)
1422
- this.fail(p.initializer, "Metaplex takes 1 to 5 creators");
1423
- const buf = this.tmp("creators");
1424
- this.line(`uint8_t ${buf}[${34 * list.length}];`);
1425
- let shares = 0n;
1426
- let constant = true;
1427
- list.forEach((el, i) => {
1428
- if (!ts.isObjectLiteralExpression(el))
1429
- this.fail(el, "a creator is { address, verified, share }");
1430
- const field = (k) => {
1431
- const q = el.properties.find((x) => ts.isPropertyAssignment(x) && ts.isIdentifier(x.name) && x.name.text === k);
1432
- const sh = el.properties.find((x) => ts.isShorthandPropertyAssignment(x) && x.name.text === k);
1433
- if (!q && !sh)
1434
- this.fail(el, `a creator needs ${k}`);
1435
- return q ? q.initializer : sh.name;
1436
- };
1437
- const at = 34 * i;
1438
- const key = this.expect(this.expr(field("address"), PUBKEY), PUBKEY, el);
1439
- this.line(`ts_memcpy(${buf} + ${at}, ${key.c}, 32);`);
1440
- const verified = this.expect(this.expr(field("verified"), BOOL), BOOL, el);
1441
- this.line(`${buf}[${at + 32}] = (${verified.c}) ? 1 : 0;`);
1442
- const shareNode = field("share");
1443
- if (ts.isBigIntLiteral(shareNode))
1444
- shares += BigInt(shareNode.text.slice(0, -1));
1445
- else
1446
- constant = false;
1447
- const share = this.expect(this.expr(shareNode, U8), U8, el);
1448
- this.line(`${buf}[${at + 33}] = (uint8_t)(${share.c});`);
1449
- });
1450
- if (constant && shares !== 100n)
1451
- this.fail(p.initializer, `creator shares add up to ${shares}; Metaplex requires 100`);
1452
- creators = buf;
1453
- ncreators = String(list.length);
1454
- }
1455
- else if (p.name.text === "collection") {
1456
- const key = this.expect(this.expr(p.initializer, PUBKEY), PUBKEY, p.initializer);
1457
- const t = this.tmp("coll");
1458
- this.line(`SolPubkey ${t} = *(${key.c});`);
1459
- collection = `&${t}`;
1460
- }
1461
- else if (p.name.text === "isCollection") {
1462
- const v = this.expect(this.expr(p.initializer, BOOL), BOOL, p.initializer);
1463
- const t = this.tmp("sized");
1464
- this.line(`bool ${t} = ${v.c};`);
1465
- sized = t;
1466
- }
1467
- else
1468
- this.fail(p.name, `createV3 extras are creators, collection and isCollection, not ${p.name.text}`);
1469
- }
1470
- }
1471
- const seeds = this.signerSeeds(seedsArg, mintAuth, a[2]);
1472
- settleAll(extrasMark);
1473
- const [name, symbol, uri, fee, mutable] = slots.map((i) => vals[i]);
1474
- 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}));`);
1475
- return undefined;
1476
- }
1477
- /** CreateMasterEditionV3 (17) and Verify (52) with VerificationArgs::CollectionV1. */
1478
- metadataCollectionOp(node, program, method) {
1479
- const a = node.arguments;
1480
- const p = `a_${program.name}`;
1481
- const seedsAt = (i) => (a[i] ? this.signingSeeds(a[i]) : { name: "NULL", count: 0 });
1482
- const acct = (i, what, w, s) => {
1483
- if (a[i].kind === ts.SyntaxKind.NullKeyword)
1484
- this.fail(a[i], `pass ${what}`);
1485
- return this.mplMeta(a[i], program, what, w, s);
1486
- };
1487
- if (method === "createMasterEditionV3") {
1488
- if (a.length !== 9 && a.length !== 10)
1489
- this.fail(node, "createMasterEditionV3(edition, mint, updateAuthority, mintAuthority, payer, metadata, tokenProgram, systemProgram, maxSupply | null, signerSeeds?)");
1490
- const metas = [
1491
- acct(0, "the edition", true, false),
1492
- acct(1, "the mint", true, false),
1493
- acct(2, "the update authority", false, true),
1494
- acct(3, "the mint authority", false, true),
1495
- acct(4, "the payer", true, true),
1496
- acct(5, "the metadata", true, false),
1497
- acct(6, "the token program", false, false),
1498
- acct(7, "the system program", false, false),
1499
- ];
1500
- // max_supply: Option<u64>; Some(0) makes a one of one, None allows unlimited prints.
1501
- 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" } }]);
1502
- this.cpi(p, metas, data.buf, data.len, seedsAt(9));
1503
- return undefined;
1504
- }
1505
- // Verify: authority, delegate record (absent: the program id), metadata, collection mint, collection metadata,
1506
- // collection master edition, system program, instructions sysvar.
1507
- if (a.length !== 7 && a.length !== 8)
1508
- this.fail(node, "verifyCollection(authority, metadata, collectionMint, collectionMetadata, collectionMasterEdition, systemProgram, instructionsSysvar, signerSeeds?)");
1509
- const metas = [
1510
- acct(0, "the collection authority", false, true),
1511
- [p, false, false],
1512
- acct(1, "the metadata", true, false),
1513
- acct(2, "the collection mint", false, false),
1514
- acct(3, "the collection metadata", true, false),
1515
- acct(4, "the collection master edition", false, false),
1516
- acct(5, "the system program", false, false),
1517
- acct(6, "the instructions sysvar", false, false),
1518
- ];
1519
- const data = this.mplData(node, 8, [{ bytes: [52, 1] }]);
1520
- this.cpi(p, metas, data.buf, data.len, seedsAt(7));
1521
- return undefined;
1522
- }
1523
- /**
1524
- * One account of a Metaplex CPI: an account parameter, or `null` for an optional account left out
1525
- * (Metaplex programs take their own id in its place).
1526
- */
1527
- mplMeta(n, program, what, writable, signer) {
1528
- if (n.kind === ts.SyntaxKind.NullKeyword)
1529
- return [`a_${program.name}`, false, false];
1530
- const acct = this.accountParam(n, what);
1531
- if (writable && !isWritable(acct.kind))
1532
- this.fail(n, `${what} must be writable (Mut<...>)`);
1533
- return [`a_${acct.name}`, writable, signer];
1534
- }
1535
- /** Borsh fields into a fresh buffer: raw bytes ("u8:N" style) or lowered values. */
1536
- mplData(at, max, fields) {
1537
- const { buf, len, put, finish } = this.byteBuffer("mpl", max, "TS_ERR_INSTRUCTION_DATA", "Metaplex instruction");
1538
- for (const f of fields) {
1539
- if ("bytes" in f) {
1540
- const name = this.tmp("bytes");
1541
- this.line(`static const uint8_t ${name}[${f.bytes.length}] = ${cBytes(f.bytes)};`);
1542
- put(name, String(f.bytes.length), f.bytes.length);
1543
- }
1544
- else if ("c" in f)
1545
- put(f.c, f.n);
1546
- else
1547
- this.serialize(this.expect(this.expr(f.value, f.type), f.type, f.value), f.value, put);
1548
- }
1549
- finish(at);
1550
- return { buf, len };
1551
- }
1552
- /**
1553
- * Borsh of one Metaplex Core plugin literal (`{ kind: "FreezeDelegate", frozen: true, authority?: … }`): the Plugin
1554
- * enum, then (`withAuthority`) the Option<PluginAuthority> that CreateV1's PluginAuthorityPair and AddPluginV1 take.
1555
- */
1556
- corePlugin(n, withAuthority) {
1557
- if (!ts.isObjectLiteralExpression(n))
1558
- this.fail(n, 'a Core plugin is an object literal: { kind: "FreezeDelegate", frozen: false }');
1559
- const props = new Map();
1560
- for (const q of n.properties) {
1561
- if (ts.isPropertyAssignment(q) && ts.isIdentifier(q.name))
1562
- props.set(q.name.text, q.initializer);
1563
- else if (ts.isShorthandPropertyAssignment(q))
1564
- props.set(q.name.text, q.name);
1565
- else
1566
- this.fail(q, "write plugin fields as name: value");
1567
- }
1568
- const kindNode = props.get("kind");
1569
- if (!kindNode || !ts.isStringLiteral(kindNode))
1570
- this.fail(n, 'a Core plugin needs kind: "Royalties" | "FreezeDelegate" | …');
1571
- const kind = kindNode.text;
1572
- const index = CORE_PLUGINS.indexOf(kind);
1573
- if (index < 0)
1574
- this.fail(kindNode, `Core plugins are ${CORE_PLUGINS.join(", ")}`);
1575
- if (kind === "Groups")
1576
- this.fail(kindNode, "Groups is kept by Core's group instructions (AddCollectionsToGroupV1 …), not set as a plugin");
1577
- const known = new Set(["kind", "authority", ...(CORE_PLUGIN_FIELDS[kind] ?? [])]);
1578
- for (const [k, v] of props)
1579
- if (!known.has(k))
1580
- this.fail(v, `${kind} has no field ${k}`);
1581
- const need = (k) => props.get(k) ?? this.fail(n, `${kind} needs ${k}`);
1582
- const list = (k, max) => {
1583
- const e = need(k);
1584
- if (!ts.isArrayLiteralExpression(e))
1585
- this.fail(e, `${k} is an array literal`);
1586
- if (e.elements.length > max)
1587
- this.fail(e, `at most ${max} entries in ${k}`);
1588
- return e.elements;
1589
- };
1590
- const u32 = (x) => [x & 0xff, (x >> 8) & 0xff, (x >> 16) & 0xff, x >>> 24];
1591
- const fields = [{ bytes: [index] }];
1592
- switch (kind) {
1593
- case "Royalties": {
1594
- const bps = need("basisPoints");
1595
- if (ts.isBigIntLiteral(bps) && BigInt(bps.text.slice(0, -1)) > 10000n)
1596
- this.fail(bps, "basisPoints is at most 10000 (100%)");
1597
- fields.push({ value: bps, type: { kind: "int", name: "u16" } });
1598
- const creators = list("creators", 5);
1599
- fields.push({ bytes: u32(creators.length) });
1600
- let sum = 0n;
1601
- let constant = true;
1602
- for (const c of creators) {
1603
- if (!ts.isObjectLiteralExpression(c))
1604
- this.fail(c, "a creator is { address, percentage }");
1605
- const get = (k) => {
1606
- const q = c.properties.find((x) => (ts.isPropertyAssignment(x) || ts.isShorthandPropertyAssignment(x)) && ts.isIdentifier(x.name) && x.name.text === k);
1607
- if (!q)
1608
- this.fail(c, `a creator needs ${k}`);
1609
- return ts.isPropertyAssignment(q) ? q.initializer : q.name;
1610
- };
1611
- const pct = get("percentage");
1612
- if (ts.isBigIntLiteral(pct))
1613
- sum += BigInt(pct.text.slice(0, -1));
1614
- else
1615
- constant = false;
1616
- fields.push({ value: get("address"), type: PUBKEY }, { value: pct, type: U8 });
1617
- }
1618
- if (constant && creators.length && sum !== 100n)
1619
- this.fail(need("creators"), `creator percentages add up to ${sum}; Core requires 100`);
1620
- // rule_set: None, or { programAllowList: [...] } / { programDenyList: [...] }
1621
- const rs = props.get("ruleSet");
1622
- if (!rs)
1623
- fields.push({ bytes: [0] });
1624
- else {
1625
- const pick = ts.isObjectLiteralExpression(rs) && rs.properties.length === 1 ? rs.properties[0] : undefined;
1626
- const which = pick && ts.isPropertyAssignment(pick) && ts.isIdentifier(pick.name) ? pick.name.text : undefined;
1627
- if (!pick ||
1628
- (which !== "programAllowList" && which !== "programDenyList") ||
1629
- !ts.isArrayLiteralExpression(pick.initializer))
1630
- this.fail(rs, "ruleSet is { programAllowList: [programs] } or { programDenyList: [programs] }");
1631
- const progs = pick.initializer.elements;
1632
- if (progs.length > 16)
1633
- this.fail(rs, "at most 16 programs in a rule set");
1634
- fields.push({ bytes: [which === "programAllowList" ? 1 : 2, ...u32(progs.length)] }, ...progs.map((k) => ({ value: k, type: PUBKEY })));
1635
- }
1636
- break;
1637
- }
1638
- case "MasterEdition": {
1639
- // Option<u32>, Option<String>, Option<String>: left out or null is None.
1640
- const opt = (k, t) => {
1641
- const v = props.get(k);
1642
- return !v || v.kind === ts.SyntaxKind.NullKeyword ? [{ bytes: [0] }] : [{ bytes: [1] }, { value: v, type: t }];
1643
- };
1644
- fields.push(...opt("maxSupply", { kind: "int", name: "u32" }), ...opt("name", STRING), ...opt("uri", STRING));
1645
- break;
1646
- }
1647
- case "VerifiedCreators":
1648
- case "Autograph": {
1649
- const sigs = list("signatures", 16);
1650
- fields.push({ bytes: u32(sigs.length) });
1651
- const second = kind === "VerifiedCreators" ? "verified" : "message";
1652
- for (const sg of sigs) {
1653
- if (!ts.isObjectLiteralExpression(sg))
1654
- this.fail(sg, `a signature is { address, ${second} }`);
1655
- const get = (k) => {
1656
- const q = sg.properties.find((x) => (ts.isPropertyAssignment(x) || ts.isShorthandPropertyAssignment(x)) && ts.isIdentifier(x.name) && x.name.text === k);
1657
- if (!q)
1658
- this.fail(sg, `a signature needs ${k}`);
1659
- return ts.isPropertyAssignment(q) ? q.initializer : q.name;
1660
- };
1661
- fields.push({ value: get("address"), type: PUBKEY }, { value: get(second), type: kind === "VerifiedCreators" ? BOOL : STRING });
1662
- }
1663
- break;
1664
- }
1665
- case "FreezeExecute":
1666
- case "PermanentFreezeExecute":
1667
- fields.push({ value: need("frozen"), type: BOOL });
1668
- break;
1669
- case "FreezeDelegate":
1670
- case "PermanentFreezeDelegate":
1671
- fields.push({ value: need("frozen"), type: BOOL });
1672
- break;
1673
- case "UpdateDelegate": {
1674
- const keys = props.has("additionalDelegates") ? list("additionalDelegates", 8) : [];
1675
- fields.push({ bytes: u32(keys.length) }, ...keys.map((k) => ({ value: k, type: PUBKEY })));
1676
- break;
1677
- }
1678
- case "Attributes": {
1679
- const attrs = list("attributes", 32);
1680
- fields.push({ bytes: u32(attrs.length) });
1681
- for (const at of attrs) {
1682
- if (!ts.isObjectLiteralExpression(at))
1683
- this.fail(at, "an attribute is { key, value }");
1684
- for (const k of ["key", "value"]) {
1685
- const q = at.properties.find((x) => (ts.isPropertyAssignment(x) || ts.isShorthandPropertyAssignment(x)) && ts.isIdentifier(x.name) && x.name.text === k);
1686
- if (!q)
1687
- this.fail(at, `an attribute needs ${k}`);
1688
- fields.push({ value: ts.isPropertyAssignment(q) ? q.initializer : q.name, type: STRING });
1689
- }
1690
- }
1691
- break;
1692
- }
1693
- case "Edition":
1694
- fields.push({ value: need("number"), type: { kind: "int", name: "u32" } });
1695
- break;
1696
- }
1697
- const auth = props.get("authority");
1698
- if (!withAuthority) {
1699
- if (auth)
1700
- this.fail(auth, "a plugin's authority is set when it is added; change it with Core's approve / revoke");
1701
- return fields;
1702
- }
1703
- if (!auth)
1704
- fields.push({ bytes: [0] }); // the plugin type's default authority
1705
- else if (ts.isStringLiteral(auth)) {
1706
- const i = ["none", "owner", "updateAuthority"].indexOf(auth.text);
1707
- if (i < 0)
1708
- this.fail(auth, 'authority is "none", "owner", "updateAuthority" or a Pubkey');
1709
- fields.push({ bytes: [1, i] });
1710
- }
1711
- else
1712
- fields.push({ bytes: [1, 3] }, { value: auth, type: PUBKEY });
1713
- return fields;
1714
- }
1715
- /** CreateV1 / CreateCollectionV1 plugins: Option<Vec<PluginAuthorityPair>>. */
1716
- corePluginList(n) {
1717
- if (!n)
1718
- return [{ bytes: [0] }];
1719
- const els = n.elements;
1720
- if (els.length > 16)
1721
- this.fail(n, "at most 16 plugins");
1722
- const kinds = els.map((e) => ts.isObjectLiteralExpression(e) ? e.properties.find((q) => q.name && ts.isIdentifier(q.name) && q.name.text === "kind") : undefined);
1723
- const seen = new Set();
1724
- kinds.forEach((k, i) => {
1725
- const lit = k && ts.isPropertyAssignment(k) && ts.isStringLiteral(k.initializer) ? k.initializer.text : undefined;
1726
- if (lit && seen.has(lit))
1727
- this.fail(els[i], `${lit} is listed twice; an asset has one plugin of each kind`);
1728
- if (lit)
1729
- seen.add(lit);
1730
- });
1731
- return [{ bytes: [1, els.length & 0xff, 0, 0, 0] }, ...els.flatMap((e) => this.corePlugin(e, true))];
1732
- }
1733
- /**
1734
- * Metaplex Core: assets and collections (with plugins), plugins and external plugin adapters added, updated, written
1735
- * and removed, transfer and burn. Each method is a row of CORE_OPS below: its accounts in order, its data.
1736
- */
1737
- coreOp(node, core, method) {
1738
- const a = node.arguments;
1739
- const p = `a_${core.name}`;
1740
- const op = this.coreOps()[method];
1741
- if (!op)
1742
- this.fail(node.expression, `Metaplex Core supports createAsset, createCollection, addPlugin, updatePlugin, removePlugin, addExternalPlugin, removeExternalPlugin, writeExternalPluginData (and the Collection forms), transferAsset and burnAsset, not ${method}`);
1743
- // An array literal of object literals right after the fixed arguments is the plugin list; the signer seeds follow.
1744
- const isPlugins = (n) => !!n && ts.isArrayLiteralExpression(n) && (n.elements.length === 0 || n.elements.every((e) => ts.isObjectLiteralExpression(e)));
1745
- const list = op.plugins && isPlugins(a[op.args]) ? a[op.args] : undefined;
1746
- const seedsAt = op.args + (list ? 1 : 0);
1747
- if (op.plugins ? a.length < op.args || a.length > seedsAt + 1 : a.length !== op.args && a.length !== op.args + 1)
1748
- this.fail(node, op.usage(method));
1749
- const metas = op.metas.map((m) => (m === "self" ? [p, false, false] : this.mplMeta(a[m[0]], core, m[1], m[2], m[3])));
1750
- const data = this.mplData(node, op.max, op.data(a, list));
1751
- this.cpi(p, metas, data.buf, data.len, a[seedsAt] ? this.signingSeeds(a[seedsAt]) : { name: "NULL", count: 0 });
1752
- return undefined;
1753
- }
1754
- /**
1755
- * Core instructions: `args` fixed arguments (then an optional plugin list when `plugins`, then optional signer
1756
- * seeds), accounts in order (`[argument, label, writable, signer]`, or "self": the Core program, Core's "none" for an
1757
- * optional account), at most `max` bytes of data.
1758
- */
1759
- coreOps() {
1760
- const str = (n) => ({ value: n, type: STRING });
1761
- const asset = [0, "the asset", true, false];
1762
- const assetPlugin = {
1763
- usage: (m) => `${m}(asset, collection | null, payer, authority | null, systemProgram, ${m === "removePlugin" ? "kind" : "plugin"}, signerSeeds?)`,
1764
- args: 6,
1765
- // Add/Remove/UpdatePluginV1: asset, collection, payer, authority, systemProgram, logWrapper.
1766
- metas: [
1767
- asset,
1768
- [1, "the collection", true, false],
1769
- [2, "the payer", true, true],
1770
- [3, "the authority", false, true],
1771
- [4, "the system program", false, false],
1772
- "self",
1773
- ],
1774
- max: 2048,
1775
- };
1776
- const collectionPlugin = {
1777
- usage: (m) => `${m}(collection, payer, authority | null, systemProgram, ${m === "removeCollectionPlugin" ? "kind" : "plugin"}, signerSeeds?)`,
1778
- args: 5,
1779
- // Add/Remove/UpdateCollectionPluginV1: collection, payer, authority, systemProgram, logWrapper.
1780
- metas: [
1781
- [0, "the collection", true, false],
1782
- [1, "the payer", true, true],
1783
- [2, "the authority", false, true],
1784
- [3, "the system program", false, false],
1785
- "self",
1786
- ],
1787
- max: 2048,
1788
- };
1789
- const assetPluginOp = (method, disc) => ({
1790
- ...assetPlugin,
1791
- data: (a) => [
1792
- { bytes: [disc] },
1793
- ...(method === "removePlugin" ? [this.corePluginType(a[5])] : this.corePlugin(a[5], method === "addPlugin")),
1794
- ],
1795
- });
1796
- const collectionPluginOp = (method, disc) => ({
1797
- ...collectionPlugin,
1798
- data: (a) => [
1799
- { bytes: [disc] },
1800
- ...(method === "removeCollectionPlugin" ? [this.corePluginType(a[4])] : this.corePlugin(a[4], method === "addCollectionPlugin")),
1801
- ],
1802
- });
1803
- // Add/RemoveExternalPluginAdapterV1: asset, collection, payer, authority, systemProgram, logWrapper; the write has a
1804
- // buffer account (left out: the data is in the instruction) before systemProgram. The Collection forms drop the asset.
1805
- const external = (method, disc, collection) => {
1806
- const write = method.startsWith("write");
1807
- const add = method.startsWith("add");
1808
- const n = (collection ? 5 : 6) + (write ? 1 : 0);
1809
- const at = collection ? 4 : 5;
1810
- const head = collection ? "collection, payer, authority | null, systemProgram" : "asset, collection | null, payer, authority | null, systemProgram";
1811
- const metas = collection
1812
- ? [
1813
- [0, "the collection", true, false],
1814
- [1, "the payer", true, true],
1815
- [2, "the authority", false, true],
1816
- ]
1817
- : [asset, [1, "the collection", true, false], [2, "the payer", true, true], [3, "the authority", false, true]];
1818
- if (write)
1819
- metas.push("self");
1820
- metas.push([collection ? 3 : 4, "the system program", false, false], "self");
1821
- return {
1822
- usage: (m) => `${m}(${head}, ${add ? "plugin" : write ? "key, data" : "key"}, signerSeeds?)`,
1823
- args: n,
1824
- metas,
1825
- max: 1024,
1826
- data: (a) => [
1827
- { bytes: [disc] },
1828
- ...(add
1829
- ? this.coreExternalPlugin(a[at])
1830
- : write
1831
- ? [...this.coreExternalKey(a[at]), ...this.coreExternalData(a[at + 1])]
1832
- : this.coreExternalKey(a[at])),
1833
- ],
1834
- };
1835
- };
1836
- return {
1837
- createAsset: {
1838
- usage: () => "createAsset(asset, collection | null, authority | null, payer, owner | null, systemProgram, name, uri, plugins?, signerSeeds?)",
1839
- args: 8,
1840
- plugins: true,
1841
- // CreateV1: asset, collection, authority, payer, owner, updateAuthority (the collection's, or the payer by
1842
- // default), systemProgram, logWrapper.
1843
- metas: [
1844
- [0, "the asset", true, true],
1845
- [1, "the collection", true, false],
1846
- [2, "the collection authority", false, true],
1847
- [3, "the payer", true, true],
1848
- [4, "the owner", false, false],
1849
- "self",
1850
- [5, "the system program", false, false],
1851
- "self",
1852
- ],
1853
- max: 2048,
1854
- data: (a, plugins) => [{ bytes: [0, 0] }, str(a[6]), str(a[7]), ...this.corePluginList(plugins)],
1855
- },
1856
- createCollection: {
1857
- usage: () => "createCollection(collection, updateAuthority | null, payer, systemProgram, name, uri, plugins?, signerSeeds?)",
1858
- args: 6,
1859
- plugins: true,
1860
- // CreateCollectionV1: collection, updateAuthority, payer, systemProgram.
1861
- metas: [
1862
- [0, "the collection", true, true],
1863
- [1, "the update authority", false, false],
1864
- [2, "the payer", true, true],
1865
- [3, "the system program", false, false],
1866
- ],
1867
- max: 2048,
1868
- data: (a, plugins) => [{ bytes: [1] }, str(a[4]), str(a[5]), ...this.corePluginList(plugins)],
1869
- },
1870
- addPlugin: assetPluginOp("addPlugin", 2),
1871
- removePlugin: assetPluginOp("removePlugin", 4),
1872
- updatePlugin: assetPluginOp("updatePlugin", 6),
1873
- addCollectionPlugin: collectionPluginOp("addCollectionPlugin", 3),
1874
- removeCollectionPlugin: collectionPluginOp("removeCollectionPlugin", 5),
1875
- updateCollectionPlugin: collectionPluginOp("updateCollectionPlugin", 7),
1876
- transferAsset: {
1877
- usage: () => "transferAsset(asset, collection | null, payer, authority | null, newOwner, signerSeeds?)",
1878
- args: 5,
1879
- // TransferV1: asset, collection, payer, authority, newOwner, systemProgram, logWrapper.
1880
- metas: [
1881
- asset,
1882
- [1, "the collection", false, false],
1883
- [2, "the payer", true, true],
1884
- [3, "the authority", false, true],
1885
- [4, "the new owner", false, false],
1886
- "self",
1887
- "self",
1888
- ],
1889
- max: 8,
1890
- data: () => [{ bytes: [14, 0] }],
1891
- },
1892
- burnAsset: {
1893
- usage: () => "burnAsset(asset, collection | null, payer, authority | null, signerSeeds?)",
1894
- args: 4,
1895
- // BurnV1: asset, collection, payer, authority, systemProgram, logWrapper.
1896
- metas: [asset, [1, "the collection", true, false], [2, "the payer", true, true], [3, "the authority", false, true], "self", "self"],
1897
- max: 8,
1898
- data: () => [{ bytes: [12, 0] }],
1899
- },
1900
- addExternalPlugin: external("addExternalPlugin", 22, false),
1901
- removeExternalPlugin: external("removeExternalPlugin", 24, false),
1902
- writeExternalPluginData: external("writeExternalPluginData", 28, false),
1903
- addCollectionExternalPlugin: external("addCollectionExternalPlugin", 23, true),
1904
- removeCollectionExternalPlugin: external("removeCollectionExternalPlugin", 25, true),
1905
- writeCollectionExternalPluginData: external("writeCollectionExternalPluginData", 29, true),
1906
- };
1907
- }
1908
- /** The fields of a Core object literal (`{ kind: "AppData", … }`) by name. */
1909
- coreProps(node, what) {
1910
- let n = node;
1911
- while (ts.isParenthesizedExpression(n) || ts.isAsExpression(n) || ts.isSatisfiesExpression(n))
1912
- n = n.expression;
1913
- if (!ts.isObjectLiteralExpression(n))
1914
- this.fail(n, `${what} is an object literal: { kind: "…", … }`);
1915
- const props = new Map();
1916
- for (const q of n.properties) {
1917
- if (ts.isPropertyAssignment(q) && ts.isIdentifier(q.name))
1918
- props.set(q.name.text, q.initializer);
1919
- else if (ts.isShorthandPropertyAssignment(q))
1920
- props.set(q.name.text, q.name);
1921
- else
1922
- this.fail(q, "write the fields as name: value");
1923
- }
1924
- return props;
1925
- }
1926
- /** PluginAuthority: "none" | "owner" | "updateAuthority" (literals), or an address. */
1927
- coreAuthority(n) {
1928
- if (ts.isStringLiteral(n)) {
1929
- const i = ["none", "owner", "updateAuthority"].indexOf(n.text);
1930
- if (i < 0)
1931
- this.fail(n, 'an authority is "none", "owner", "updateAuthority" or a Pubkey');
1932
- return [{ bytes: [i] }];
1933
- }
1934
- return [{ bytes: [3] }, { value: n, type: PUBKEY }];
1935
- }
1936
- coreOption(n, inner) {
1937
- return n ? [{ bytes: [1] }, ...inner(n)] : [{ bytes: [0] }];
1938
- }
1939
- coreSchema(n) {
1940
- const i = ts.isStringLiteral(n) ? ["binary", "json", "msgpack"].indexOf(n.text) : -1;
1941
- if (i < 0)
1942
- this.fail(n, 'schema is "binary", "json" or "msgpack"');
1943
- return [{ bytes: [i] }];
1944
- }
1945
- /** Vec<(HookableLifecycleEvent, ExternalCheckResult)>: `[{ event: "transfer", canReject: true }, …]`. */
1946
- coreChecks(n, at) {
1947
- if (!n || !ts.isArrayLiteralExpression(n))
1948
- this.fail(n ?? at, 'checks is a list: [{ event: "transfer", canApprove: true, canReject: true }]');
1949
- const out = [{ bytes: [n.elements.length & 0xff, 0, 0, 0] }];
1950
- for (const e of n.elements) {
1951
- const p = this.coreProps(e, "a lifecycle check");
1952
- const ev = p.get("event");
1953
- const i = ev && ts.isStringLiteral(ev) ? ["create", "transfer", "burn", "update", "execute"].indexOf(ev.text) : -1;
1954
- if (i < 0)
1955
- this.fail(ev ?? e, 'event is "create", "transfer", "burn", "update" or "execute"');
1956
- let flags = 0;
1957
- for (const [k, bit] of [
1958
- ["canListen", 1],
1959
- ["canApprove", 2],
1960
- ["canReject", 4],
1961
- ]) {
1962
- const v = p.get(k);
1963
- if (v && v.kind !== ts.SyntaxKind.TrueKeyword && v.kind !== ts.SyntaxKind.FalseKeyword)
1964
- this.fail(v, `${k} is true or false`);
1965
- if (v?.kind === ts.SyntaxKind.TrueKeyword)
1966
- flags |= bit;
1967
- }
1968
- for (const k of p.keys())
1969
- if (!["event", "canListen", "canApprove", "canReject"].includes(k))
1970
- this.fail(e, `a lifecycle check has event, canListen, canApprove and canReject, not ${k}`);
1971
- out.push({ bytes: [i, flags, 0, 0, 0] });
1972
- }
1973
- return out;
1974
- }
1975
- /** ExtraAccount: `{ kind: "address", address, isSigner?, isWritable? }` or a preconfigured one (`{ kind: "owner" }`, …). */
1976
- coreExtraAccount(n) {
1977
- const p = this.coreProps(n, "an extra account");
1978
- const kind = p.get("kind");
1979
- const kinds = ["program", "collection", "owner", "recipient", "asset", "customPda", "address"];
1980
- const i = kind && ts.isStringLiteral(kind) ? kinds.indexOf(kind.text) : -1;
1981
- if (i < 0 || i === 5)
1982
- this.fail(kind ?? n, 'an extra account is { kind: "address", address } or "program", "collection", "owner", "recipient", "asset"');
1983
- const flag = (k) => {
1984
- const v = p.get(k);
1985
- if (v && v.kind !== ts.SyntaxKind.TrueKeyword && v.kind !== ts.SyntaxKind.FalseKeyword)
1986
- this.fail(v, `${k} is true or false`);
1987
- return v?.kind === ts.SyntaxKind.TrueKeyword ? 1 : 0;
1988
- };
1989
- if (i === 6) {
1990
- const addr = p.get("address");
1991
- if (!addr)
1992
- this.fail(n, "an address extra account needs address");
1993
- return [{ bytes: [6] }, { value: addr, type: PUBKEY }, { bytes: [flag("isSigner"), flag("isWritable")] }];
1994
- }
1995
- return [{ bytes: [i, flag("isSigner"), flag("isWritable")] }];
1996
- }
1997
- /**
1998
- * ExternalPluginAdapterInitInfo from a literal: `{ kind: "AppData", dataAuthority, schema? }`, `{ kind: "Oracle",
1999
- * baseAddress, checks, resultsOffset?, baseAddressConfig? }`, `{ kind: "LifecycleHook", hookedProgram, checks,
2000
- * extraAccounts?, dataAuthority?, schema? }` and the Linked forms (collections); `authority?` is the plugin's own.
2001
- */
2002
- coreExternalPlugin(n) {
2003
- const p = this.coreProps(n, "a Core external plugin");
2004
- const kind = p.get("kind");
2005
- const kinds = ["LifecycleHook", "Oracle", "AppData", "LinkedLifecycleHook", "LinkedAppData"];
2006
- const i = kind && ts.isStringLiteral(kind) ? kinds.indexOf(kind.text) : -1;
2007
- if (i < 0)
2008
- this.fail(kind ?? n, `a Core external plugin is ${kinds.join(", ")}`);
2009
- const allowed = {
2010
- 0: ["hookedProgram", "checks", "extraAccounts", "dataAuthority", "schema"],
2011
- 1: ["baseAddress", "checks", "baseAddressConfig", "resultsOffset"],
2012
- 2: ["dataAuthority", "schema"],
2013
- 3: ["hookedProgram", "checks", "extraAccounts", "dataAuthority", "schema"],
2014
- 4: ["dataAuthority", "schema"],
2015
- };
2016
- for (const k of p.keys())
2017
- if (k !== "kind" && k !== "authority" && !allowed[i].includes(k))
2018
- this.fail(n, `${kinds[i]} takes ${allowed[i].join(", ")} and authority, not ${k}`);
2019
- const need = (k) => p.get(k) ?? this.fail(n, `${kinds[i]} needs ${k}`);
2020
- const auth = this.coreOption(p.get("authority"), (x) => this.coreAuthority(x));
2021
- const schema = this.coreOption(p.get("schema"), (x) => this.coreSchema(x));
2022
- if (i === 2 || i === 4)
2023
- return [{ bytes: [i] }, ...this.coreAuthority(need("dataAuthority")), ...auth, ...schema];
2024
- if (i === 1) {
2025
- const offset = p.get("resultsOffset");
2026
- const off = !offset
2027
- ? [{ bytes: [0] }]
2028
- : ts.isStringLiteral(offset) && (offset.text === "none" || offset.text === "anchor")
2029
- ? [{ bytes: [1, offset.text === "none" ? 0 : 1] }]
2030
- : [{ bytes: [1, 2] }, { value: offset, type: U64 }];
2031
- return [
2032
- { bytes: [1] },
2033
- { value: need("baseAddress"), type: PUBKEY },
2034
- ...auth,
2035
- ...this.coreChecks(need("checks"), n),
2036
- ...this.coreOption(p.get("baseAddressConfig"), (x) => this.coreExtraAccount(x)),
2037
- ...off,
2038
- ];
2039
- }
2040
- const extras = p.get("extraAccounts");
2041
- if (extras && !ts.isArrayLiteralExpression(extras))
2042
- this.fail(extras, "extraAccounts is a list of extra accounts");
2043
- return [
2044
- { bytes: [i] },
2045
- { value: need("hookedProgram"), type: PUBKEY },
2046
- ...auth,
2047
- ...this.coreChecks(need("checks"), n),
2048
- ...(extras ? [{ bytes: [1, extras.elements.length & 0xff, 0, 0, 0] }, ...extras.elements.flatMap((e) => this.coreExtraAccount(e))] : [{ bytes: [0] }]),
2049
- ...this.coreOption(p.get("dataAuthority"), (x) => this.coreAuthority(x)),
2050
- ...schema,
2051
- ];
2052
- }
2053
- /** ExternalPluginAdapterKey: `{ kind: "AppData", dataAuthority }`, `{ kind: "Oracle", address }`, `{ kind: "LifecycleHook", address }`, … */
2054
- coreExternalKey(n) {
2055
- const p = this.coreProps(n, "a Core external plugin key");
2056
- const kind = p.get("kind");
2057
- const kinds = ["LifecycleHook", "Oracle", "AppData", "LinkedLifecycleHook", "LinkedAppData"];
2058
- const i = kind && ts.isStringLiteral(kind) ? kinds.indexOf(kind.text) : -1;
2059
- if (i < 0)
2060
- this.fail(kind ?? n, `a Core external plugin key is ${kinds.join(", ")}`);
2061
- if (i === 2 || i === 4)
2062
- return [{ bytes: [i] }, ...this.coreAuthority(p.get("dataAuthority") ?? this.fail(n, `${kinds[i]}'s key is its dataAuthority`))];
2063
- return [
2064
- { bytes: [i] },
2065
- { 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 },
2066
- ];
2067
- }
2068
- /** The data written: Option<Vec<u8>> from a string, a Vec<u8> argument, or null (clears it). */
2069
- coreExternalData(n) {
2070
- if (n.kind === ts.SyntaxKind.NullKeyword)
2071
- return [{ bytes: [0] }];
2072
- const l = ts.isIdentifier(n) ? this.lookup(n.text) : undefined;
2073
- if (l?.type.kind === "vecArg") {
2074
- if (l.type.elem.kind !== "int" || l.type.elem.name !== "u8")
2075
- this.fail(n, "data is a string, a Vec<u8> argument or null");
2076
- const t = this.tmp("dl");
2077
- this.line(`uint32_t ${t} = (uint32_t)${l.c}.len;`);
2078
- return [{ bytes: [1] }, { c: `&${t}`, n: "4" }, { c: `${l.c}.ptr`, n: `(uint64_t)${t}` }];
2079
- }
2080
- return [{ bytes: [1] }, { value: n, type: STRING }];
2081
- }
2082
- /** PluginType (u8) from a kind string literal: removePlugin(…, "FreezeDelegate"). */
2083
- corePluginType(n) {
2084
- if (!ts.isStringLiteral(n))
2085
- this.fail(n, 'name the plugin kind as a string literal: "FreezeDelegate"');
2086
- const i = CORE_PLUGINS.indexOf(n.text);
2087
- if (i < 0)
2088
- this.fail(n, `Core plugins are ${CORE_PLUGINS.join(", ")}`);
2089
- return { bytes: [i] };
2090
- }
2091
- /** Bubblegum (compressed NFTs on SPL account compression): createTree, mint (MintV1, no collection, no creators). */
2092
- bubblegumOp(node, bg, method) {
2093
- const a = node.arguments;
2094
- const p = `a_${bg.name}`;
2095
- const seedsAt = (i) => (a[i] ? this.signingSeeds(a[i]) : { name: "NULL", count: 0 });
2096
- const acct = (i, what, w, s) => this.mplMeta(a[i], bg, what, w, s);
2097
- switch (method) {
2098
- case "createTree": {
2099
- // CreateTreeConfig: treeConfig, merkleTree, payer, treeCreator, logWrapper, compressionProgram, systemProgram.
2100
- if (a.length !== 10 && a.length !== 11)
2101
- this.fail(node, "createTree(treeConfig, merkleTree, payer, treeCreator, logWrapper, compressionProgram, systemProgram, maxDepth, maxBufferSize, isPublic, signerSeeds?)");
2102
- const metas = [
2103
- acct(0, "the tree config", true, false),
2104
- acct(1, "the merkle tree", true, false),
2105
- acct(2, "the payer", true, true),
2106
- acct(3, "the tree creator", false, true),
2107
- acct(4, "the log wrapper", false, false),
2108
- acct(5, "the compression program", false, false),
2109
- acct(6, "the system program", false, false),
2110
- ];
2111
- const U32 = { kind: "int", name: "u32" };
2112
- const data = this.mplData(node, 32, [
2113
- { bytes: [165, 83, 136, 142, 89, 202, 47, 220] },
2114
- { value: a[7], type: U32 },
2115
- { value: a[8], type: U32 },
2116
- { bytes: [1] }, // public: Some(bool)
2117
- { value: a[9], type: BOOL },
2118
- ]);
2119
- this.cpi(p, metas, data.buf, data.len, seedsAt(10));
2120
- return undefined;
2121
- }
2122
- case "mint": {
2123
- // MintV1: treeConfig, leafOwner, leafDelegate, merkleTree, payer, treeCreatorOrDelegate, logWrapper,
2124
- // compressionProgram, systemProgram; MetadataArgs with no collection, uses or creators.
2125
- if (a.length !== 13 && a.length !== 14)
2126
- this.fail(node, "mint(treeConfig, leafOwner, leafDelegate, merkleTree, payer, treeDelegate, logWrapper, compressionProgram, systemProgram, name, symbol, uri, sellerFeeBasisPoints, signerSeeds?)");
2127
- const metas = [
2128
- acct(0, "the tree config", true, false),
2129
- acct(1, "the leaf owner", false, false),
2130
- acct(2, "the leaf delegate", false, false),
2131
- acct(3, "the merkle tree", true, false),
2132
- acct(4, "the payer", false, true),
2133
- acct(5, "the tree delegate", false, true),
2134
- acct(6, "the log wrapper", false, false),
2135
- acct(7, "the compression program", false, false),
2136
- acct(8, "the system program", false, false),
2137
- ];
2138
- const data = this.mplData(node, 1024, [
2139
- { bytes: [145, 98, 192, 118, 184, 147, 118, 104] },
2140
- { value: a[9], type: STRING },
2141
- { value: a[10], type: STRING },
2142
- { value: a[11], type: STRING },
2143
- { value: a[12], type: { kind: "int", name: "u16" } },
2144
- // primarySaleHappened false, isMutable true, editionNonce None, tokenStandard Some(NonFungible),
2145
- // collection None, uses None, tokenProgramVersion Original, creators [].
2146
- { bytes: [0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0] },
2147
- ]);
2148
- this.cpi(p, metas, data.buf, data.len, seedsAt(13));
2149
- return undefined;
2150
- }
2151
- case "mintToCollection": {
2152
- // MintToCollectionV1: MintV1's accounts plus the collection authority (signing), its record PDA (or null),
2153
- // the collection mint, metadata (writable) and master edition, Bubblegum's signer PDA and Token Metadata;
2154
- // MetadataArgs with Some({ verified: false, key: collection mint }) (Bubblegum verifies it).
2155
- if (a.length !== 17 && a.length !== 18)
2156
- 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?)");
2157
- const metas = [
2158
- acct(0, "the tree config", true, false),
2159
- acct(1, "the leaf owner", false, false),
2160
- acct(2, "the leaf delegate", false, false),
2161
- acct(3, "the merkle tree", true, false),
2162
- acct(4, "the payer", false, true),
2163
- acct(5, "the tree delegate", false, true),
2164
- acct(6, "the collection authority", false, true),
2165
- acct(7, "the collection authority record", false, false),
2166
- acct(8, "the collection mint", false, false),
2167
- acct(9, "the collection metadata", true, false),
2168
- acct(10, "the collection edition", false, false),
2169
- acct(11, "Bubblegum's signer", false, false),
2170
- acct(12, "the log wrapper", false, false),
2171
- acct(13, "the compression program", false, false),
2172
- acct(14, "Token Metadata", false, false),
2173
- acct(15, "the system program", false, false),
2174
- ];
2175
- const md = a[16];
2176
- if (!ts.isObjectLiteralExpression(md))
2177
- this.fail(md, "the metadata is { name, symbol, uri, sellerFeeBasisPoints, creators?, isMutable?, editionNonce? }");
2178
- const props = this.literalProps(md, ["name", "symbol", "uri", "sellerFeeBasisPoints", "creators", "isMutable", "editionNonce"], "the metadata");
2179
- const need = (k) => props.get(k) ?? this.fail(md, `the metadata needs ${k}`);
2180
- // `collectionMint.key`, read where the call is.
2181
- const key = ts.factory.createPropertyAccessExpression(a[8], "key");
2182
- ts.setTextRange(key, a[8]);
2183
- key.parent = node;
2184
- const nonce = props.get("editionNonce");
2185
- const data = this.mplData(node, 1024, [
2186
- { bytes: [153, 18, 178, 47, 197, 158, 86, 15] },
2187
- { value: need("name"), type: STRING },
2188
- { value: need("symbol"), type: STRING },
2189
- { value: need("uri"), type: STRING },
2190
- { value: need("sellerFeeBasisPoints"), type: { kind: "int", name: "u16" } },
2191
- { bytes: [0] }, // primarySaleHappened
2192
- props.get("isMutable") ? { value: props.get("isMutable"), type: BOOL } : { bytes: [1] },
2193
- ...(nonce ? [{ bytes: [1] }, { value: nonce, type: U8 }] : [{ bytes: [0] }]),
2194
- { bytes: [1, 0] }, // tokenStandard Some(NonFungible)
2195
- { bytes: [1, 0] }, // collection Some({ verified: false, … })
2196
- { value: key, type: PUBKEY },
2197
- { bytes: [0, 0] }, // uses None, tokenProgramVersion Original
2198
- ...this.bubblegumCreators(props.get("creators")),
2199
- ]);
2200
- this.cpi(p, metas, data.buf, data.len, seedsAt(17));
2201
- return undefined;
2202
- }
2203
- }
2204
- return this.bubblegumV2(node, bg, method);
2205
- }
2206
- /** Bubblegum V2 (trees on mpl-account-compression with mpl-noop; optional Metaplex Core collections). */
2207
- bubblegumV2(node, bg, method) {
2208
- const a = node.arguments;
2209
- const p = `a_${bg.name}`;
2210
- const acct = (i, what, w, s) => this.mplMeta(a[i], bg, what, w, s);
2211
- const seedsAt = (i) => (a[i] ? this.signingSeeds(a[i]) : { name: "NULL", count: 0 });
2212
- const U32 = { kind: "int", name: "u32" };
2213
- const U64v = { kind: "int", name: "u64" };
2214
- const HASH = { kind: "pubkey", hash: true };
2215
- // The leaf an instruction replaces. "v2": { root, dataHash, creatorHash, assetDataHash?, flags?, nonce, index };
2216
- // "delegate": the same with collectionHash? before assetDataHash; "meta": { root, assetDataHash?, flags?, nonce,
2217
- // index } (the hashes come from the metadata passed); "v1": { root, dataHash, creatorHash, nonce, index }.
2218
- const leafFields = (n, shape = "v2") => {
2219
- const known = shape === "v1"
2220
- ? ["root", "dataHash", "creatorHash", "nonce", "index"]
2221
- : shape === "meta"
2222
- ? ["root", "assetDataHash", "flags", "nonce", "index"]
2223
- : ["root", "dataHash", "creatorHash", ...(shape === "delegate" ? ["collectionHash"] : []), "assetDataHash", "flags", "nonce", "index"];
2224
- if (!ts.isObjectLiteralExpression(n))
2225
- this.fail(n, `the leaf is { ${known.join(", ")} }`);
2226
- const props = new Map();
2227
- for (const q of n.properties) {
2228
- if (ts.isPropertyAssignment(q) && ts.isIdentifier(q.name))
2229
- props.set(q.name.text, q.initializer);
2230
- else if (ts.isShorthandPropertyAssignment(q))
2231
- props.set(q.name.text, q.name);
2232
- else
2233
- this.fail(q, "write leaf fields as name: value");
2234
- }
2235
- for (const [k, v] of props)
2236
- if (!known.includes(k))
2237
- this.fail(v, `the leaf has no field ${k}`);
2238
- const need = (k) => props.get(k) ?? this.fail(n, `the leaf needs ${k}`);
2239
- // Left out or null: None. A value that may be null at run time (`Hash | null`) goes as a Borsh Option.
2240
- const opt = (k, t) => {
2241
- const v = props.get(k);
2242
- if (!v || v.kind === ts.SyntaxKind.NullKeyword)
2243
- return [{ bytes: [0] }];
2244
- this.model.options.set(optionKey(t), t);
2245
- return [{ value: v, type: { kind: "option", inner: t } }];
2246
- };
2247
- const hashes = shape === "meta"
2248
- ? []
2249
- : [
2250
- { value: need("dataHash"), type: HASH },
2251
- { value: need("creatorHash"), type: HASH },
2252
- ];
2253
- const tail = [
2254
- { value: need("nonce"), type: U64v },
2255
- { value: need("index"), type: U32 },
2256
- ];
2257
- if (shape === "v1")
2258
- return [{ value: need("root"), type: HASH }, ...hashes, ...tail];
2259
- return [
2260
- { value: need("root"), type: HASH },
2261
- ...hashes,
2262
- ...(shape === "delegate" ? opt("collectionHash", HASH) : []),
2263
- ...opt("assetDataHash", HASH),
2264
- ...opt("flags", U8),
2265
- ...tail,
2266
- ];
2267
- };
2268
- // MetadataArgsV2 from { name, symbol, uri, sellerFeeBasisPoints, primarySaleHappened?, isMutable?, creators?,
2269
- // collection? } (a leaf's current metadata: the program hashes it to check the leaf).
2270
- const metadataV2 = (md) => {
2271
- if (!ts.isObjectLiteralExpression(md))
2272
- this.fail(md, "the metadata is { name, symbol, uri, sellerFeeBasisPoints, primarySaleHappened?, isMutable?, creators?, collection? }");
2273
- const props = this.literalProps(md, ["name", "symbol", "uri", "sellerFeeBasisPoints", "primarySaleHappened", "isMutable", "creators", "collection"], "the metadata");
2274
- const need = (k) => props.get(k) ?? this.fail(md, `the metadata needs ${k}`);
2275
- const fields = [
2276
- { value: need("name"), type: STRING },
2277
- { value: need("symbol"), type: STRING },
2278
- { value: need("uri"), type: STRING },
2279
- { value: need("sellerFeeBasisPoints"), type: { kind: "int", name: "u16" } },
2280
- ];
2281
- const flag = (k, dflt) => (props.get(k) ? { value: props.get(k), type: BOOL } : { bytes: [dflt] });
2282
- fields.push(flag("primarySaleHappened", 0), flag("isMutable", 1), { bytes: [1, 0] }); // token_standard: Some(NonFungible)
2283
- fields.push(...this.bubblegumCreators(props.get("creators")));
2284
- const coll = props.get("collection");
2285
- if (!coll || coll.kind === ts.SyntaxKind.NullKeyword)
2286
- fields.push({ bytes: [0] });
2287
- else {
2288
- this.model.options.set("pubkey", PUBKEY);
2289
- fields.push({ value: coll, type: { kind: "option", inner: PUBKEY } });
2290
- }
2291
- return fields;
2292
- };
2293
- const proofRange = (n) => {
2294
- if (!this.ix)
2295
- this.fail(n, "a Merkle proof comes from remainingAccounts(), so only instructions can pass one");
2296
- return this.remainingRange(n) ?? this.fail(n, "pass the proof as remainingAccounts() or rest.slice(a, b)");
2297
- };
2298
- switch (method) {
2299
- case "createTreeV2": {
2300
- // CreateTreeConfigV2: treeConfig, merkleTree, payer, treeCreator, logWrapper, compressionProgram, systemProgram.
2301
- if (a.length !== 10 && a.length !== 11)
2302
- this.fail(node, "createTreeV2(treeConfig, merkleTree, payer, treeCreator | null, logWrapper, compressionProgram, systemProgram, maxDepth, maxBufferSize, isPublic, signerSeeds?)");
2303
- const metas = [
2304
- acct(0, "the tree config", true, false),
2305
- acct(1, "the merkle tree", true, false),
2306
- acct(2, "the payer", true, true),
2307
- acct(3, "the tree creator", false, true),
2308
- acct(4, "the log wrapper", false, false),
2309
- acct(5, "the compression program", false, false),
2310
- acct(6, "the system program", false, false),
2311
- ];
2312
- const data = this.mplData(node, 32, [
2313
- { bytes: [55, 99, 95, 215, 142, 203, 227, 205] },
2314
- { value: a[7], type: U32 },
2315
- { value: a[8], type: U32 },
2316
- { bytes: [1] },
2317
- { value: a[9], type: BOOL },
2318
- ]);
2319
- this.cpi(p, metas, data.buf, data.len, seedsAt(10));
2320
- return undefined;
2321
- }
2322
- case "mintV2": {
2323
- // MintV2: treeConfig, payer, treeCreatorOrDelegate, collectionAuthority, leafOwner, leafDelegate, merkleTree,
2324
- // coreCollection, mplCoreCpiSigner, logWrapper, compressionProgram, mplCoreProgram, systemProgram.
2325
- 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?)";
2326
- const collection = a[11] && ts.isObjectLiteralExpression(a[11]) ? a[11] : undefined;
2327
- if (a.length < 11 || a.length > (collection ? 13 : 12))
2328
- this.fail(node, usage);
2329
- const md = a[10];
2330
- if (!ts.isObjectLiteralExpression(md))
2331
- this.fail(md, "the metadata is { name, symbol, uri, sellerFeeBasisPoints, creators?, isMutable? }");
2332
- const field = (o, k) => {
2333
- const q = o.properties.find((x) => (ts.isPropertyAssignment(x) || ts.isShorthandPropertyAssignment(x)) && ts.isIdentifier(x.name) && x.name.text === k);
2334
- return q ? (ts.isPropertyAssignment(q) ? q.initializer : q.name) : undefined;
2335
- };
2336
- for (const q of md.properties)
2337
- if (!q.name || !ts.isIdentifier(q.name) || !["name", "symbol", "uri", "sellerFeeBasisPoints", "creators", "isMutable"].includes(q.name.text))
2338
- this.fail(q, "the metadata takes name, symbol, uri, sellerFeeBasisPoints, creators and isMutable");
2339
- const coll = collection
2340
- ? ["collection", "authority", "cpiSigner"].map((k) => field(collection, k) ?? this.fail(collection, `the collection needs ${k}`))
2341
- : undefined;
2342
- if (collection)
2343
- for (const q of collection.properties)
2344
- if (!q.name || !ts.isIdentifier(q.name) || !["collection", "authority", "cpiSigner"].includes(q.name.text))
2345
- this.fail(q, "the collection is { collection, authority, cpiSigner }");
2346
- const metas = [
2347
- acct(0, "the tree config", true, false),
2348
- acct(1, "the payer", true, true),
2349
- acct(2, "the tree delegate", false, true),
2350
- coll ? this.mplMeta(coll[1], bg, "the collection authority", false, true) : [p, false, false],
2351
- acct(3, "the leaf owner", false, false),
2352
- acct(4, "the leaf delegate", false, false),
2353
- acct(5, "the merkle tree", true, false),
2354
- coll ? this.mplMeta(coll[0], bg, "the core collection", true, false) : [p, false, false],
2355
- coll ? this.mplMeta(coll[2], bg, "the mpl-core CPI signer", false, false) : [p, false, false],
2356
- acct(6, "the log wrapper", false, false),
2357
- acct(7, "the compression program", false, false),
2358
- acct(8, "the mpl-core program", false, false),
2359
- acct(9, "the system program", false, false),
2360
- ];
2361
- const need = (k) => field(md, k) ?? this.fail(md, `the metadata needs ${k}`);
2362
- const fields = [
2363
- { bytes: [120, 121, 23, 146, 173, 110, 199, 205] },
2364
- { value: need("name"), type: STRING },
2365
- { value: need("symbol"), type: STRING },
2366
- { value: need("uri"), type: STRING },
2367
- { value: need("sellerFeeBasisPoints"), type: { kind: "int", name: "u16" } },
2368
- { bytes: [0] }, // primary_sale_happened
2369
- ];
2370
- const mutable = field(md, "isMutable");
2371
- fields.push(mutable ? { value: mutable, type: BOOL } : { bytes: [1] });
2372
- fields.push({ bytes: [1, 0] }); // token_standard: Some(NonFungible)
2373
- const creators = field(md, "creators");
2374
- if (creators && !ts.isArrayLiteralExpression(creators))
2375
- this.fail(creators, "creators: [{ address, verified, share }, …] (an array literal)");
2376
- const list = creators ? creators.elements : [];
2377
- if (list.length > 5)
2378
- this.fail(creators, "Bubblegum takes at most 5 creators");
2379
- fields.push({ bytes: [list.length, 0, 0, 0] });
2380
- let shares = 0n;
2381
- let constant = true;
2382
- for (const el of list) {
2383
- if (!ts.isObjectLiteralExpression(el))
2384
- this.fail(el, "a creator is { address, verified, share }");
2385
- const f = (k) => field(el, k) ?? this.fail(el, `a creator needs ${k}`);
2386
- const share = f("share");
2387
- if (ts.isBigIntLiteral(share))
2388
- shares += BigInt(share.text.slice(0, -1));
2389
- else
2390
- constant = false;
2391
- fields.push({ value: f("address"), type: PUBKEY }, { value: f("verified"), type: BOOL }, { value: share, type: U8 });
2392
- }
2393
- if (list.length && constant && shares !== 100n)
2394
- this.fail(creators, `creator shares add up to ${shares}; Bubblegum requires 100`);
2395
- // collection: Some(the core collection's key) when minting into one.
2396
- if (coll)
2397
- fields.push({ bytes: [1] }, { value: this.keyOf(coll[0]), type: PUBKEY });
2398
- else
2399
- fields.push({ bytes: [0] });
2400
- fields.push({ bytes: [0, 0] }); // asset_data, asset_data_schema: None
2401
- const data = this.mplData(node, 1024, fields);
2402
- this.cpi(p, metas, data.buf, data.len, seedsAt(collection ? 12 : 11));
2403
- return undefined;
2404
- }
2405
- case "transferV2": {
2406
- // TransferV2: treeConfig, payer, authority, leafOwner, leafDelegate, newLeafOwner, merkleTree, coreCollection,
2407
- // logWrapper, compressionProgram, systemProgram; the proof follows as remaining accounts.
2408
- if (a.length !== 13 && a.length !== 14)
2409
- this.fail(node, "transferV2(treeConfig, payer, authority | null, leafOwner, leafDelegate | null, newLeafOwner, merkleTree, coreCollection | null, logWrapper, compressionProgram, systemProgram, leaf, proof, signerSeeds?)");
2410
- const metas = [
2411
- acct(0, "the tree config", true, false),
2412
- acct(1, "the payer", true, true),
2413
- acct(2, "the authority", false, true),
2414
- acct(3, "the leaf owner", false, false),
2415
- acct(4, "the leaf delegate", false, false),
2416
- acct(5, "the new leaf owner", false, false),
2417
- acct(6, "the merkle tree", true, false),
2418
- acct(7, "the core collection", false, false),
2419
- acct(8, "the log wrapper", false, false),
2420
- acct(9, "the compression program", false, false),
2421
- acct(10, "the system program", false, false),
2422
- ];
2423
- const data = this.mplData(node, 160, [{ bytes: [119, 40, 6, 235, 234, 221, 248, 49] }, ...leafFields(a[11])]);
2424
- this.cpi(p, metas, data.buf, data.len, seedsAt(13), proofRange(a[12]));
2425
- return undefined;
2426
- }
2427
- case "burnV2": {
2428
- // BurnV2: treeConfig, payer, authority, leafOwner, leafDelegate, merkleTree, coreCollection, mplCoreCpiSigner,
2429
- // logWrapper, compressionProgram, mplCoreProgram, systemProgram; the proof follows as remaining accounts.
2430
- if (a.length !== 14 && a.length !== 15)
2431
- this.fail(node, "burnV2(treeConfig, payer, authority | null, leafOwner, leafDelegate | null, merkleTree, coreCollection | null, mplCoreCpiSigner | null, logWrapper, compressionProgram, mplCoreProgram, systemProgram, leaf, proof, signerSeeds?)");
2432
- const metas = [
2433
- acct(0, "the tree config", true, false),
2434
- acct(1, "the payer", true, true),
2435
- acct(2, "the authority", false, true),
2436
- acct(3, "the leaf owner", false, false),
2437
- acct(4, "the leaf delegate", false, false),
2438
- acct(5, "the merkle tree", true, false),
2439
- acct(6, "the core collection", true, false),
2440
- acct(7, "the mpl-core CPI signer", false, false),
2441
- acct(8, "the log wrapper", false, false),
2442
- acct(9, "the compression program", false, false),
2443
- acct(10, "the mpl-core program", false, false),
2444
- acct(11, "the system program", false, false),
2445
- ];
2446
- const data = this.mplData(node, 160, [{ bytes: [115, 210, 34, 240, 232, 143, 183, 16] }, ...leafFields(a[12])]);
2447
- this.cpi(p, metas, data.buf, data.len, seedsAt(14), proofRange(a[13]));
2448
- return undefined;
2449
- }
2450
- }
2451
- const op = BUBBLEGUM_OPS[method];
2452
- if (op) {
2453
- // accounts…, [leaf, metadata?, update?], proof, signerSeeds?
2454
- const nAccounts = op.accounts.length;
2455
- const extra = op.leaf === "meta" ? (method === "updateMetadataV2" ? 2 : 1) : 0;
2456
- const proofAt = nAccounts + 1 + extra;
2457
- if (a.length !== proofAt + 1 && a.length !== proofAt + 2)
2458
- this.fail(node, `${method}(${op.accounts.map(([l, , , o]) => (o ? `${l} | null` : l)).join(", ")}, leaf${extra ? (extra === 2 ? ", currentMetadata, update" : ", metadata") : ""}, proof, signerSeeds?)`);
2459
- const hasSeeds = !!a[proofAt + 1];
2460
- const metas = op.accounts.map(([label, w, s, optional, either], i) => {
2461
- if (!optional && a[i].kind === ts.SyntaxKind.NullKeyword)
2462
- this.fail(a[i], `pass ${label}`);
2463
- const m = this.mplMeta(a[i], bg, label, w, s);
2464
- // V1 leaf owner / delegate: either may sign (a PDA owner signs with the seeds).
2465
- if (either)
2466
- return [
2467
- m[0],
2468
- w,
2469
- either === "owner"
2470
- ? `(${m[0]}->is_signer || ${hasSeeds})`
2471
- : `(${m[0]}->is_signer || (${hasSeeds} && ${m[0]} == ${`a_${this.accountParam(a[i - 1], "the leaf owner").name}`}))`,
2472
- ];
2473
- return m;
2474
- });
2475
- const fields = [{ bytes: op.disc }, ...leafFields(a[nAccounts], op.leaf)];
2476
- if (op.leaf === "meta")
2477
- fields.push(...metadataV2(a[nAccounts + 1]));
2478
- if (method === "updateMetadataV2")
2479
- fields.push(...this.bubblegumUpdateArgs(a[nAccounts + 2]));
2480
- const data = this.mplData(node, 2048, fields);
2481
- this.cpi(p, metas, data.buf, data.len, seedsAt(proofAt + 1), proofRange(a[proofAt]));
2482
- return undefined;
2483
- }
2484
- this.fail(node.expression, `Bubblegum supports createTree, mint, mintToCollection, createTreeV2, mintV2, transferV2, burnV2, ${Object.keys(BUBBLEGUM_OPS).join(", ")}, not ${method}`);
2485
- }
2486
- /** Object literal properties by name, refusing others. */
2487
- literalProps(o, allowed, what) {
2488
- const props = new Map();
2489
- for (const q of o.properties) {
2490
- if (ts.isPropertyAssignment(q) && ts.isIdentifier(q.name))
2491
- props.set(q.name.text, q.initializer);
2492
- else if (ts.isShorthandPropertyAssignment(q))
2493
- props.set(q.name.text, q.name);
2494
- else
2495
- this.fail(q, `write ${what}'s fields as name: value`);
2496
- }
2497
- for (const [k, v] of props)
2498
- if (!allowed.includes(k))
2499
- this.fail(v, `${what} has no field ${k} (${allowed.join(", ")})`);
2500
- return props;
2501
- }
2502
- /** Vec<Creator> (address, verified, share) from a literal list; shares add up to 100 when literal. */
2503
- bubblegumCreators(creators) {
2504
- if (creators && !ts.isArrayLiteralExpression(creators))
2505
- this.fail(creators, "creators: [{ address, verified, share }, …] (an array literal)");
2506
- const list = creators ? creators.elements : [];
2507
- if (list.length > 5)
2508
- this.fail(creators, "Bubblegum takes at most 5 creators");
2509
- const fields = [{ bytes: [list.length, 0, 0, 0] }];
2510
- let shares = 0n;
2511
- let constant = true;
2512
- for (const el of list) {
2513
- if (!ts.isObjectLiteralExpression(el))
2514
- this.fail(el, "a creator is { address, verified, share }");
2515
- const props = this.literalProps(el, ["address", "verified", "share"], "a creator");
2516
- const f = (k) => props.get(k) ?? this.fail(el, `a creator needs ${k}`);
2517
- const share = f("share");
2518
- if (ts.isBigIntLiteral(share))
2519
- shares += BigInt(share.text.slice(0, -1));
2520
- else
2521
- constant = false;
2522
- fields.push({ value: f("address"), type: PUBKEY }, { value: f("verified"), type: BOOL }, { value: share, type: U8 });
2523
- }
2524
- if (list.length && constant && shares !== 100n)
2525
- this.fail(creators, `creator shares add up to ${shares}; Bubblegum requires 100`);
2526
- return fields;
2527
- }
2528
- /** UpdateArgs: every field optional (left out or null: unchanged). */
2529
- bubblegumUpdateArgs(n) {
2530
- if (!ts.isObjectLiteralExpression(n))
2531
- this.fail(n, "the update is { name?, symbol?, uri?, creators?, sellerFeeBasisPoints?, primarySaleHappened?, isMutable? }");
2532
- const props = this.literalProps(n, ["name", "symbol", "uri", "creators", "sellerFeeBasisPoints", "primarySaleHappened", "isMutable"], "the update");
2533
- const opt = (k, t) => {
2534
- const v = props.get(k);
2535
- return !v || v.kind === ts.SyntaxKind.NullKeyword ? [{ bytes: [0] }] : [{ bytes: [1] }, { value: v, type: t }];
2536
- };
2537
- const creators = props.get("creators");
2538
- return [
2539
- ...opt("name", STRING),
2540
- ...opt("symbol", STRING),
2541
- ...opt("uri", STRING),
2542
- ...(creators && creators.kind !== ts.SyntaxKind.NullKeyword ? [{ bytes: [1] }, ...this.bubblegumCreators(creators)] : [{ bytes: [0] }]),
2543
- ...opt("sellerFeeBasisPoints", { kind: "int", name: "u16" }),
2544
- ...opt("primarySaleHappened", BOOL),
2545
- ...opt("isMutable", BOOL),
2546
- ];
2547
- }
2548
- /** `acct.key` of an account parameter, as an expression to serialize. */
2549
- keyOf(n) {
2550
- const f = ts.factory;
2551
- const e = f.createPropertyAccessExpression(n, "key");
2552
- ts.setTextRange(e, n);
2553
- e.parent = n.parent;
2554
- return e;
2555
- }
2556
- /**
2557
- * `remainingAccounts()` (or a const bound to it): every remaining account; `rest.slice(a, b?)`: indexes a..b of them
2558
- * (both checked against the count, 5104). C expressions for the range, relative to the first remaining account.
2559
- */
2560
- remainingRange(node) {
2561
- const n = this.ix.accounts.length;
2562
- const count = `(params->ka_num - ${n})`;
2563
- if (this.isRemaining(node))
2564
- return { from: "0", to: count };
2565
- if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression) || node.expression.name.text !== "slice")
2566
- return undefined;
2567
- if (!this.isRemaining(node.expression.expression))
2568
- return undefined;
2569
- if (node.arguments.length < 1 || node.arguments.length > 2)
2570
- this.fail(node, "slice(start, end?) takes one or two indexes");
2571
- // Both ends may equal the count (an empty slice at the end).
2572
- const from = this.index(node.arguments[0], `${count} + 1`);
2573
- const to = node.arguments[1] ? this.index(node.arguments[1], `${count} + 1`) : count;
2574
- this.line(`if (${from} > ${to}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: remaining accounts slice out of range");`);
2575
- return { from, to };
2576
- }
2
+ import { discriminator, heapVecOf, snakeCase } from "../analyze.js";
3
+ import { isScalar, isWritable, sameType, typeName } from "../model.js";
4
+ import { accountLimit, MAX_CPI_DATA, MAX_EVENT, PUBKEY, STRING, cBytes, valueC, fixedVecC, vecCount } from "./shared.js";
5
+ import { MetaplexEmitter } from "./metaplex.js";
6
+ /** Generic CPIs (`invoke`, `invokeInstruction`) and events (`emit`, `emitCpi`). */
7
+ export class CpiEmitter extends MetaplexEmitter {
2577
8
  invoke(node) {
2578
9
  const a = node.arguments;
2579
10
  if (a.length !== 3 && a.length !== 4)
@@ -2637,8 +68,8 @@ export class CpiEmitter extends CallEmitter {
2637
68
  parts.push({ kind: "meta", c: metas[metas.length - 1] });
2638
69
  }
2639
70
  // The CPI's account list is built in a buffer with room for one entry per instruction account.
2640
- if (metas.length > MAX_ACCOUNTS)
2641
- this.fail(a[1], `invoke takes at most ${MAX_ACCOUNTS} accounts`);
71
+ if (metas.length > accountLimit(this.model))
72
+ this.fail(a[1], `invoke takes at most ${accountLimit(this.model)} accounts`);
2642
73
  // Data: integers (LE at their width), booleans, Pubkeys, strings (Borsh), sighash("name"), hex("..")
2643
74
  if (!ts.isArrayLiteralExpression(a[2]))
2644
75
  this.fail(a[2], "data must be an array literal");
@@ -2709,11 +140,11 @@ export class CpiEmitter extends CallEmitter {
2709
140
  // Room for every account of the instruction (ts_invoke's scratch holds TS_MAX_ACCOUNTS records).
2710
141
  const n = this.ix.accounts.length;
2711
142
  const cnt = this.tmp("nmetas");
2712
- this.line(`SolAccountMeta ${metasName}[TS_MAX_ACCOUNTS];`);
143
+ this.line(`TS_METAS_ROOM(${metasName});`);
2713
144
  this.line(`uint64_t ${cnt} = 0;`);
2714
145
  const spreads = parts.filter((p) => p.kind === "spread");
2715
146
  const total = [String(metas.length), ...spreads.map((p) => `(${p.to} - ${p.from})`)].join(" + ");
2716
- this.line(`if (${total} > TS_MAX_ACCOUNTS) TS_FAIL(TS_ERR_TOO_MANY_ACCOUNTS, "TypeSOL: the CPI lists more than ${MAX_ACCOUNTS} accounts");`);
147
+ this.line(`if (${total} > TS_MAX_ACCOUNTS) TS_FAIL(TS_ERR_TOO_MANY_ACCOUNTS, "TypeSOL: the CPI lists more than ${accountLimit(this.model)} accounts");`);
2717
148
  for (const p of parts) {
2718
149
  if (p.kind === "meta") {
2719
150
  this.line(`${metasName}[${cnt}++] = (SolAccountMeta)${p.c};`);
@@ -2747,105 +178,68 @@ export class CpiEmitter extends CallEmitter {
2747
178
  return undefined;
2748
179
  }
2749
180
  /**
2750
- * A byte buffer written front to back. Its C declaration is patched in afterwards so it is
2751
- * exactly as large as the fixed content, and only falls back to `max` when strings make it dynamic.
181
+ * `invokeInstruction(programId, metas, data, infos, signerSeeds?)`: a CPI decided at run time (Rust's
182
+ * `invoke_signed(&Instruction { program_id, accounts, data }, infos, seeds)`), e.g. one stored in account data. Each
183
+ * meta is a struct with `pubkey`, `isSigner` and `isWritable`; `data` a list of u8; every account in `infos` (the
184
+ * remaining accounts, or a slice of them) goes to the runtime, which finds each meta's account there by key (an
185
+ * account missing there fails the CPI, as under Rust) and checks the privileges: a meta may only be a signer or
186
+ * writable as the transaction passed it, or a PDA of this program that `signerSeeds` sign for.
2752
187
  */
2753
- byteBuffer(prefix, max, errorCode, what) {
2754
- const buf = this.tmp(prefix);
2755
- const len = this.tmp(`${prefix}len`);
2756
- const declAt = this.lines.length;
2757
- this.line(`/* ${buf} */`);
2758
- this.line(`uint64_t ${len} = 0;`);
2759
- let fixed = 0;
2760
- let dynamic = false;
2761
- const put = (src, n, bytes) => {
2762
- // Once a variable-size piece was written the offset is only known at runtime: check every later write,
2763
- // fixed-size ones included, so nothing lands past the buffer.
2764
- if (bytes === undefined)
2765
- dynamic = true;
2766
- else
2767
- fixed += bytes;
2768
- if (dynamic)
2769
- this.line(`if (${len} + ${n} > ${max}) TS_FAIL(${errorCode}, "TypeSOL: ${what} too large");`);
2770
- this.line(`ts_memcpy(${buf} + ${len}, ${src}, ${n});`);
2771
- this.line(`${len} += ${n};`);
2772
- };
2773
- const finish = (at) => {
2774
- if (fixed > max)
2775
- this.fail(at, `${what} is at least ${fixed} bytes; the limit is ${max}`);
2776
- this.lines[declAt] = this.lines[declAt].replace(`/* ${buf} */`, `uint8_t ${buf}[${dynamic ? max : Math.max(fixed, 1)}];`);
2777
- };
2778
- return { buf, len, put, finish };
2779
- }
2780
- /** Append a value's Borsh encoding through `put(srcPointer, byteCount)`. */
2781
- serialize(v, node, put) {
2782
- if (v.isNull)
2783
- this.fail(node, "a bare null has no type here; pass an Option value (e.g. a local declared `const x: u64 | null = null`)");
2784
- const typed = v.literal !== undefined ? this.literal(v.literal, U64, node) : v;
2785
- if (typed.type.kind === "pubkey") {
2786
- put(`(${typed.c})`, "32", 32);
2787
- }
2788
- else if (typed.type.kind === "string") {
2789
- const t = this.tmp("s");
2790
- const l = this.tmp("slen");
2791
- this.line(`TS_Str ${t} = ${typed.c};`);
2792
- this.line(`uint32_t ${l} = (uint32_t)${t}.len;`);
2793
- put(`&${l}`, "4", 4);
2794
- put(`${t}.ptr`, `${t}.len`);
2795
- }
2796
- else if (typed.type.kind === "option") {
2797
- // Borsh Option: tag byte, then the value only when Some (so the size is dynamic).
2798
- const inner = typed.type.inner;
2799
- const t = this.tmp("o");
2800
- this.line(`${optC(inner)} ${t} = ${typed.c};`);
2801
- put(`&${t}.some`, "1", 1);
2802
- put(`&${t}.v`, `(${t}.some ? ${inner.kind === "struct" ? this.fieldBytes(inner) : scalarSize(inner)} : 0)`);
2803
- }
2804
- else if (isScalar(typed.type)) {
2805
- const ct = scalarStorageC(typed.type);
2806
- const bytes = scalarSize(typed.type);
2807
- const t = this.tmp("arg");
2808
- this.line(`${ct} ${t} = (${ct})(${typed.c});`);
2809
- put(`&${t}`, String(bytes), bytes);
188
+ invokeInstruction(node) {
189
+ const a = node.arguments;
190
+ if (!this.ix)
191
+ this.fail(node, "invokeInstruction is only available in instructions (it passes remaining accounts)");
192
+ if (a.length !== 4 && a.length !== 5)
193
+ this.fail(node, "invokeInstruction(programId, accounts, data, infos, signerSeeds?) takes 4 or 5 arguments");
194
+ const program = this.expect(this.expr(a[0], PUBKEY), PUBKEY, a[0]);
195
+ const programKey = this.tmp("dprog");
196
+ this.line(`SolPubkey ${programKey} = *(${program.c});`);
197
+ const list = (e, what) => {
198
+ const l = ts.isIdentifier(e) ? this.lookup(e.text) : undefined;
199
+ if (l?.type.kind === "vecArg")
200
+ return { items: `${l.c}.ptr`, count: `((uint64_t)${l.c}.len)`, elem: l.type.elem };
201
+ const r = this.ref(e);
202
+ if (r?.vec && r.type.kind === "vec")
203
+ return { items: `${r.vec.items}`, count: vecCount(r.vec), elem: r.type.elem };
204
+ this.fail(e, `${what}: a Vec or FixedVec (account data, an argument or a local list)`);
205
+ };
206
+ const metas = list(a[1], "the accounts");
207
+ const elem = metas.elem;
208
+ const st = elem.kind === "struct" ? this.model.structs.get(elem.name) : undefined;
209
+ const field = (name, kind) => st?.fields.find((f) => f.name === name && f.type.kind === kind);
210
+ if (!st || !field("pubkey", "pubkey") || !field("isSigner", "bool") || !field("isWritable", "bool"))
211
+ this.fail(a[1], "each account is a struct with pubkey: Pubkey, isSigner: boolean and isWritable: boolean");
212
+ const data = list(a[2], "the data");
213
+ if (data.elem.kind !== "int" || data.elem.name !== "u8")
214
+ this.fail(a[2], "the data is a list of u8");
215
+ const range = this.remainingRange(a[3]) ?? this.fail(a[3], "pass the accounts the CPI may use: remainingAccounts() or rest.slice(a, b)");
216
+ const seeds = a.length === 5 ? this.signingSeeds(a[4]) : undefined;
217
+ const n = this.tmp("dn");
218
+ const m = this.tmp("dmetas");
219
+ const i = this.tmp("di");
220
+ const k = this.tmp("dk");
221
+ this.line(`uint64_t ${n} = ${metas.count};`);
222
+ this.line(`SolAccountMeta *${m} = NULL;`);
223
+ this.line(`TS_TRY(ts_alloc(${n} * sizeof(SolAccountMeta) + 1, (uint8_t **)&${m}));`);
224
+ this.line(`for (uint64_t ${i} = 0; ${i} < ${n}; ${i}++) {`);
225
+ this.line(` const TSS_${st.name} *e = &((const TSS_${st.name} *)${metas.items})[${i}];`);
226
+ this.line(` ${m}[${i}] = (SolAccountMeta){(SolPubkey *)&e->pubkey, e->isWritable != 0, e->isSigner != 0};`);
227
+ this.line(`}`);
228
+ // Every account offered goes along as an AccountInfo (ts_invoke's scratch holds TS_MAX_ACCOUNTS of them).
229
+ const base = this.ix.accounts.length;
230
+ this.line(`uint64_t ${k} = 0;`);
231
+ this.line(`TS_INFOS_RESERVE(params, (${range.to}) - (${range.from}));`);
232
+ this.line(`for (uint64_t ${i}b = ${base} + ${range.from}; ${i}b < ${base} + ${range.to}; ${i}b++) ts_info(params->ka[${i}b], &params->infos[${k}++]);`);
233
+ const ixName = this.tmp("cpi");
234
+ this.line(`SolInstruction ${ixName} = {&${programKey}, ${m}, ${n}, (uint8_t *)${data.items}, ${data.count}};`);
235
+ if (seeds) {
236
+ const signer = this.tmp("signer");
237
+ this.line(`SolSignerSeeds ${signer} = {${seeds.name}, ${seeds.count}};`);
238
+ this.line(`TS_TRY(sol_invoke_signed(&${ixName}, params->infos, ${k}, &${signer}, ${typeof seeds.count === "number" ? (seeds.count > 0 ? 1 : 0) : `${seeds.count} > 0 ? 1 : 0`}));`);
2810
239
  }
2811
240
  else
2812
- this.fail(node, `${typeName(typed.type)} cannot be serialized here`);
2813
- }
2814
- /** Borsh-encode a data-enum place: the tag byte, then the active variant's fields. */
2815
- serializeDataEnum(node, name, put) {
2816
- const src = this.ref(node);
2817
- if (!src || src.type.kind !== "dataEnum" || src.type.name !== name)
2818
- this.fail(node, `expected a ${name}`);
2819
- this.serializeDataEnumLv(src.lv, name, put);
2820
- }
2821
- serializeDataEnumLv(lv, name, put) {
2822
- const src = { lv };
2823
- const e = this.model.dataEnums.get(name);
2824
- put(`&${src.lv}.tag`, "1", 1);
2825
- this.line(`switch (${src.lv}.tag) {`);
2826
- e.variants.forEach((v, i) => {
2827
- this.line(`case ${i}: {`);
2828
- for (const f of v.fields) {
2829
- const at = `${src.lv}.v.${v.name}.${f.name}`;
2830
- if (f.type.kind === "string") {
2831
- // Borsh String: u32 length, then the bytes.
2832
- const n = this.tmp("sl");
2833
- this.line(`uint32_t ${n} = (uint32_t)${at}.len;`);
2834
- put(`&${n}`, "4");
2835
- put(`${at}.ptr`, `${at}.len`);
2836
- continue;
2837
- }
2838
- if (f.type.kind === "dataEnum" && this.model.dataEnums.get(f.type.name)?.variable) {
2839
- this.serializeDataEnumLv(at, f.type.name, put);
2840
- continue;
2841
- }
2842
- const n = this.fieldBytes(f.type);
2843
- // put() with no static size: the payload differs by variant.
2844
- put(`&${at}`, String(n));
2845
- }
2846
- this.line(`break; }`);
2847
- });
2848
- this.line(`}`);
241
+ this.line(`TS_TRY(sol_invoke_signed(&${ixName}, params->infos, ${k}, NULL, 0));`);
242
+ return undefined;
2849
243
  }
2850
244
  emitEvent(node, cpi) {
2851
245
  const targ = node.typeArguments?.[0];
@@ -2977,6 +371,8 @@ export class CpiEmitter extends CallEmitter {
2977
371
  }
2978
372
  /** emit<T> of a @layout borsh struct: built like account data, then packed as Anchor serializes it. */
2979
373
  emitBorshEvent(node, s, obj, cpi) {
374
+ if (heapVecOf(s))
375
+ this.fail(node, `${s.name} holds a Vec<T>; events take a struct with FixedVec<T, N> instead`);
2980
376
  this.model.events.add(s.name);
2981
377
  const t = this.tmp("evs");
2982
378
  const b = this.tmp("evb");
@@ -3019,45 +415,4 @@ export class CpiEmitter extends CallEmitter {
3019
415
  this.line(`SolBytes ${bytes} = {${buf}, ${len}};`);
3020
416
  this.line(`sol_log_data(&${bytes}, 1);`);
3021
417
  }
3022
- /** Structs reachable through the fields of struct `name` (not including itself unless it recurses). */
3023
- nestedStructs(name) {
3024
- const out = new Set();
3025
- const visit = (t) => {
3026
- if (t.kind === "struct") {
3027
- if (out.has(t.name))
3028
- return;
3029
- out.add(t.name);
3030
- this.model.structs.get(t.name)?.fields.forEach((f) => visit(f.type));
3031
- }
3032
- else if (t.kind === "array" || t.kind === "vec")
3033
- visit(t.elem);
3034
- else if (t.kind === "option" && t.inner.kind === "struct")
3035
- visit(t.inner);
3036
- else if (t.kind === "dataEnum")
3037
- this.model.dataEnums.get(t.name)?.variants.forEach((v) => v.fields.forEach((f) => visit(f.type)));
3038
- };
3039
- this.model.structs.get(name)?.fields.forEach((f) => visit(f.type));
3040
- return out;
3041
- }
3042
- /** Structs whose IDL description is the fixed layout: account data, arguments, and everything nested in them. */
3043
- fixedLayoutStructs() {
3044
- const out = new Set();
3045
- const visit = (t) => {
3046
- if (t.kind === "struct") {
3047
- if (out.has(t.name))
3048
- return;
3049
- out.add(t.name);
3050
- this.model.structs.get(t.name)?.fields.forEach((f) => visit(f.type));
3051
- }
3052
- else if (t.kind === "array" || t.kind === "vec")
3053
- visit(t.elem);
3054
- else if (t.kind === "option" && t.inner.kind === "struct")
3055
- visit(t.inner);
3056
- else if (t.kind === "dataEnum")
3057
- this.model.dataEnums.get(t.name)?.variants.forEach((v) => v.fields.forEach((f) => visit(f.type)));
3058
- };
3059
- for (const name of [...this.model.accountStructs, ...this.model.argStructs])
3060
- visit({ kind: "struct", name });
3061
- return out;
3062
- }
3063
418
  }