@typesol/cli 0.33.0 → 0.35.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.
@@ -2,6 +2,7 @@ import ts from "typescript";
2
2
  import { isWritable, optionKey } from "../model.js";
3
3
  import { U64, U8, BOOL, PUBKEY, STRING, cBytes } from "./shared.js";
4
4
  import { TokenEmitter } from "./token.js";
5
+ const U16V = { kind: "int", name: "u16" };
5
6
  /**
6
7
  * Bubblegum instructions that replace a leaf: discriminator, accounts in order ([label, writable, signer, optional,
7
8
  * either-signs]) and the leaf's shape. Optional accounts take `null` (the program id). The Merkle proof follows the
@@ -186,8 +187,12 @@ export class MetaplexEmitter extends TokenEmitter {
186
187
  metadataOp(node, program, method) {
187
188
  if (method === "createMasterEditionV3" || method === "verifyCollection")
188
189
  return this.metadataCollectionOp(node, program, method);
190
+ if (method === "updateMetadataAccountsV2")
191
+ return this.metadataUpdate(node, program);
192
+ if (method === "burnV1")
193
+ return this.metadataBurn(node, program);
189
194
  if (method !== "createV3")
190
- this.fail(node.expression, `the Token Metadata program supports createV3, createMasterEditionV3 and verifyCollection, not ${method}`);
195
+ this.fail(node.expression, `the Token Metadata program supports createV3, createMasterEditionV3, verifyCollection, updateMetadataAccountsV2 and burnV1, not ${method}`);
191
196
  const a = node.arguments;
192
197
  const usage = "createV3(metadata, mint, mintAuthority, payer, updateAuthority, systemProgram, name, symbol, uri, sellerFeeBasisPoints, isMutable, { creators?, collection?, isCollection? }?, signerSeeds?)";
193
198
  // An object literal after isMutable carries the optional creators / collection; signerSeeds stays last.
@@ -228,42 +233,9 @@ export class MetaplexEmitter extends TokenEmitter {
228
233
  if (!ts.isPropertyAssignment(p) || !ts.isIdentifier(p.name))
229
234
  this.fail(p, "use creators: [...], collection: key and isCollection: boolean");
230
235
  if (p.name.text === "creators") {
231
- if (!ts.isArrayLiteralExpression(p.initializer))
232
- this.fail(p.initializer, "creators: [{ address, verified, share }, …] (an array literal)");
233
- const list = p.initializer.elements;
234
- if (list.length < 1 || list.length > 5)
235
- this.fail(p.initializer, "Metaplex takes 1 to 5 creators");
236
- const buf = this.tmp("creators");
237
- this.line(`uint8_t ${buf}[${34 * list.length}];`);
238
- let shares = 0n;
239
- let constant = true;
240
- list.forEach((el, i) => {
241
- if (!ts.isObjectLiteralExpression(el))
242
- this.fail(el, "a creator is { address, verified, share }");
243
- const field = (k) => {
244
- const q = el.properties.find((x) => ts.isPropertyAssignment(x) && ts.isIdentifier(x.name) && x.name.text === k);
245
- const sh = el.properties.find((x) => ts.isShorthandPropertyAssignment(x) && x.name.text === k);
246
- if (!q && !sh)
247
- this.fail(el, `a creator needs ${k}`);
248
- return q ? q.initializer : sh.name;
249
- };
250
- const at = 34 * i;
251
- const key = this.expect(this.expr(field("address"), PUBKEY), PUBKEY, el);
252
- this.line(`ts_memcpy(${buf} + ${at}, ${key.c}, 32);`);
253
- const verified = this.expect(this.expr(field("verified"), BOOL), BOOL, el);
254
- this.line(`${buf}[${at + 32}] = (${verified.c}) ? 1 : 0;`);
255
- const shareNode = field("share");
256
- if (ts.isBigIntLiteral(shareNode))
257
- shares += BigInt(shareNode.text.slice(0, -1));
258
- else
259
- constant = false;
260
- const share = this.expect(this.expr(shareNode, U8), U8, el);
261
- this.line(`${buf}[${at + 33}] = (uint8_t)(${share.c});`);
262
- });
263
- if (constant && shares !== 100n)
264
- this.fail(p.initializer, `creator shares add up to ${shares}; Metaplex requires 100`);
265
- creators = buf;
266
- ncreators = String(list.length);
236
+ const c = this.mplCreators(p.initializer);
237
+ creators = c.buf;
238
+ ncreators = c.count;
267
239
  }
268
240
  else if (p.name.text === "collection") {
269
241
  const key = this.expect(this.expr(p.initializer, PUBKEY), PUBKEY, p.initializer);
@@ -287,6 +259,145 @@ export class MetaplexEmitter extends TokenEmitter {
287
259
  this.line(`TS_TRY(ts_mpl_create_v3(params, a_${program.name}, a_${metadata.name}, a_${mint.name}, a_${mintAuth.name}, a_${payer.name}, a_${updateAuth.name}, a_${sys.name}, ${name.c}, ${symbol.c}, ${uri.c}, ${fee.c}, ${mutable.c}, ${creators}, ${ncreators}, ${collection}, ${sized}, ${seeds.name}, ${seeds.count}));`);
288
260
  return undefined;
289
261
  }
262
+ /** Metaplex creators `[{ address, verified, share }, …]` (1 to 5, shares adding up to 100): 34 bytes each. */
263
+ mplCreators(list0) {
264
+ if (!ts.isArrayLiteralExpression(list0))
265
+ this.fail(list0, "creators: [{ address, verified, share }, …] (an array literal)");
266
+ const list = list0.elements;
267
+ if (list.length < 1 || list.length > 5)
268
+ this.fail(list0, "Metaplex takes 1 to 5 creators");
269
+ const buf = this.tmp("creators");
270
+ this.line(`uint8_t ${buf}[${34 * list.length}];`);
271
+ let shares = 0n;
272
+ let constant = true;
273
+ list.forEach((el, i) => {
274
+ if (!ts.isObjectLiteralExpression(el))
275
+ this.fail(el, "a creator is { address, verified, share }");
276
+ const field = (k) => {
277
+ const q = el.properties.find((x) => ts.isPropertyAssignment(x) && ts.isIdentifier(x.name) && x.name.text === k);
278
+ const sh = el.properties.find((x) => ts.isShorthandPropertyAssignment(x) && x.name.text === k);
279
+ if (!q && !sh)
280
+ this.fail(el, `a creator needs ${k}`);
281
+ return q ? q.initializer : sh.name;
282
+ };
283
+ const at = 34 * i;
284
+ const key = this.expect(this.expr(field("address"), PUBKEY), PUBKEY, el);
285
+ this.line(`ts_memcpy(${buf} + ${at}, ${key.c}, 32);`);
286
+ const verified = this.expect(this.expr(field("verified"), BOOL), BOOL, el);
287
+ this.line(`${buf}[${at + 32}] = (${verified.c}) ? 1 : 0;`);
288
+ const shareNode = field("share");
289
+ if (ts.isBigIntLiteral(shareNode))
290
+ shares += BigInt(shareNode.text.slice(0, -1));
291
+ else
292
+ constant = false;
293
+ const share = this.expect(this.expr(shareNode, U8), U8, el);
294
+ this.line(`${buf}[${at + 33}] = (uint8_t)(${share.c});`);
295
+ });
296
+ if (constant && shares !== 100n)
297
+ this.fail(list0, `creator shares add up to ${shares}; Metaplex requires 100`);
298
+ return { buf, count: String(list.length) };
299
+ }
300
+ /**
301
+ * updateMetadataAccountsV2(metadata, updateAuthority, data | null, newUpdateAuthority | null, primarySaleHappened |
302
+ * null, isMutable | null, signerSeeds?): Anchor's `update_metadata_accounts_v2`. `data` is the whole new DataV2
303
+ * (`{ name, symbol, uri, sellerFeeBasisPoints, creators?, collection? }`); each null leaves that part as it is.
304
+ */
305
+ metadataUpdate(node, program) {
306
+ const a = node.arguments;
307
+ const usage = "updateMetadataAccountsV2(metadata, updateAuthority, data | null, newUpdateAuthority | null, primarySaleHappened | null, isMutable | null, signerSeeds?)";
308
+ if (a.length !== 6 && a.length !== 7)
309
+ this.fail(node, usage);
310
+ const metadata = this.accountParam(a[0], "the metadata account");
311
+ if (!isWritable(metadata.kind))
312
+ this.fail(a[0], "the metadata account must be Mut<AccountInfo>");
313
+ const ua = this.accountParam(a[1], "the update authority");
314
+ const isNull = (n) => n.kind === ts.SyntaxKind.NullKeyword;
315
+ let hasData = "false";
316
+ let name = "ts_str(NULL, 0)";
317
+ let symbol = name;
318
+ let uri = name;
319
+ let fee = "0";
320
+ let creators = "NULL";
321
+ let ncreators = "-1";
322
+ let collection = "NULL";
323
+ if (!isNull(a[2])) {
324
+ if (!ts.isObjectLiteralExpression(a[2]))
325
+ this.fail(a[2], "data is { name, symbol, uri, sellerFeeBasisPoints, creators?, collection? } or null");
326
+ const props = this.literalProps(a[2], ["name", "symbol", "uri", "sellerFeeBasisPoints", "creators", "collection"], "data");
327
+ for (const k of ["name", "symbol", "uri", "sellerFeeBasisPoints"])
328
+ if (!props.has(k))
329
+ this.fail(a[2], `data needs ${k} (it replaces the whole DataV2)`);
330
+ const text = (k) => {
331
+ const t = this.tmp("md");
332
+ this.line(`TS_Str ${t} = ${this.expect(this.expr(props.get(k), STRING), STRING, props.get(k)).c};`);
333
+ return t;
334
+ };
335
+ [name, symbol, uri] = ["name", "symbol", "uri"].map(text);
336
+ const f = this.tmp("fee");
337
+ this.line(`uint16_t ${f} = ${this.expect(this.expr(props.get("sellerFeeBasisPoints"), U16V), U16V, props.get("sellerFeeBasisPoints")).c};`);
338
+ fee = f;
339
+ if (props.has("creators"))
340
+ ({ buf: creators, count: ncreators } = this.mplCreators(props.get("creators")));
341
+ if (props.has("collection")) {
342
+ const key = this.expect(this.expr(props.get("collection"), PUBKEY), PUBKEY, props.get("collection"));
343
+ const t = this.tmp("coll");
344
+ this.line(`SolPubkey ${t} = *(${key.c});`);
345
+ collection = `&${t}`;
346
+ }
347
+ hasData = "true";
348
+ }
349
+ let next = "NULL";
350
+ if (!isNull(a[3])) {
351
+ const key = this.expect(this.expr(a[3], PUBKEY), PUBKEY, a[3]);
352
+ const t = this.tmp("ua");
353
+ this.line(`SolPubkey ${t} = *(${key.c});`);
354
+ next = `&${t}`;
355
+ }
356
+ const flag = (n) => (isNull(n) ? "-1" : `((${this.expect(this.expr(n, BOOL), BOOL, n).c}) ? 1 : 0)`);
357
+ const primary = flag(a[4]);
358
+ const mutable = flag(a[5]);
359
+ const seeds = this.signerSeeds(a[6], ua, a[1]);
360
+ this.line(`TS_TRY(ts_mpl_update_v2(params, a_${program.name}, a_${metadata.name}, a_${ua.name}, ${hasData}, ${name}, ${symbol}, ${uri}, ${fee}, ${creators}, ${ncreators}, ${collection}, ${next}, ${primary}, ${mutable}, ${seeds.name}, ${seeds.count}));`);
361
+ return undefined;
362
+ }
363
+ /**
364
+ * burnV1(authority, metadata, edition | null, mint, token, collectionMetadata | null, systemProgram,
365
+ * instructionsSysvar, tokenProgram, amount, signerSeeds?): Token Metadata's Burn (41, BurnArgs::V1) of a
366
+ * non-fungible (its master edition) or fungible asset held in `token`. The holder signs and gets the rent back.
367
+ */
368
+ metadataBurn(node, program) {
369
+ const a = node.arguments;
370
+ if (a.length !== 10 && a.length !== 11)
371
+ this.fail(node, "burnV1(authority, metadata, edition | null, mint, token, collectionMetadata | null, systemProgram, instructionsSysvar, tokenProgram, amount, signerSeeds?)");
372
+ const p = `a_${program.name}`;
373
+ const none = [p, false, false];
374
+ const authority = this.accountParam(a[0], "the authority (the holder)");
375
+ if (!isWritable(authority.kind))
376
+ this.fail(a[0], "the authority must be writable (Mut<...>): it gets the rent back");
377
+ // Burn: authority, collection metadata, metadata, edition, mint, token, master edition, master edition mint,
378
+ // master edition token, edition marker, token record (optional ones: the program id), system program,
379
+ // instructions sysvar, token program.
380
+ const metas = [
381
+ [`a_${authority.name}`, true, true],
382
+ this.mplMeta(a[5], program, "the collection metadata", true, false),
383
+ this.mplMeta(a[1], program, "the metadata", true, false),
384
+ this.mplMeta(a[2], program, "the edition", true, false),
385
+ this.mplMeta(a[3], program, "the mint", true, false),
386
+ this.mplMeta(a[4], program, "the token account", true, false),
387
+ none,
388
+ none,
389
+ none,
390
+ none,
391
+ none,
392
+ this.mplMeta(a[6], program, "the system program", false, false),
393
+ this.mplMeta(a[7], program, "the instructions sysvar", false, false),
394
+ this.mplMeta(a[8], program, "the token program", false, false),
395
+ ];
396
+ const data = this.mplData(node, 10, [{ bytes: [41, 0] }, { value: a[9], type: U64 }]);
397
+ const seeds = this.signerSeeds(a[10], authority, a[0]);
398
+ this.cpi(p, metas, data.buf, data.len, seeds);
399
+ return undefined;
400
+ }
290
401
  /** CreateMasterEditionV3 (17) and Verify (52) with VerificationArgs::CollectionV1. */
291
402
  metadataCollectionOp(node, program, method) {
292
403
  const a = node.arguments;
@@ -160,12 +160,16 @@ export function emitProgram(analysis, opts = {}) {
160
160
  out.push(` params.infos_cap = 0;`, ` params.metas = NULL;`);
161
161
  if ([...helperBodies, ...ixBodies].some((b) => b.includes("ts_claim_mut(")))
162
162
  out.push(limit > 64 ? ` ts_memzero(params.loaded_mut, sizeof(params.loaded_mut));` : ` params.loaded_mut = 0;`);
163
- const minDisc = Math.min(8, ...model.instructions.map((ix) => ix.discriminator.length));
164
- out.push(` if (params.data_len < ${minDisc}) TS_FAIL(TS_ERR_INSTRUCTION_MISSING, "TypeSOL: instruction data too short");`);
163
+ const fallback = model.instructions.find((ix) => ix.fallback);
164
+ const dispatched = model.instructions.filter((ix) => !ix.fallback);
165
+ const minDisc = Math.min(8, ...dispatched.map((ix) => ix.discriminator.length));
166
+ // With a @fallback, short data goes to it too (Anchor's dispatch); each comparison below checks the length.
167
+ if (!fallback)
168
+ out.push(` if (params.data_len < ${minDisc}) TS_FAIL(TS_ERR_INSTRUCTION_MISSING, "TypeSOL: instruction data too short");`);
165
169
  // Self-CPI events (emitCpi): accept the event instruction when its authority PDA signed it, like Anchor.
166
170
  if (model.instructions.some((ix) => ix.accounts.some((a) => a.kind.kind === "eventAuthority")))
167
171
  out.push(` if (params.data_len >= 8 && ts_mem_eq(params.data, TS_EVENT_IX_TAG, 8)) return ts_event_dispatch(&params);`);
168
- for (const ix of model.instructions) {
172
+ for (const ix of dispatched) {
169
173
  const n = ix.discriminator.length;
170
174
  // An 8-byte discriminator is one u64 compare (the data is little-endian bytes, the literal their u64 value).
171
175
  if (n === 8) {
@@ -178,7 +182,7 @@ export function emitProgram(analysis, opts = {}) {
178
182
  out.push(` if (params.data_len >= ${n} && ts_mem_eq(params.data, disc, ${n})) return ix_${ix.name}(&params);`);
179
183
  out.push(` }`);
180
184
  }
181
- out.push(` TS_FAIL(TS_ERR_INSTRUCTION_NOT_FOUND, "TypeSOL: unknown instruction");`);
185
+ out.push(fallback ? ` return ix_${fallback.name}(&params);` : ` TS_FAIL(TS_ERR_INSTRUCTION_NOT_FOUND, "TypeSOL: unknown instruction");`);
182
186
  out.push(`}`);
183
187
  return out.join("\n") + "\n";
184
188
  }
@@ -902,6 +902,14 @@ export class StatementEmitter extends CpiEmitter {
902
902
  continue;
903
903
  }
904
904
  const fn = ts.isCallExpression(init) ? this.exportName(init.expression) : undefined;
905
+ // The instruction's data as sent, discriminator included (a @fallback's input): a list of u8.
906
+ if (fn === "instructionData") {
907
+ if (init.arguments.length)
908
+ this.fail(init, "instructionData() takes no arguments");
909
+ this.line(`TS_VecArg ${c} = {params->data, (uint32_t)params->data_len};`);
910
+ this.scopes.at(-1).set(name, { c, type: { kind: "vecArg", elem: { kind: "int", name: "u8" } }, mutable: false });
911
+ continue;
912
+ }
905
913
  // A seed list to sign with more than once: `const vault = signer(["vault", owner.key, bump])`.
906
914
  if (fn === "signer") {
907
915
  if (mutable)
@@ -5,4 +5,12 @@ import { CreateEmitter } from "./create.js";
5
5
  export declare abstract class TokenEmitter extends CreateEmitter {
6
6
  protected tokenOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
7
7
  protected ataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
8
+ /** memoProgram.memo(text, signers?, signerSeeds?): SPL Memo v2, the UTF-8 text as data, each signer a signing account. */
9
+ protected memoOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
10
+ /**
11
+ * The Stake program (bincode: a u32 instruction tag): initialize, authorize, delegate, deactivate and withdraw, with
12
+ * the sysvar and config accounts it reads passed in, as anchor-spl's stake module does. Each authority signs (a PDA of
13
+ * this program with `signerSeeds`).
14
+ */
15
+ protected stakeOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
8
16
  }
@@ -1,3 +1,4 @@
1
+ import ts from "typescript";
1
2
  import { isWritable } from "../model.js";
2
3
  import { U64, U8, BOOL, PUBKEY, STRING, cBytes, optC } from "./shared.js";
3
4
  import { CreateEmitter } from "./create.js";
@@ -140,7 +141,74 @@ export class TokenEmitter extends CreateEmitter {
140
141
  return anyAcct(a[0], "the mint", true);
141
142
  };
142
143
  const none = { name: "NULL", count: 0 };
144
+ // The Token Group interface (spl-token-group-interface), which Token-2022 implements: 8-byte discriminators.
145
+ const grouped = (disc, fields, metas, seeds) => {
146
+ const { buf, len, put, finish } = this.byteBuffer("grp", 96, "TS_ERR_INSTRUCTION_DATA", "token group instruction");
147
+ const d = this.tmp("disc");
148
+ this.line(`static const uint8_t ${d}[8] = {${disc.join(", ")}};`);
149
+ put(d, "8", 8);
150
+ for (const f of fields)
151
+ f(put);
152
+ finish(node);
153
+ this.cpi(p, metas.map(([acc, w, sg]) => [`a_${acc.name}`, w, sg]), buf, len, seeds);
154
+ };
143
155
  switch (method) {
156
+ case "initializeTokenGroup": {
157
+ token2022Only();
158
+ if (a.length !== 5 && a.length !== 6)
159
+ this.fail(node, "initializeTokenGroup(group, mint, mintAuthority, updateAuthority | null, maxSize, signerSeeds?)");
160
+ const group = anyAcct(a[0], "the group", true);
161
+ const mint = anyAcct(a[1], "the mint", false);
162
+ const auth = this.accountParam(a[2], "the mint authority");
163
+ grouped([121, 113, 108, 39, 54, 51, 0, 4], [nonZeroKey(a[3]), value(a[4], U64)], [
164
+ [group, true, false],
165
+ [mint, false, false],
166
+ [auth, false, true],
167
+ ], this.signerSeeds(a[5], auth, a[2]));
168
+ return undefined;
169
+ }
170
+ case "initializeGroupMember": {
171
+ token2022Only();
172
+ if (a.length !== 5 && a.length !== 6)
173
+ this.fail(node, "initializeGroupMember(member, memberMint, memberMintAuthority, group, groupUpdateAuthority, signerSeeds?)");
174
+ const member = anyAcct(a[0], "the member", true);
175
+ const memberMint = anyAcct(a[1], "the member mint", false);
176
+ const mintAuth = this.accountParam(a[2], "the member mint's authority");
177
+ const group = anyAcct(a[3], "the group", true);
178
+ const groupAuth = this.accountParam(a[4], "the group's update authority");
179
+ grouped([152, 32, 222, 176, 223, 237, 116, 134], [], [
180
+ [member, true, false],
181
+ [memberMint, false, false],
182
+ [mintAuth, false, true],
183
+ [group, true, false],
184
+ [groupAuth, false, true],
185
+ ], a[5] ? this.signingSeeds(a[5]) : none);
186
+ return undefined;
187
+ }
188
+ case "updateGroupMaxSize": {
189
+ token2022Only();
190
+ if (a.length !== 3 && a.length !== 4)
191
+ this.fail(node, "updateGroupMaxSize(group, updateAuthority, maxSize, signerSeeds?)");
192
+ const group = anyAcct(a[0], "the group", true);
193
+ const auth = this.accountParam(a[1], "the update authority");
194
+ grouped([108, 37, 171, 143, 248, 30, 18, 110], [value(a[2], U64)], [
195
+ [group, true, false],
196
+ [auth, false, true],
197
+ ], this.signerSeeds(a[3], auth, a[1]));
198
+ return undefined;
199
+ }
200
+ case "updateGroupAuthority": {
201
+ token2022Only();
202
+ if (a.length !== 3 && a.length !== 4)
203
+ this.fail(node, "updateGroupAuthority(group, updateAuthority, next | null, signerSeeds?)");
204
+ const group = anyAcct(a[0], "the group", true);
205
+ const auth = this.accountParam(a[1], "the update authority");
206
+ grouped([161, 105, 88, 1, 237, 221, 216, 203], [nonZeroKey(a[2])], [
207
+ [group, true, false],
208
+ [auth, false, true],
209
+ ], this.signerSeeds(a[3], auth, a[1]));
210
+ return undefined;
211
+ }
144
212
  case "initializeTransferFeeConfig": {
145
213
  const mint = mintOnly(5, "initializeTransferFeeConfig(mint, configAuthority | null, withdrawAuthority | null, basisPoints, maximumFee)");
146
214
  this.model.options.set("pubkey", PUBKEY);
@@ -533,4 +601,125 @@ export class TokenEmitter extends CreateEmitter {
533
601
  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"}));`);
534
602
  return undefined;
535
603
  }
604
+ /** memoProgram.memo(text, signers?, signerSeeds?): SPL Memo v2, the UTF-8 text as data, each signer a signing account. */
605
+ memoOp(node, program, method) {
606
+ if (method !== "memo")
607
+ this.fail(node.expression, "the Memo program has memo(text, signers?, signerSeeds?)");
608
+ const a = node.arguments;
609
+ if (a.length < 1 || a.length > 3)
610
+ this.fail(node, "memo(text, signers?, signerSeeds?)");
611
+ const text = this.expect(this.expr(a[0], STRING), STRING, a[0]);
612
+ const list = a[1];
613
+ if (list && !ts.isArrayLiteralExpression(list))
614
+ this.fail(list, "the signers are a list of accounts: [authority, …]");
615
+ const signers = list ? list.elements.map((e) => this.accountParam(e, "a memo signer")) : [];
616
+ const t = this.tmp("memo");
617
+ this.line(`TS_Str ${t} = ${text.c};`);
618
+ const seeds = a[2] ? this.signingSeeds(a[2]) : { name: "NULL", count: 0 };
619
+ if (!signers.length)
620
+ this.line(`TS_TRY(ts_cpi(params, a_${program.name}, (uint8_t *)${t}.ptr, ${t}.len, NULL, 0, ${seeds.name}, ${seeds.count}));`);
621
+ else
622
+ this.cpi(`a_${program.name}`, signers.map((s) => [`a_${s.name}`, false, true]), `(uint8_t *)${t}.ptr`, `${t}.len`, seeds);
623
+ return undefined;
624
+ }
625
+ /**
626
+ * The Stake program (bincode: a u32 instruction tag): initialize, authorize, delegate, deactivate and withdraw, with
627
+ * the sysvar and config accounts it reads passed in, as anchor-spl's stake module does. Each authority signs (a PDA of
628
+ * this program with `signerSeeds`).
629
+ */
630
+ stakeOp(node, program, method) {
631
+ const a = node.arguments;
632
+ const acct = (i, what, mut = false) => {
633
+ const x = this.accountParam(a[i], what);
634
+ if (mut && !isWritable(x.kind))
635
+ this.fail(a[i], `${what} must be writable (Mut<...>)`);
636
+ return x;
637
+ };
638
+ const send = (tag, fields, metas, seeds) => {
639
+ const { buf, len, put, finish } = this.byteBuffer("stk", 116, "TS_ERR_INSTRUCTION_DATA", "stake instruction");
640
+ const t = this.tmp("tag");
641
+ this.line(`uint32_t ${t} = ${tag};`);
642
+ put(`&${t}`, "4", 4);
643
+ for (const f of fields)
644
+ f(put);
645
+ finish(node);
646
+ this.cpi(`a_${program.name}`, metas.map(([x, w, sg]) => [`a_${x.name}`, w, sg]), buf, len, seeds);
647
+ };
648
+ const value = (n, t) => (put) => this.serialize(this.expect(this.expr(n, t), t, n), n, put);
649
+ const zeros = (n) => (put) => {
650
+ const z = this.tmp("z");
651
+ this.line(`uint8_t ${z}[${n}] = {0};`);
652
+ put(z, String(n), n);
653
+ };
654
+ const arity = (n, usage) => {
655
+ if (a.length !== n && a.length !== n + 1)
656
+ this.fail(node, usage);
657
+ };
658
+ switch (method) {
659
+ case "initialize": {
660
+ // Authorized { staker, withdrawer }, Lockup { unix_timestamp, epoch, custodian }: no lockup.
661
+ if (a.length !== 4)
662
+ this.fail(node, "initialize(stake, rentSysvar, staker, withdrawer)");
663
+ send(0, [value(a[2], PUBKEY), value(a[3], PUBKEY), zeros(48)], [
664
+ [acct(0, "the stake account", true), true, false],
665
+ [acct(1, "the Rent sysvar"), false, false],
666
+ ], {
667
+ name: "NULL",
668
+ count: 0,
669
+ });
670
+ return undefined;
671
+ }
672
+ case "authorize": {
673
+ arity(5, 'authorize(stake, clockSysvar, authority, newAuthority, "staker" | "withdrawer", signerSeeds?)');
674
+ const kind = a[4];
675
+ const i = ts.isStringLiteral(kind) ? ["staker", "withdrawer"].indexOf(kind.text) : -1;
676
+ if (i < 0)
677
+ this.fail(kind, 'the authority to change is "staker" or "withdrawer"');
678
+ const auth = acct(2, "the authority");
679
+ const k = this.tmp("which");
680
+ send(1, [value(a[3], PUBKEY), (put) => (this.line(`uint32_t ${k} = ${i};`), put(`&${k}`, "4", 4))], [
681
+ [acct(0, "the stake account", true), true, false],
682
+ [acct(1, "the Clock sysvar"), false, false],
683
+ [auth, false, true],
684
+ ], this.signerSeeds(a[5], auth, a[2]));
685
+ return undefined;
686
+ }
687
+ case "delegate": {
688
+ arity(6, "delegate(stake, vote, clockSysvar, stakeHistorySysvar, stakeConfig, staker, signerSeeds?)");
689
+ const staker = acct(5, "the staker");
690
+ send(2, [], [
691
+ [acct(0, "the stake account", true), true, false],
692
+ [acct(1, "the vote account"), false, false],
693
+ [acct(2, "the Clock sysvar"), false, false],
694
+ [acct(3, "the StakeHistory sysvar"), false, false],
695
+ [acct(4, "the stake config account"), false, false],
696
+ [staker, false, true],
697
+ ], this.signerSeeds(a[6], staker, a[5]));
698
+ return undefined;
699
+ }
700
+ case "deactivate": {
701
+ arity(3, "deactivate(stake, clockSysvar, staker, signerSeeds?)");
702
+ const staker = acct(2, "the staker");
703
+ send(5, [], [
704
+ [acct(0, "the stake account", true), true, false],
705
+ [acct(1, "the Clock sysvar"), false, false],
706
+ [staker, false, true],
707
+ ], this.signerSeeds(a[3], staker, a[2]));
708
+ return undefined;
709
+ }
710
+ case "withdraw": {
711
+ arity(6, "withdraw(stake, to, clockSysvar, stakeHistorySysvar, withdrawer, lamports, signerSeeds?)");
712
+ const withdrawer = acct(4, "the withdrawer");
713
+ send(4, [value(a[5], U64)], [
714
+ [acct(0, "the stake account", true), true, false],
715
+ [acct(1, "the destination", true), true, false],
716
+ [acct(2, "the Clock sysvar"), false, false],
717
+ [acct(3, "the StakeHistory sysvar"), false, false],
718
+ [withdrawer, false, true],
719
+ ], this.signerSeeds(a[6], withdrawer, a[4]));
720
+ return undefined;
721
+ }
722
+ }
723
+ this.fail(node.expression, `the Stake program supports initialize, authorize, delegate, deactivate and withdraw, not ${method}`);
724
+ }
536
725
  }
@@ -94,11 +94,16 @@ function idlType(t, borshOption = false) {
94
94
  * composite accounts), a field of another group as `<group>_<field>` (how clients flatten groups), else the name.
95
95
  */
96
96
  function relativePath(path, from) {
97
- const at = path.indexOf("__");
98
- if (at < 0)
97
+ if (!path.includes("__"))
99
98
  return path;
100
- const group = path.slice(0, at);
101
- return group === from ? path.slice(at + 2) : `${group}_${path.slice(at + 2)}`;
99
+ if (from &&
100
+ path.startsWith(`${from}__`) &&
101
+ !path
102
+ .slice(from.length + 2)
103
+ .split(".")[0]
104
+ .includes("__"))
105
+ return path.slice(from.length + 2);
106
+ return path.replaceAll("__", "_");
102
107
  }
103
108
  function relativeSeeds(seeds, from) {
104
109
  if (!Array.isArray(seeds))
@@ -121,6 +126,12 @@ function accountEntry(ix, name, k, programAddress) {
121
126
  entry.address = "Sysvar1nstructions1111111111111111111111111";
122
127
  if (k.kind === "ataProgram")
123
128
  entry.address = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
129
+ if (k.kind === "memoProgram")
130
+ entry.address = "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr";
131
+ if (k.kind === "stakeProgram")
132
+ entry.address = "Stake11111111111111111111111111111111111111";
133
+ if (k.kind === "slotHashes")
134
+ entry.address = "SysvarS1otHashes111111111111111111111111111";
124
135
  if (k.kind === "metadataProgram")
125
136
  entry.address = "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s";
126
137
  if (k.kind === "coreProgram")
@@ -160,18 +171,20 @@ function accountEntry(ix, name, k, programAddress) {
160
171
  /** The instruction's account entries, an account group's fields nested under it: `{ name: "pool", accounts: [...] }`. */
161
172
  function nestGroups(ix, entry) {
162
173
  const out = [];
163
- let open;
174
+ // The groups open at the current account, outermost first: their paths and entry lists.
175
+ let open = [];
164
176
  for (const a of ix.accounts) {
165
- if (!a.group) {
166
- open = undefined;
167
- out.push(entry(a));
168
- continue;
177
+ const path = a.group?.path ?? [];
178
+ let keep = 0;
179
+ while (keep < open.length && keep < path.length && open[keep].path.join("__") === path.slice(0, keep + 1).join("__"))
180
+ keep++;
181
+ open = open.slice(0, keep);
182
+ for (let i = keep; i < path.length; i++) {
183
+ const g = { path: path.slice(0, i + 1), accounts: [] };
184
+ (i === 0 ? out : open[i - 1].accounts).push({ name: snakeCase(path[i]), accounts: g.accounts });
185
+ open.push(g);
169
186
  }
170
- if (open?.param !== a.group.param) {
171
- open = { param: a.group.param, accounts: [] };
172
- out.push({ name: snakeCase(a.group.param), accounts: open.accounts });
173
- }
174
- open.accounts.push(entry(a));
187
+ (open.length ? open[open.length - 1].accounts : out).push(entry(a));
175
188
  }
176
189
  return out;
177
190
  }
@@ -182,7 +195,9 @@ export function buildIdl(model, address, version = "0.1.0") {
182
195
  const idl = {
183
196
  address,
184
197
  metadata: { name: model.name, version, spec: "0.1.0", description: "Built with TypeSOL" },
185
- instructions: model.instructions.map((ix) => ({
198
+ instructions: model.instructions
199
+ .filter((ix) => !ix.fallback)
200
+ .map((ix) => ({
186
201
  name: ix.name,
187
202
  ...docsOf(ix.node),
188
203
  discriminator: ix.discriminator,
@@ -242,6 +242,18 @@ export type ParamKind = {
242
242
  kind: "programData";
243
243
  } | {
244
244
  kind: "ataProgram";
245
+ }
246
+ /** The SPL Memo program (v2). */
247
+ | {
248
+ kind: "memoProgram";
249
+ }
250
+ /** The native Stake program. */
251
+ | {
252
+ kind: "stakeProgram";
253
+ }
254
+ /** The SlotHashes sysvar account (too large for the sysvar syscalls, so read as an account). */
255
+ | {
256
+ kind: "slotHashes";
245
257
  } | {
246
258
  kind: "metadataProgram";
247
259
  } | {
@@ -314,11 +326,15 @@ export interface AccountParam {
314
326
  /** The parameter, or the field of an account group. */
315
327
  node: ts.ParameterDeclaration | ts.PropertySignature;
316
328
  constraints: Constraints;
317
- /** A field of an account group: the group parameter, the field, and the group's interface. `name` is `<param>__<field>`. */
329
+ /**
330
+ * A field of an account group: `path` the group parameter and the fields of groups inside it down to this one,
331
+ * `param` their names joined with "__", the field, and the group's interface. `name` is `<param>__<field>`.
332
+ */
318
333
  group?: {
319
334
  param: string;
320
335
  field: string;
321
336
  type: string;
337
+ path: string[];
322
338
  };
323
339
  /** Created in the body as a new keypair account (`create(payer, null, …)`), so it signs: the IDL says so. */
324
340
  signsInit?: boolean;
@@ -341,6 +357,8 @@ export type IdlSeed = {
341
357
  path: string;
342
358
  };
343
359
  export interface Instruction {
360
+ /** `@fallback`: run when no instruction's discriminator matches; not in the IDL. */
361
+ fallback?: boolean;
344
362
  name: string;
345
363
  discriminator: number[];
346
364
  accounts: AccountParam[];
package/dist/testing.d.ts CHANGED
@@ -19,8 +19,11 @@
19
19
  import anchor, { type Idl } from "@anchor-lang/core";
20
20
  import { type Address, type Instruction, type KeyPairSigner } from "@solana/kit";
21
21
  import { FailedTransactionMetadata, LiteSVM, TransactionMetadata } from "litesvm";
22
+ import { loadClonedAccounts } from "./tools/clone.js";
22
23
  import { type SvmConnection, svmConnection } from "./tools/svmrpc.js";
23
24
  export { type SvmConnection, svmConnection };
25
+ /** Load what `typesol clone` wrote (a directory of `<address>.json` accounts and `<address>.so` programs) into a LiteSVM. */
26
+ export { loadClonedAccounts };
24
27
  declare const BorshCoder: typeof anchor.BorshCoder;
25
28
  type BorshCoder = InstanceType<typeof BorshCoder>;
26
29
  export type Result = TransactionMetadata | FailedTransactionMetadata;
package/dist/testing.js CHANGED
@@ -23,9 +23,12 @@ import { createHash } from "node:crypto";
23
23
  import path from "node:path";
24
24
  import { fileURLToPath } from "node:url";
25
25
  import { TYPESOL_ERRORS } from "./tools/clientgen.js";
26
+ import { loadClonedAccounts } from "./tools/clone.js";
26
27
  import { svmConnection } from "./tools/svmrpc.js";
27
28
  import { buildWorkspace, findWorkspace } from "./workspace.js";
28
29
  export { svmConnection };
30
+ /** Load what `typesol clone` wrote (a directory of `<address>.json` accounts and `<address>.so` programs) into a LiteSVM. */
31
+ export { loadClonedAccounts };
29
32
  // @anchor-lang/core is CommonJS: Node 22 cannot import its classes by name from an installed ES module.
30
33
  const { BN, BorshCoder } = anchor;
31
34
  /**
@@ -64,6 +67,8 @@ export async function testProgram(program, from) {
64
67
  const svm = new LiteSVM();
65
68
  const programId = built.address;
66
69
  svm.addProgramFromFile(programId, built.result.soPath);
70
+ // Accounts and programs `typesol clone` copied from a cluster (tests/accounts), in place before the first test.
71
+ loadClonedAccounts(svm, ws.accounts);
67
72
  return programHarness(svm, programId, built.result.idl);
68
73
  }
69
74
  /** The same helpers for a program already loaded into `svm` at `programId` with this IDL. */