@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
@@ -0,0 +1,39 @@
1
+ import ts from "typescript";
2
+ import { type AccountParam } from "../model.js";
3
+ import { type Value } from "./shared.js";
4
+ import { CpiCoreEmitter } from "./cpi-core.js";
5
+ /** Creating accounts: `create` / `createIfNeeded` of program accounts, mints, token accounts and ATAs (with Token-2022 mint extensions), System transfers and createAccount. */
6
+ export declare abstract class CreateEmitter extends CpiCoreEmitter {
7
+ protected create(node: ts.CallExpression, target: AccountParam, topLevel: boolean, ifNeeded?: boolean): Value;
8
+ /**
9
+ * `vault.create(payer, seeds | null, mint, authority)` on `Init<TokenAccount>` and `mint.create(payer, seeds | null,
10
+ * decimals, authority, freezeAuthority | null)` on `Init<Mint>` (Anchor's `init` with `token::` / `mint::`
11
+ * constraints): a PDA of this program (or, with `null`, a new keypair account that signs), created owned by the
12
+ * instruction's token program and initialized. `createIfNeeded` on `InitIfNeeded<…>` does that unless the account
13
+ * exists, and then checks it is that PDA, owned by the token program, and has that mint and owner / those
14
+ * authorities and decimals (Anchor's init_if_needed checks). create returns the bump (0 for a keypair),
15
+ * createIfNeeded whether it created the account.
16
+ */
17
+ protected createToken(node: ts.CallExpression, target: AccountParam, topLevel: boolean): Value;
18
+ /**
19
+ * The extensions in `mint.create(…, { … })` (Anchor's `extensions::…` constraints): their values are evaluated now,
20
+ * in source order; the returned lines (each extension's Token-2022 initializer, mint writable, before
21
+ * InitializeMint2) run after the account is created, sized for exactly these extensions.
22
+ */
23
+ protected mintExtensions(lit: ts.ObjectLiteralExpression, tp: string, acct: string, ifNeeded?: boolean): {
24
+ space: number;
25
+ lines: string[];
26
+ checks: string[];
27
+ };
28
+ /**
29
+ * `ata.create(payer)` / `ata.createIfNeeded(payer)` on `Ata<Init|InitIfNeeded<TokenAccount>, "owner", "mint">`
30
+ * (Anchor's `init` / `init_if_needed` with `associated_token::…`). create always calls the ATA program's Create, which
31
+ * fails if the account exists. createIfNeeded calls it only when the account is still a System account (Anchor's
32
+ * test) and otherwise checks that the existing account is that ATA. Either way the account is then checked as an
33
+ * initialized token account of that mint and owner, and is a TokenAccount from here on.
34
+ */
35
+ protected createAta(node: ts.CallExpression, target: AccountParam, topLevel: boolean): Value | undefined;
36
+ protected systemTransfer(node: ts.CallExpression): undefined;
37
+ /** systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?) */
38
+ protected createAccount(node: ts.CallExpression, system: AccountParam): undefined;
39
+ }
@@ -0,0 +1,548 @@
1
+ import ts from "typescript";
2
+ import { heapVecOf } from "../analyze.js";
3
+ import { borshMinSize } from "./borsh.js";
4
+ import { isWritable } from "../model.js";
5
+ import { U64, U8, BOOL, PUBKEY, scalarStorageC, optC, emptySizeC } from "./shared.js";
6
+ import { CpiCoreEmitter } from "./cpi-core.js";
7
+ /** Creating accounts: `create` / `createIfNeeded` of program accounts, mints, token accounts and ATAs (with Token-2022 mint extensions), System transfers and createAccount. */
8
+ export class CreateEmitter extends CpiCoreEmitter {
9
+ create(node, target, topLevel, ifNeeded = false) {
10
+ const call = `${target.name}.${ifNeeded ? "createIfNeeded" : "create"}`;
11
+ if (!topLevel)
12
+ this.fail(node, `${call}(...) must be a top-level statement of the instruction`);
13
+ if (this.created.has(target.name))
14
+ this.fail(node, `${target.name} is already created`);
15
+ if (node.arguments.length !== 2 && node.arguments.length !== 3)
16
+ this.fail(node, `${call}(payer, seeds | null, space?) takes two or three arguments`);
17
+ const payer = this.accountParam(node.arguments[0], "the payer");
18
+ if (payer.kind.kind !== "signer" || !payer.kind.mut)
19
+ this.fail(node.arguments[0], "the payer must be a Mut<Signer>");
20
+ const s = target.kind.struct;
21
+ const keypair = node.arguments[1].kind === ts.SyntaxKind.NullKeyword;
22
+ if (keypair && ifNeeded)
23
+ this.fail(node.arguments[1], "createIfNeeded takes seeds: a keypair account cannot be checked to be the one meant");
24
+ const seeds = keypair ? undefined : this.seeds(node.arguments[1], 1);
25
+ if (seeds)
26
+ this.recordPda(target, seeds.idl);
27
+ const b = this.tmp("bump");
28
+ // The account's size: the struct's (8 + its fixed size, Anchor's InitSpace for @layout borsh), or Anchor's
29
+ // `space = …` when given, which must hold the struct.
30
+ // A @layout borsh struct with a Vec<T> has no fixed size: like Anchor's `init`, it takes `space`, at least its
31
+ // smallest Borsh form.
32
+ const unbounded = !!heapVecOf(s);
33
+ const need = unbounded ? `${8 + borshMinSize(s, this.model)}` : s.layout === "borsh" ? `8 + sizeof(TSS_${s.name})` : `8 + ${emptySizeC(s)}`;
34
+ let space = need;
35
+ const spaceArg = node.arguments[2];
36
+ if (unbounded && !spaceArg)
37
+ this.fail(node, `${s.name} holds a Vec<T>, so it has no fixed size: pass the account's space, create(payer, seeds, space) (Anchor's space = …)`);
38
+ if (spaceArg) {
39
+ if (s.vec)
40
+ this.fail(spaceArg, `${s.name} has a growable Vec: its size follows the Vec's length, so it takes no space argument`);
41
+ const raw = this.expr(spaceArg);
42
+ const v = this.expect(raw, U64, spaceArg);
43
+ const min = unbounded ? 8 + borshMinSize(s, this.model) : 8 + this.fieldBytes({ kind: "struct", name: s.name });
44
+ if (raw.literal !== undefined && raw.literal < BigInt(min))
45
+ this.fail(spaceArg, `${s.name} needs at least ${min} bytes (8 + its size)`);
46
+ space = this.tmp("space");
47
+ this.line(`uint64_t ${space} = ${v.c};`);
48
+ 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");`);
49
+ }
50
+ this.line(`uint8_t ${b};`);
51
+ const done = () => {
52
+ this.created.add(target.name);
53
+ this.pendingInit.delete(target.name);
54
+ this.bumps.set(target.name, b);
55
+ };
56
+ if (!seeds) {
57
+ // A new keypair account that signs the transaction (Anchor's `init` without seeds).
58
+ target.signsInit = true;
59
+ this.line(`TS_TRY(ts_create_owned(params, a_${payer.name}, a_${target.name}, NULL, 0, params->program_id, ${space}, &${b}));`);
60
+ this.line(`a_${target.name}->data_len = ${space};`);
61
+ this.line(`ts_memcpy(a_${target.name}->data, TS_DISC_${s.name}, 8);`);
62
+ done();
63
+ return { c: b, type: U8 };
64
+ }
65
+ if (ifNeeded) {
66
+ // Returns whether it was created now; an existing account must be this PDA, ours, and a ${s.name}.
67
+ const created = this.tmp("created");
68
+ this.line(`bool ${created};`);
69
+ 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}));`);
70
+ // An existing @layout borsh account is unpacked now (a new one starts from the zeroed struct).
71
+ if (s.layout === "borsh")
72
+ 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));`);
73
+ done();
74
+ return { c: created, type: BOOL };
75
+ }
76
+ this.line(`TS_TRY(ts_create_pda(params, a_${payer.name}, a_${target.name}, ${seeds.name}, ${seeds.count}, TS_DISC_${s.name}, ${space}, &${b}));`);
77
+ done();
78
+ return { c: b, type: U8 };
79
+ }
80
+ /**
81
+ * `vault.create(payer, seeds | null, mint, authority)` on `Init<TokenAccount>` and `mint.create(payer, seeds | null,
82
+ * decimals, authority, freezeAuthority | null)` on `Init<Mint>` (Anchor's `init` with `token::` / `mint::`
83
+ * constraints): a PDA of this program (or, with `null`, a new keypair account that signs), created owned by the
84
+ * instruction's token program and initialized. `createIfNeeded` on `InitIfNeeded<…>` does that unless the account
85
+ * exists, and then checks it is that PDA, owned by the token program, and has that mint and owner / those
86
+ * authorities and decimals (Anchor's init_if_needed checks). create returns the bump (0 for a keypair),
87
+ * createIfNeeded whether it created the account.
88
+ */
89
+ createToken(node, target, topLevel) {
90
+ const isMint = target.kind.kind === "mint";
91
+ const ifNeeded = target.kind.init === "ifNeeded";
92
+ const call = `${target.name}.${ifNeeded ? "createIfNeeded" : "create"}`;
93
+ const usage = isMint
94
+ ? `${call}(payer, seeds | null, decimals, mintAuthority, freezeAuthority | null, extensions?, tokenProgram?)`
95
+ : `${call}(payer, seeds | null, mint, authority, tokenProgram?)`;
96
+ if (!topLevel)
97
+ this.fail(node, `${call}(...) must be a top-level statement of the instruction`);
98
+ if (this.created.has(target.name))
99
+ this.fail(node, `${target.name} is already created`);
100
+ const a = node.arguments;
101
+ if (!isMint && a.length === 1)
102
+ this.fail(node, `${call}(payer) creates an associated token account: wrap it in Ata<…, "owner", "mint">; or call ${usage.slice(call.length)}`);
103
+ // A mint may list its Token-2022 extensions next (Anchor's `extensions::…`), as an object literal.
104
+ const bare = (e) => e && (ts.isAsExpression(e) || ts.isParenthesizedExpression(e) || ts.isSatisfiesExpression(e)) ? bare(e.expression) : e;
105
+ const ext5 = bare(a[5]);
106
+ const extArg = isMint && ext5 && ts.isObjectLiteralExpression(ext5) ? ext5 : undefined;
107
+ const fixedArgs = isMint ? (extArg ? 6 : 5) : 4;
108
+ if (a.length !== fixedArgs && a.length !== fixedArgs + 1)
109
+ this.fail(node, usage);
110
+ const payer = this.accountParam(a[0], "the payer");
111
+ if (payer.kind.kind !== "signer" || !payer.kind.mut)
112
+ this.fail(a[0], "the payer must be a Mut<Signer>");
113
+ // The token program: named as the last argument, or the instruction's only token program parameter.
114
+ let programs = this.ix.accounts.filter((p) => p.kind.kind === "tokenProgram");
115
+ if (a[fixedArgs]) {
116
+ const named = this.accountParam(a[fixedArgs], "the token program");
117
+ if (named.kind.kind !== "tokenProgram")
118
+ this.fail(a[fixedArgs], "pass a TokenProgram, Token2022Program or TokenInterface parameter");
119
+ programs = [named];
120
+ }
121
+ if (programs.length !== 1)
122
+ this.fail(node, `${call}(...) needs one token program: pass it as the last argument, or have exactly one token program parameter`);
123
+ if (programs[0].optional)
124
+ this.fail(programs[0].node, `${call}(...) needs "${programs[0].name}": it cannot be optional`);
125
+ if (!this.ix.accounts.some((p) => p.kind.kind === "system" && !p.optional))
126
+ this.fail(node, `${call}(...) needs a SystemProgram parameter`);
127
+ const tp = `a_${programs[0].name}`;
128
+ const acct = `a_${target.name}`;
129
+ // Seeds, then the values, in source order.
130
+ let seeds = { name: "NULL", count: 0 };
131
+ if (a[1].kind !== ts.SyntaxKind.NullKeyword) {
132
+ const s = this.seeds(a[1], 1);
133
+ this.recordPda(target, s.idl);
134
+ seeds = s;
135
+ }
136
+ else
137
+ target.signsInit = true;
138
+ const vals = [];
139
+ const take = (n, t) => {
140
+ const mark = this.lines.length;
141
+ // The account's own address is known before it exists (`vault.create(payer, seeds, mint, vault.key)`).
142
+ const own = ts.isPropertyAccessExpression(n) && n.name.text === "key" && ts.isIdentifier(n.expression) && n.expression.text === target.name;
143
+ const v = own ? { c: `(&${acct}->key)`, type: PUBKEY } : this.expect(this.expr(n, t), t, n);
144
+ for (let j = 0; j < vals.length; j++)
145
+ vals[j] = this.settle(vals[j], mark);
146
+ vals.push(v);
147
+ };
148
+ let mint;
149
+ const extLines = [];
150
+ const extChecks = [];
151
+ let mintSpace = "TS_MINT_LEN";
152
+ if (isMint) {
153
+ take(a[2], U8);
154
+ take(a[3], PUBKEY);
155
+ if (a[4].kind !== ts.SyntaxKind.NullKeyword)
156
+ take(a[4], PUBKEY);
157
+ if (extArg) {
158
+ if (programs[0].kind.kind === "tokenProgram" && programs[0].kind.flavor === "token")
159
+ this.fail(extArg, "mint extensions are Token-2022's; use Token2022Program or TokenInterface");
160
+ const ext = this.mintExtensions(extArg, tp, acct, ifNeeded);
161
+ mintSpace = String(ext.space);
162
+ extLines.push(...ext.lines);
163
+ extChecks.push(...ext.checks);
164
+ }
165
+ }
166
+ else {
167
+ mint = this.accountParam(a[2], "the mint");
168
+ if (mint.kind.kind !== "mint")
169
+ this.fail(a[2], "pass the Mint parameter the account will hold");
170
+ take(a[3], PUBKEY);
171
+ }
172
+ const b = this.tmp("bump");
173
+ this.line(`uint8_t ${b};`);
174
+ const created = this.tmp("created");
175
+ const createLines = [];
176
+ if (isMint) {
177
+ const [decimals, authority, freeze] = vals;
178
+ 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"}));`);
179
+ if (ifNeeded) {
180
+ this.line(`bool ${created} = ts_key_eq(&${acct}->owner, &TS_SYSTEM_PROGRAM_ID);`);
181
+ this.line(`if (${created}) {`);
182
+ for (const l of createLines)
183
+ this.line(` ${l}`);
184
+ this.line(`} else {`);
185
+ this.line(` TS_TRY(ts_token_existing(params, ${acct}, ${tp}, ${seeds.name}, ${seeds.count}, &${b}));`);
186
+ this.line(` TS_TRY(ts_check_mint(${acct}));`);
187
+ this.line(` TS_TRY(ts_check_mint_is(${acct}, (uint8_t)(${decimals.c}), ${authority.c}, ${freeze ? freeze.c : "NULL"}));`);
188
+ for (const l of extChecks)
189
+ this.line(` ${l}`);
190
+ this.line(`}`);
191
+ }
192
+ else
193
+ for (const l of createLines)
194
+ this.line(l);
195
+ }
196
+ else {
197
+ const [authority] = vals;
198
+ const space = this.tmp("space");
199
+ 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}));`);
200
+ if (ifNeeded) {
201
+ this.line(`bool ${created} = ts_key_eq(&${acct}->owner, &TS_SYSTEM_PROGRAM_ID);`);
202
+ this.line(`if (${created}) {`);
203
+ for (const l of createLines)
204
+ this.line(` ${l}`);
205
+ this.line(`} else {`);
206
+ this.line(` TS_TRY(ts_token_existing(params, ${acct}, ${tp}, ${seeds.name}, ${seeds.count}, &${b}));`);
207
+ this.line(` TS_TRY(ts_check_token_account(${acct}));`);
208
+ 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}");`);
209
+ this.line(` if (!ts_key_eq(ts_token_owner(${acct}), ${authority.c})) TS_FAIL(TS_ERR_TOKEN_OWNER, "TypeSOL: ${target.name} has another owner");`);
210
+ this.line(`}`);
211
+ }
212
+ else
213
+ for (const l of createLines)
214
+ this.line(l);
215
+ }
216
+ this.created.add(target.name);
217
+ this.pendingInit.delete(target.name);
218
+ this.bumps.set(target.name, b);
219
+ return ifNeeded ? { c: created, type: BOOL } : { c: b, type: U8 };
220
+ }
221
+ /**
222
+ * The extensions in `mint.create(…, { … })` (Anchor's `extensions::…` constraints): their values are evaluated now,
223
+ * in source order; the returned lines (each extension's Token-2022 initializer, mint writable, before
224
+ * InitializeMint2) run after the account is created, sized for exactly these extensions.
225
+ */
226
+ mintExtensions(lit, tp, acct, ifNeeded = false) {
227
+ const optKey = { kind: "option", inner: PUBKEY };
228
+ this.model.options.set("pubkey", PUBKEY);
229
+ // name: [extension type length, initializer tag, the fields an object value takes ([] for a plain value)]
230
+ const KINDS = {
231
+ transferFee: { len: 108, fields: ["configAuthority", "withdrawAuthority", "basisPoints", "maximumFee"] },
232
+ closeAuthority: { len: 32, fields: [] },
233
+ defaultAccountState: { len: 1, fields: [] },
234
+ nonTransferable: { len: 0, fields: [] },
235
+ interestBearing: { len: 52, fields: ["rateAuthority", "rate"] },
236
+ permanentDelegate: { len: 32, fields: [] },
237
+ transferHook: { len: 64, fields: ["authority", "programId"] },
238
+ metadataPointer: { len: 64, fields: ["authority", "metadataAddress"] },
239
+ groupPointer: { len: 64, fields: ["authority", "groupAddress"] },
240
+ groupMemberPointer: { len: 64, fields: ["authority", "memberAddress"] },
241
+ };
242
+ const given = new Map();
243
+ for (const p of lit.properties) {
244
+ const value = ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) ? p.initializer : ts.isShorthandPropertyAssignment(p) ? p.name : undefined;
245
+ if (!value || !p.name || !ts.isIdentifier(p.name))
246
+ this.fail(p, "write the extensions as `name: value` entries");
247
+ if (!KINDS[p.name.text])
248
+ this.fail(p.name, `mint extensions: ${Object.keys(KINDS).join(", ")}`);
249
+ given.set(p.name.text, value);
250
+ }
251
+ const U16 = { kind: "int", name: "u16" };
252
+ const I16 = { kind: "int", name: "i16" };
253
+ // Values in source order, held in temporaries; the CPIs come later.
254
+ const held = new Map();
255
+ const keyTmp = (e, nonZero) => {
256
+ // OptionalNonZeroPubkey (32 bytes, zero for none) or COption (a tag byte, then 32).
257
+ const v = this.expect(this.expr(e, optKey), optKey, e);
258
+ const t = this.tmp("xk");
259
+ this.line(`${optC(PUBKEY)} ${t} = ${v.c};`);
260
+ if (!nonZero)
261
+ return t;
262
+ const z = this.tmp("xz");
263
+ this.line(`SolPubkey ${z};`);
264
+ this.line(`if (${t}.some) ${z} = ${t}.v; else ts_memzero(&${z}, 32);`);
265
+ return z;
266
+ };
267
+ const scalarTmp = (e, t) => {
268
+ const v = this.expect(this.expr(e, t), t, e);
269
+ const n = this.tmp("xv");
270
+ this.line(`${scalarStorageC(t)} ${n} = ${v.c};`);
271
+ return n;
272
+ };
273
+ for (const [name, e] of given) {
274
+ const k = KINDS[name];
275
+ const vals = new Map();
276
+ if (k.fields.length) {
277
+ if (!ts.isObjectLiteralExpression(e))
278
+ this.fail(e, `${name}: { ${k.fields.join(", ")} }`);
279
+ const props = new Map();
280
+ for (const p of e.properties) {
281
+ const value = ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) ? p.initializer : ts.isShorthandPropertyAssignment(p) ? p.name : undefined;
282
+ if (!value || !p.name || !ts.isIdentifier(p.name) || !k.fields.includes(p.name.text))
283
+ this.fail(p, `${name}: { ${k.fields.join(", ")} }`);
284
+ props.set(p.name.text, value);
285
+ }
286
+ for (const f of k.fields)
287
+ if (!props.has(f))
288
+ this.fail(e, `${name} needs ${f}`);
289
+ for (const [f, v] of props) {
290
+ if (f === "basisPoints") {
291
+ const t = scalarTmp(v, U16);
292
+ this.line(`if (${t} > 10000) TS_FAIL(TS_ERR_INSTRUCTION_DATA, "TypeSOL: transfer fee above 10000 basis points");`);
293
+ vals.set(f, t);
294
+ }
295
+ else if (f === "maximumFee")
296
+ vals.set(f, scalarTmp(v, U64));
297
+ else if (f === "rate")
298
+ vals.set(f, scalarTmp(v, I16));
299
+ else
300
+ vals.set(f, keyTmp(v, name !== "transferFee"));
301
+ }
302
+ }
303
+ else if (name === "closeAuthority")
304
+ vals.set("v", keyTmp(e, false));
305
+ else if (name === "permanentDelegate") {
306
+ const v = this.expect(this.expr(e, PUBKEY), PUBKEY, e);
307
+ const t = this.tmp("xk");
308
+ this.line(`SolPubkey ${t} = *(${v.c});`);
309
+ vals.set("v", t);
310
+ }
311
+ else if (name === "defaultAccountState") {
312
+ const v = this.expect(this.expr(e, BOOL), BOOL, e);
313
+ const t = this.tmp("xs");
314
+ this.line(`uint8_t ${t} = (${v.c}) ? 2 : 1;`); // frozen: AccountState::Frozen, else Initialized
315
+ vals.set("v", t);
316
+ }
317
+ else if (!(e.kind === ts.SyntaxKind.TrueKeyword))
318
+ this.fail(e, "nonTransferable: true");
319
+ held.set(name, vals);
320
+ }
321
+ // Each initializer: its bytes, then a CPI with the mint as the only (writable) account.
322
+ const lines = [];
323
+ const cpi = (bytes) => {
324
+ const total = bytes.reduce((n, [, k]) => n + k, 0);
325
+ const buf = this.tmp("xd");
326
+ lines.push(`{ uint8_t ${buf}[${total}]; uint64_t at = 0;`);
327
+ for (const [src, n] of bytes)
328
+ lines.push(` ts_memcpy(${buf} + at, ${src}, ${n}); at += ${n};`);
329
+ lines.push(` SolAccountMeta m[1] = {{&${acct}->key, true, false}};`, ` TS_TRY(ts_cpi(params, ${tp}, ${buf}, at, m, 1, NULL, 0)); }`);
330
+ };
331
+ const tag = (n) => `(const uint8_t[]){${n}}`;
332
+ const coption = (t) => [
333
+ [`(const uint8_t[]){${t}.some ? 1 : 0}`, 1],
334
+ [`&${t}.v`, 32],
335
+ ];
336
+ let space = 0;
337
+ for (const name of Object.keys(KINDS)) {
338
+ const v = held.get(name);
339
+ if (!v)
340
+ continue;
341
+ space += 4 + KINDS[name].len;
342
+ switch (name) {
343
+ case "transferFee":
344
+ cpi([
345
+ [tag(26), 1],
346
+ [tag(0), 1],
347
+ ...coption(v.get("configAuthority")),
348
+ ...coption(v.get("withdrawAuthority")),
349
+ [`&${v.get("basisPoints")}`, 2],
350
+ [`&${v.get("maximumFee")}`, 8],
351
+ ]);
352
+ break;
353
+ case "closeAuthority":
354
+ cpi([[tag(25), 1], ...coption(v.get("v"))]);
355
+ break;
356
+ case "defaultAccountState":
357
+ cpi([
358
+ [tag(28), 1],
359
+ [tag(0), 1],
360
+ [`&${v.get("v")}`, 1],
361
+ ]);
362
+ break;
363
+ case "nonTransferable":
364
+ cpi([[tag(32), 1]]);
365
+ break;
366
+ case "interestBearing":
367
+ cpi([
368
+ [tag(33), 1],
369
+ [tag(0), 1],
370
+ [`&${v.get("rateAuthority")}`, 32],
371
+ [`&${v.get("rate")}`, 2],
372
+ ]);
373
+ break;
374
+ case "permanentDelegate":
375
+ cpi([
376
+ [tag(35), 1],
377
+ [`&${v.get("v")}`, 32],
378
+ ]);
379
+ break;
380
+ default: {
381
+ const t = { transferHook: 36, metadataPointer: 39, groupPointer: 40, groupMemberPointer: 41 }[name];
382
+ const [f1, f2] = KINDS[name].fields;
383
+ cpi([
384
+ [tag(t), 1],
385
+ [tag(0), 1],
386
+ [`&${v.get(f1)}`, 32],
387
+ [`&${v.get(f2)}`, 32],
388
+ ]);
389
+ }
390
+ }
391
+ }
392
+ // An existing mint (createIfNeeded) is checked as Anchor's `extensions::…` constraints check it: the extension must
393
+ // be there (its Anchor code) and each key must match (the next codes). Anchor has constraints for these six only.
394
+ const CHECKS = {
395
+ groupPointer: {
396
+ type: 20,
397
+ code: 2024,
398
+ fields: [
399
+ ["authority", 0],
400
+ ["groupAddress", 32],
401
+ ],
402
+ },
403
+ groupMemberPointer: {
404
+ type: 21,
405
+ code: 2027,
406
+ fields: [
407
+ ["authority", 0],
408
+ ["memberAddress", 32],
409
+ ],
410
+ },
411
+ metadataPointer: {
412
+ type: 18,
413
+ code: 2030,
414
+ fields: [
415
+ ["authority", 0],
416
+ ["metadataAddress", 32],
417
+ ],
418
+ },
419
+ closeAuthority: { type: 3, code: 2033, fields: [["v", 0]] },
420
+ permanentDelegate: { type: 12, code: 2035, fields: [["v", 0]] },
421
+ transferHook: {
422
+ type: 14,
423
+ code: 2037,
424
+ fields: [
425
+ ["authority", 0],
426
+ ["programId", 32],
427
+ ],
428
+ },
429
+ };
430
+ const checks = [];
431
+ if (ifNeeded)
432
+ for (const [name, v] of held) {
433
+ const c = CHECKS[name];
434
+ if (!c)
435
+ this.fail(lit, `${name} cannot be checked on an existing mint (Anchor has no constraint for it): create the mint with create(…)`);
436
+ 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"); }`);
437
+ c.fields.forEach(([f, at], i) => {
438
+ const held = v.get(f);
439
+ // The value given: a nonzero-or-zero key, a COption (close authority) or a plain key (permanent delegate).
440
+ const want = name === "closeAuthority" ? `(${held}.some ? ${held}.v : (SolPubkey){0})` : held;
441
+ 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"); }`);
442
+ });
443
+ }
444
+ // Base account (165, the mint padded to an account's size), the account type byte, then each TLV entry.
445
+ return { space: 165 + 1 + space, lines, checks };
446
+ }
447
+ /**
448
+ * `ata.create(payer)` / `ata.createIfNeeded(payer)` on `Ata<Init|InitIfNeeded<TokenAccount>, "owner", "mint">`
449
+ * (Anchor's `init` / `init_if_needed` with `associated_token::…`). create always calls the ATA program's Create, which
450
+ * fails if the account exists. createIfNeeded calls it only when the account is still a System account (Anchor's
451
+ * test) and otherwise checks that the existing account is that ATA. Either way the account is then checked as an
452
+ * initialized token account of that mint and owner, and is a TokenAccount from here on.
453
+ */
454
+ createAta(node, target, topLevel) {
455
+ const ifNeeded = target.kind.init === "ifNeeded";
456
+ const call = `${target.name}.${ifNeeded ? "createIfNeeded" : "create"}`;
457
+ if (!topLevel)
458
+ this.fail(node, `${call}(...) must be a top-level statement of the instruction`);
459
+ if (this.created.has(target.name))
460
+ this.fail(node, `${target.name} is already created`);
461
+ if (node.arguments.length !== 1)
462
+ this.fail(node, `${call}(payer) takes the payer`);
463
+ const payer = this.accountParam(node.arguments[0], "the payer");
464
+ if (payer.kind.kind !== "signer" || !payer.kind.mut)
465
+ this.fail(node.arguments[0], "the payer must be a Mut<Signer>");
466
+ const need = (kind, what) => {
467
+ const p = this.ix.accounts.find((o) => o.kind.kind === kind);
468
+ if (!p)
469
+ this.fail(node, `${call}(...) needs ${what} parameter`);
470
+ if (p.optional)
471
+ this.fail(p.node, `${call}(...) needs "${p.name}": it cannot be optional`);
472
+ return p;
473
+ };
474
+ const ataProgram = need("ataProgram", "an AssociatedTokenProgram");
475
+ const system = need("system", "a SystemProgram");
476
+ const tokenProgram = need("tokenProgram", "a token program (TokenProgram, Token2022Program or TokenInterface)");
477
+ // The address is derived under the token program: with two, which one the mint uses is not known here.
478
+ const tokenPrograms = this.ix.accounts.filter((o) => o.kind.kind === "tokenProgram");
479
+ if (tokenPrograms.length > 1)
480
+ this.fail(node, `${call}(...) needs exactly one token program parameter (found ${tokenPrograms.map((o) => o.name).join(", ")}); use TokenInterface`);
481
+ const { owner, mint } = target.constraints.ata;
482
+ const a = `a_${target.name}`;
483
+ 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));`;
484
+ let result;
485
+ if (ifNeeded) {
486
+ const created = this.tmp("created");
487
+ this.line(`bool ${created} = ts_key_eq(&${a}->owner, &TS_SYSTEM_PROGRAM_ID);`);
488
+ this.line(`if (${created}) {`);
489
+ this.line(` ${create}`);
490
+ this.line(`} else {`);
491
+ this.line(` SolPubkey ata_${target.name};`);
492
+ this.line(` TS_TRY(ts_ata_address(&a_${owner}->key, &a_${mint}->key, &a_${tokenProgram.name}->key, &ata_${target.name}));`);
493
+ 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}");`);
494
+ this.line(`}`);
495
+ result = { c: created, type: BOOL };
496
+ }
497
+ else
498
+ this.line(create);
499
+ this.line(`TS_TRY(ts_check_token_account(${a}));`);
500
+ 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}");`);
501
+ 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}");`);
502
+ this.created.add(target.name);
503
+ this.pendingInit.delete(target.name);
504
+ return result;
505
+ }
506
+ systemTransfer(node) {
507
+ if (node.arguments.length !== 3)
508
+ this.fail(node, "transfer(from, to, lamports) takes three arguments");
509
+ const [fromN, toN, amtN] = node.arguments;
510
+ const from = this.accountParam(fromN, "transfer's source");
511
+ if (from.kind.kind !== "signer" || !from.kind.mut)
512
+ this.fail(fromN, "the source must be a Mut<Signer>");
513
+ const to = this.accountParam(toN, "transfer's destination");
514
+ if (!isWritable(to.kind))
515
+ this.fail(toN, "the destination must be writable (Mut<...>)");
516
+ const amt = this.expect(this.expr(amtN, U64), U64, amtN);
517
+ this.line(`TS_TRY(ts_system_transfer(params, a_${from.name}, a_${to.name}, ${amt.c}));`);
518
+ return undefined;
519
+ }
520
+ /** systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?) */
521
+ createAccount(node, system) {
522
+ const a = node.arguments;
523
+ if (a.length !== 5 && a.length !== 6)
524
+ this.fail(node, "createAccount(payer, account, lamports, space, owner, signerSeeds?)");
525
+ const payer = this.accountParam(a[0], "the payer");
526
+ if (payer.kind.kind !== "signer" || !payer.kind.mut)
527
+ this.fail(a[0], "the payer must be a Mut<Signer>");
528
+ const acct = this.accountParam(a[1], "the new account");
529
+ if (!isWritable(acct.kind))
530
+ this.fail(a[1], "the new account must be writable (Mut<Signer> or Mut<AccountInfo>)");
531
+ if (acct.kind.kind !== "signer" && a.length !== 6)
532
+ this.fail(a[1], "the new account must sign: a Mut<Signer> keypair, or pass signerSeeds for a PDA");
533
+ const { buf, len, put, finish } = this.byteBuffer("sys", 52, "TS_ERR_INSTRUCTION_DATA", "system instruction");
534
+ const tag = this.tmp("tag");
535
+ this.line(`uint32_t ${tag} = 0; /* CreateAccount */`);
536
+ put(`&${tag}`, "4", 4);
537
+ this.serialize(this.expect(this.expr(a[2], U64), U64, a[2]), a[2], put);
538
+ this.serialize(this.expect(this.expr(a[3], U64), U64, a[3]), a[3], put);
539
+ this.serialize(this.expect(this.expr(a[4], PUBKEY), PUBKEY, a[4]), a[4], put);
540
+ finish(node);
541
+ const seeds = a.length === 6 ? this.signingSeeds(a[5]) : { name: "NULL", count: 0 };
542
+ this.cpi(`a_${system.name}`, [
543
+ [`a_${payer.name}`, true, true],
544
+ [`a_${acct.name}`, true, true],
545
+ ], buf, len, seeds);
546
+ return undefined;
547
+ }
548
+ }
@@ -11,10 +11,19 @@ export declare class FunctionEmitter extends StatementEmitter {
11
11
  protected epilogue(): string[];
12
12
  /**
13
13
  * Each account's constraints, account by account in parameter order and, within one account, in Anchor's order
14
- * (anchor-syn's `linearize`): seeds, associated token, has_one, owner, executable, address, token::, mint::.
14
+ * (anchor-syn's `linearize`): seeds, associated token, has_one, constraint, owner, executable, address, token::, mint::.
15
15
  * A transaction that breaks several checks then fails with the same error code as under Anchor.
16
16
  */
17
- protected constraintChecks(ix: Instruction): string[];
17
+ /**
18
+ * `constraint(account, condition, error?)` statements at the start of the body: Anchor's `constraint = expr @ error`.
19
+ * Each is lowered here, with the arguments decoded, and runs with its account's constraints (after has_one, before
20
+ * owner), so a transaction breaking several checks gets Anchor's error code. The default error is ConstraintRaw (2003).
21
+ */
22
+ protected rawConstraints(ix: Instruction): {
23
+ lines: Map<string, string[]>;
24
+ count: number;
25
+ };
26
+ protected constraintChecks(ix: Instruction, raw?: Map<string, string[]>): string[];
18
27
  /** Ata<…>: the account's owner (2015) and address (2009) as Anchor checks them, then its mint. */
19
28
  private ataCheck;
20
29
  /** Seeds<…>: the account is the PDA of its seeds (with the stored bump, or the canonical one found here). */