@typesol/cli 0.28.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +1 -1
  3. package/dist/compiler/analyze.d.ts +3 -1
  4. package/dist/compiler/analyze.js +21 -7
  5. package/dist/compiler/emit/alias.d.ts +48 -0
  6. package/dist/compiler/emit/alias.js +166 -0
  7. package/dist/compiler/emit/borsh.js +6 -3
  8. package/dist/compiler/emit/calls.js +21 -4
  9. package/dist/compiler/emit/cpi-core.d.ts +70 -0
  10. package/dist/compiler/emit/cpi-core.js +356 -0
  11. package/dist/compiler/emit/cpi.d.ts +3 -177
  12. package/dist/compiler/emit/cpi.js +13 -2721
  13. package/dist/compiler/emit/create.d.ts +39 -0
  14. package/dist/compiler/emit/create.js +548 -0
  15. package/dist/compiler/emit/function.d.ts +11 -2
  16. package/dist/compiler/emit/function.js +42 -7
  17. package/dist/compiler/emit/metaplex.d.ts +78 -0
  18. package/dist/compiler/emit/metaplex.js +1345 -0
  19. package/dist/compiler/emit/program.js +24 -4
  20. package/dist/compiler/emit/shared.d.ts +5 -1
  21. package/dist/compiler/emit/shared.js +11 -2
  22. package/dist/compiler/emit/statements.d.ts +0 -9
  23. package/dist/compiler/emit/statements.js +2 -53
  24. package/dist/compiler/emit/storage.d.ts +5 -20
  25. package/dist/compiler/emit/storage.js +40 -106
  26. package/dist/compiler/emit/token.d.ts +8 -0
  27. package/dist/compiler/emit/token.js +493 -0
  28. package/dist/compiler/model.d.ts +10 -2
  29. package/dist/compiler/model.js +7 -1
  30. package/dist/tools/portgen.js +3 -0
  31. package/docs/architecture.md +29 -1
  32. package/docs/audit.md +3 -2
  33. package/docs/case-study-multisig.md +31 -29
  34. package/docs/errors.md +3 -2
  35. package/docs/language.md +4 -3
  36. package/docs/migrate-from-anchor.md +3 -3
  37. package/docs/security-model.md +1 -1
  38. package/lib/typesol.d.ts +17 -6
  39. package/package.json +1 -1
  40. package/runtime/typesol_rt.h +85 -1
@@ -3,7 +3,7 @@ import { snakeCase } from "../analyze.js";
3
3
  import { decodeAddress } from "../../keys.js";
4
4
  import { INT_INFO, isScalar, isWritable, scalarSize, typeName, } from "../model.js";
5
5
  import { borshIdentical, borshMinSize } from "./borsh.js";
6
- import { MAX_ACCOUNTS, ATA_PROGRAM_BYTES, cBytes, cString, optC, fieldC, storageDecl, helperSignature, emptySizeC, vecLenCheck } from "./shared.js";
6
+ import { BOOL, accountLimit, ATA_PROGRAM_BYTES, cBytes, cString, optC, fieldC, storageDecl, helperSignature, emptySizeC, vecLenCheck } from "./shared.js";
7
7
  import { StatementEmitter } from "./statements.js";
8
8
  /**
9
9
  * One instruction or helper as a C function: the instruction prologue (account checks, constraints and
@@ -28,8 +28,9 @@ export class FunctionEmitter extends StatementEmitter {
28
28
  const head = [];
29
29
  head.push(`__attribute__((noinline)) static uint64_t ix_${ix.name}(TsParams *params) {`);
30
30
  const n = ix.accounts.length;
31
- if (n > MAX_ACCOUNTS)
32
- this.reporter.fail(ix.node, `instructions may take at most ${MAX_ACCOUNTS} accounts`);
31
+ const limit = accountLimit(this.model);
32
+ if (n > limit)
33
+ this.reporter.fail(ix.node, `instructions may take at most ${limit} accounts (const MAX_ACCOUNTS = …n raises it, up to 255)`);
33
34
  head.push(` if (params->ka_num < ${n}) TS_FAIL(TS_ERR_NOT_ENOUGH_ACCOUNTS, "TypeSOL: not enough accounts");`);
34
35
  for (const a of ix.accounts) {
35
36
  const v = `a_${a.name}`;
@@ -350,13 +351,15 @@ export class FunctionEmitter extends StatementEmitter {
350
351
  }
351
352
  if (ix.args.length)
352
353
  head.push(` (void)off;`);
353
- head.push(...this.constraintChecks(ix));
354
+ this.scopes = [new Map()];
355
+ const raw = this.rawConstraints(ix);
356
+ head.push(...this.constraintChecks(ix, raw.lines));
354
357
  this.scopes = [new Map()];
355
358
  // Two back-to-back markers measure what one marker costs, so the profiler can subtract it.
356
359
  if (this.profile)
357
360
  for (let i = 0; i < 2; i++)
358
361
  (this.line(`sol_log("ts:~");`), this.line(`sol_log_compute_units();`));
359
- for (const stmt of ix.node.body.statements)
362
+ for (const stmt of ix.node.body.statements.slice(raw.count))
360
363
  this.reporter.guard(() => this.statement(stmt, true));
361
364
  for (const name of this.pendingInit) {
362
365
  const k = this.accounts.get(name).kind;
@@ -405,10 +408,41 @@ export class FunctionEmitter extends StatementEmitter {
405
408
  }
406
409
  /**
407
410
  * Each account's constraints, account by account in parameter order and, within one account, in Anchor's order
408
- * (anchor-syn's `linearize`): seeds, associated token, has_one, owner, executable, address, token::, mint::.
411
+ * (anchor-syn's `linearize`): seeds, associated token, has_one, constraint, owner, executable, address, token::, mint::.
409
412
  * A transaction that breaks several checks then fails with the same error code as under Anchor.
410
413
  */
411
- constraintChecks(ix) {
414
+ /**
415
+ * `constraint(account, condition, error?)` statements at the start of the body: Anchor's `constraint = expr @ error`.
416
+ * Each is lowered here, with the arguments decoded, and runs with its account's constraints (after has_one, before
417
+ * owner), so a transaction breaking several checks gets Anchor's error code. The default error is ConstraintRaw (2003).
418
+ */
419
+ rawConstraints(ix) {
420
+ const lines = new Map();
421
+ let count = 0;
422
+ for (const stmt of ix.node.body.statements) {
423
+ const call = ts.isExpressionStatement(stmt) && ts.isCallExpression(stmt.expression) ? stmt.expression : undefined;
424
+ if (!call || this.exportName(call.expression) !== "constraint")
425
+ break;
426
+ count++;
427
+ this.reporter.guard(() => {
428
+ const [acct, cond, error] = call.arguments;
429
+ if (!acct || !cond || call.arguments.length > 3)
430
+ this.fail(call, "constraint(account, condition, error?) takes an account parameter, a condition and an optional error");
431
+ const a = ts.isIdentifier(acct) ? ix.accounts.find((x) => x.name === acct.text) : undefined;
432
+ if (!a)
433
+ this.fail(acct, "constraint's first argument is the account parameter the check belongs to (it runs with that account's checks)");
434
+ const mark = this.lines.length;
435
+ const hoistMark = this.hoisted.length;
436
+ const c = this.expect(this.expr(cond, BOOL), BOOL, cond);
437
+ const err = error ? this.errorRef(error) : { code: 2003, name: "ConstraintRaw", msg: "ConstraintRaw" };
438
+ this.line(`if (!${c.c}) TS_FAIL(${err.code}, ${cString(`Error ${err.code} ${err.name}: ${err.msg} (${this.location(call)})`)});`);
439
+ const emitted = [...this.hoisted.splice(hoistMark), ...this.lines.splice(mark)];
440
+ lines.set(a.name, [...(lines.get(a.name) ?? []), ...emitted]);
441
+ });
442
+ }
443
+ return { lines, count };
444
+ }
445
+ constraintChecks(ix, raw = new Map()) {
412
446
  const out = [];
413
447
  // Bumps found by Seeds<…> checks, declared ahead of the (possibly optional-guarded) checks for `acct.pdaBump`.
414
448
  const bumpDecls = [];
@@ -452,6 +486,7 @@ export class FunctionEmitter extends StatementEmitter {
452
486
  }
453
487
  if (k === "account")
454
488
  out.push(...hasOne);
489
+ out.push(...(raw.get(a.name) ?? []));
455
490
  if (c.owner) {
456
491
  out.push(` static const SolPubkey co_${a.name} = {${cBytes(c.owner.bytes)}};`);
457
492
  out.push(` if (!ts_key_eq(&a_${a.name}->owner, &co_${a.name})) TS_FAIL(TS_ERR_CONSTRAINT_OWNER, "TypeSOL: ${a.name} is not owned by the expected program");`);
@@ -0,0 +1,78 @@
1
+ import ts from "typescript";
2
+ import { type AccountParam, type ValueType } from "../model.js";
3
+ import { TokenEmitter } from "./token.js";
4
+ /** One piece of a Metaplex instruction's Borsh data: fixed bytes, or a value lowered and serialized in source order. */
5
+ type MplField = {
6
+ bytes: number[];
7
+ } | {
8
+ value: ts.Expression;
9
+ type: ValueType;
10
+ } | {
11
+ c: string;
12
+ n: string;
13
+ };
14
+ /** Metaplex: Token Metadata, Core (plugins and external plugins) and Bubblegum. */
15
+ export declare abstract class MetaplexEmitter extends TokenEmitter {
16
+ protected metadataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
17
+ /** CreateMasterEditionV3 (17) and Verify (52) with VerificationArgs::CollectionV1. */
18
+ protected metadataCollectionOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
19
+ /**
20
+ * One account of a Metaplex CPI: an account parameter, or `null` for an optional account left out
21
+ * (Metaplex programs take their own id in its place).
22
+ */
23
+ protected mplMeta(n: ts.Expression, program: AccountParam, what: string, writable: boolean, signer: boolean): [string, boolean, boolean];
24
+ /** Borsh fields into a fresh buffer: raw bytes ("u8:N" style) or lowered values. */
25
+ protected mplData(at: ts.Node, max: number, fields: MplField[]): {
26
+ buf: string;
27
+ len: string;
28
+ };
29
+ /**
30
+ * Borsh of one Metaplex Core plugin literal (`{ kind: "FreezeDelegate", frozen: true, authority?: … }`): the Plugin
31
+ * enum, then (`withAuthority`) the Option<PluginAuthority> that CreateV1's PluginAuthorityPair and AddPluginV1 take.
32
+ */
33
+ protected corePlugin(n: ts.Expression, withAuthority: boolean): MplField[];
34
+ /** CreateV1 / CreateCollectionV1 plugins: Option<Vec<PluginAuthorityPair>>. */
35
+ protected corePluginList(n: ts.Expression | undefined): MplField[];
36
+ /**
37
+ * Metaplex Core: assets and collections (with plugins), plugins and external plugin adapters added, updated, written
38
+ * and removed, transfer and burn. Each method is a row of CORE_OPS below: its accounts in order, its data.
39
+ */
40
+ protected coreOp(node: ts.CallExpression, core: AccountParam, method: string): undefined;
41
+ /**
42
+ * Core instructions: `args` fixed arguments (then an optional plugin list when `plugins`, then optional signer
43
+ * seeds), accounts in order (`[argument, label, writable, signer]`, or "self": the Core program, Core's "none" for an
44
+ * optional account), at most `max` bytes of data.
45
+ */
46
+ private coreOps;
47
+ /** The fields of a Core object literal (`{ kind: "AppData", … }`) by name. */
48
+ private coreProps;
49
+ /** PluginAuthority: "none" | "owner" | "updateAuthority" (literals), or an address. */
50
+ private coreAuthority;
51
+ private coreOption;
52
+ private coreSchema;
53
+ /** Vec<(HookableLifecycleEvent, ExternalCheckResult)>: `[{ event: "transfer", canReject: true }, …]`. */
54
+ private coreChecks;
55
+ /** ExtraAccount: `{ kind: "address", address, isSigner?, isWritable? }` or a preconfigured one (`{ kind: "owner" }`, …). */
56
+ private coreExtraAccount;
57
+ /**
58
+ * ExternalPluginAdapterInitInfo from a literal: `{ kind: "AppData", dataAuthority, schema? }`, `{ kind: "Oracle",
59
+ * baseAddress, checks, resultsOffset?, baseAddressConfig? }`, `{ kind: "LifecycleHook", hookedProgram, checks,
60
+ * extraAccounts?, dataAuthority?, schema? }` and the Linked forms (collections); `authority?` is the plugin's own.
61
+ */
62
+ protected coreExternalPlugin(n: ts.Expression): MplField[];
63
+ /** ExternalPluginAdapterKey: `{ kind: "AppData", dataAuthority }`, `{ kind: "Oracle", address }`, `{ kind: "LifecycleHook", address }`, … */
64
+ protected coreExternalKey(n: ts.Expression): MplField[];
65
+ /** The data written: Option<Vec<u8>> from a string, a Vec<u8> argument, or null (clears it). */
66
+ protected coreExternalData(n: ts.Expression): MplField[];
67
+ /** PluginType (u8) from a kind string literal: removePlugin(…, "FreezeDelegate"). */
68
+ protected corePluginType(n: ts.Expression): MplField;
69
+ /** Bubblegum (compressed NFTs on SPL account compression): createTree, mint (MintV1, no collection, no creators). */
70
+ protected bubblegumOp(node: ts.CallExpression, bg: AccountParam, method: string): undefined;
71
+ /** Bubblegum V2 (trees on mpl-account-compression with mpl-noop; optional Metaplex Core collections). */
72
+ protected bubblegumV2(node: ts.CallExpression, bg: AccountParam, method: string): undefined;
73
+ /** Vec<Creator> (address, verified, share) from a literal list; shares add up to 100 when literal. */
74
+ protected bubblegumCreators(creators: ts.Expression | undefined): MplField[];
75
+ /** UpdateArgs: every field optional (left out or null: unchanged). */
76
+ protected bubblegumUpdateArgs(n: ts.Expression): MplField[];
77
+ }
78
+ export {};