@typesol/cli 0.40.0 → 0.42.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.
- package/CHANGELOG.md +120 -0
- package/README.md +9 -5
- package/dist/ai.d.ts +10 -0
- package/dist/ai.js +43 -0
- package/dist/cli.js +15 -1
- package/dist/compiler/analyze.js +44 -3
- package/dist/compiler/diagnostics.d.ts +2 -0
- package/dist/compiler/emit/base.d.ts +40 -7
- package/dist/compiler/emit/base.js +33 -0
- package/dist/compiler/emit/borsh.d.ts +7 -0
- package/dist/compiler/emit/borsh.js +86 -1
- package/dist/compiler/emit/calls.d.ts +102 -2
- package/dist/compiler/emit/calls.js +671 -50
- package/dist/compiler/emit/cpi-core.d.ts +9 -3
- package/dist/compiler/emit/cpi-core.js +12 -7
- package/dist/compiler/emit/cpi.js +8 -14
- package/dist/compiler/emit/create.d.ts +3 -3
- package/dist/compiler/emit/create.js +33 -25
- package/dist/compiler/emit/expressions.js +51 -2
- package/dist/compiler/emit/function.js +2 -2
- package/dist/compiler/emit/outline.d.ts +24 -0
- package/dist/compiler/emit/outline.js +100 -0
- package/dist/compiler/emit/program.js +7 -2
- package/dist/compiler/emit/shared.d.ts +35 -1
- package/dist/compiler/emit/shared.js +9 -1
- package/dist/compiler/emit/statements.d.ts +31 -0
- package/dist/compiler/emit/statements.js +272 -14
- package/dist/compiler/emit/storage.d.ts +27 -1
- package/dist/compiler/emit/storage.js +124 -11
- package/dist/compiler/emit/token.d.ts +11 -8
- package/dist/compiler/emit/token.js +233 -104
- package/dist/compiler/hints.js +6 -0
- package/dist/compiler/model.d.ts +20 -1
- package/dist/compiler/model.js +5 -0
- package/dist/testing-stake.d.ts +216 -0
- package/dist/testing-stake.js +526 -0
- package/dist/testing.d.ts +1 -0
- package/dist/testing.js +1 -0
- package/dist/tools/mcp.d.ts +11 -0
- package/dist/tools/mcp.js +208 -0
- package/dist/workspace.js +8 -0
- package/docs/ai.md +52 -0
- package/docs/architecture.md +1 -1
- package/docs/audit.md +16 -14
- package/docs/case-study-raydium-cp-swap.md +77 -41
- package/docs/case-study-spl-stake-pool.md +122 -0
- package/docs/errors.md +1 -1
- package/docs/language.md +107 -14
- package/docs/security-model.md +4 -0
- package/docs/stability.md +69 -0
- package/docs/test-your-program.md +47 -0
- package/docs/testing.md +19 -0
- package/lib/typesol.d.ts +241 -40
- package/llms-full.txt +1352 -0
- package/llms.txt +30 -0
- package/package.json +4 -2
- package/runtime/typesol_rt.h +69 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import ts from "typescript";
|
|
2
2
|
import { type AccountParam, type IdlSeed } from "../model.js";
|
|
3
|
-
import { type Value } from "./shared.js";
|
|
3
|
+
import { type Value, type CpiAcct } from "./shared.js";
|
|
4
4
|
import { CallEmitter } from "./calls.js";
|
|
5
5
|
/** Seeds and signer seeds, the byte buffers and Borsh serialization every CPI builds on, remaining-account ranges. */
|
|
6
6
|
export declare abstract class CpiCoreEmitter extends CallEmitter {
|
|
@@ -27,7 +27,11 @@ export declare abstract class CpiCoreEmitter extends CallEmitter {
|
|
|
27
27
|
to: string;
|
|
28
28
|
asPassed?: boolean;
|
|
29
29
|
}): void;
|
|
30
|
-
|
|
30
|
+
/**
|
|
31
|
+
* The seeds a CPI is signed with, or none: then a declared authority must be a Signer. A remaining account (a
|
|
32
|
+
* CpiAcct without `param`) is left to the runtime, which refuses a signer meta for an account that did not sign.
|
|
33
|
+
*/
|
|
34
|
+
protected signerSeeds(node: ts.Expression | undefined, authority: AccountParam | CpiAcct, at: ts.Node): {
|
|
31
35
|
name: string;
|
|
32
36
|
count: number | string;
|
|
33
37
|
};
|
|
@@ -50,11 +54,13 @@ export declare abstract class CpiCoreEmitter extends CallEmitter {
|
|
|
50
54
|
protected keyOf(n: ts.Expression): ts.Expression;
|
|
51
55
|
/**
|
|
52
56
|
* `remainingAccounts()` (or a const bound to it): every remaining account; `rest.slice(a, b?)`: indexes a..b of them
|
|
53
|
-
* (both checked against the count, 5104). C expressions for the range, relative to the first remaining account
|
|
57
|
+
* (both checked against the count, 5104). C expressions for the range, relative to the first remaining account, and
|
|
58
|
+
* `base`, the index of that account among the instruction's (a helper's RemainingAccounts parameter carries it).
|
|
54
59
|
*/
|
|
55
60
|
protected remainingRange(node: ts.Expression): {
|
|
56
61
|
from: string;
|
|
57
62
|
to: string;
|
|
63
|
+
base: string;
|
|
58
64
|
} | undefined;
|
|
59
65
|
/**
|
|
60
66
|
* A byte buffer written front to back. Its C declaration is patched in afterwards so it is
|
|
@@ -178,9 +178,14 @@ export class CpiCoreEmitter extends CallEmitter {
|
|
|
178
178
|
this.line(`for (uint64_t ${i} = ${n} + ${tail.from}; ${i} < ${n} + ${tail.to}; ${i}++) ${m}[${cnt}++] = (SolAccountMeta){¶ms->ka[${i}]->key, ${tail.asPassed ? `params->ka[${i}]->is_writable` : 0}, 0};`);
|
|
179
179
|
this.line(`TS_TRY(ts_cpi(params, ${program}, ${buf}, ${len}, ${m}, ${cnt}, ${seeds.name}, ${seeds.count}));`);
|
|
180
180
|
}
|
|
181
|
+
/**
|
|
182
|
+
* The seeds a CPI is signed with, or none: then a declared authority must be a Signer. A remaining account (a
|
|
183
|
+
* CpiAcct without `param`) is left to the runtime, which refuses a signer meta for an account that did not sign.
|
|
184
|
+
*/
|
|
181
185
|
signerSeeds(node, authority, at) {
|
|
182
186
|
if (!node) {
|
|
183
|
-
|
|
187
|
+
const declared = "c" in authority ? authority.param : authority;
|
|
188
|
+
if (declared && declared.kind.kind !== "signer")
|
|
184
189
|
this.fail(at, "the authority must be a Signer, or pass signerSeeds for a PDA authority");
|
|
185
190
|
return { name: "NULL", count: 0 };
|
|
186
191
|
}
|
|
@@ -236,18 +241,18 @@ export class CpiCoreEmitter extends CallEmitter {
|
|
|
236
241
|
}
|
|
237
242
|
/**
|
|
238
243
|
* `remainingAccounts()` (or a const bound to it): every remaining account; `rest.slice(a, b?)`: indexes a..b of them
|
|
239
|
-
* (both checked against the count, 5104). C expressions for the range, relative to the first remaining account
|
|
244
|
+
* (both checked against the count, 5104). C expressions for the range, relative to the first remaining account, and
|
|
245
|
+
* `base`, the index of that account among the instruction's (a helper's RemainingAccounts parameter carries it).
|
|
240
246
|
*/
|
|
241
247
|
remainingRange(node) {
|
|
242
248
|
const sliced = ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "slice";
|
|
243
249
|
if (!this.isRemaining(node) && !(sliced && this.isRemaining(node.expression.expression)))
|
|
244
250
|
return undefined;
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
const n = this.ix.accounts.length;
|
|
251
|
+
// In a helper: the RemainingAccounts parameter (remainingBase refuses remainingAccounts() there, with a hint).
|
|
252
|
+
const n = this.ix ? this.ix.accounts.length : this.remainingBase(sliced ? node.expression.expression : node);
|
|
248
253
|
const count = `(params->ka_num - ${n})`;
|
|
249
254
|
if (this.isRemaining(node))
|
|
250
|
-
return { from: "0", to: count };
|
|
255
|
+
return { from: "0", to: count, base: String(n) };
|
|
251
256
|
if (!ts.isCallExpression(node))
|
|
252
257
|
return undefined;
|
|
253
258
|
if (node.arguments.length < 1 || node.arguments.length > 2)
|
|
@@ -256,7 +261,7 @@ export class CpiCoreEmitter extends CallEmitter {
|
|
|
256
261
|
const from = this.index(node.arguments[0], `${count} + 1`);
|
|
257
262
|
const to = node.arguments[1] ? this.index(node.arguments[1], `${count} + 1`) : count;
|
|
258
263
|
this.line(`if (${from} > ${to}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: remaining accounts slice out of range");`);
|
|
259
|
-
return { from, to };
|
|
264
|
+
return { from, to, base: String(n) };
|
|
260
265
|
}
|
|
261
266
|
/**
|
|
262
267
|
* A byte buffer written front to back. Its C declaration is patched in afterwards so it is
|
|
@@ -196,22 +196,13 @@ export class CpiEmitter extends MetaplexEmitter {
|
|
|
196
196
|
*/
|
|
197
197
|
invokeInstruction(node) {
|
|
198
198
|
const a = node.arguments;
|
|
199
|
-
if (!this.ix)
|
|
200
|
-
this.fail(node, "invokeInstruction is only available in instructions (it passes remaining accounts)");
|
|
201
199
|
if (a.length !== 4 && a.length !== 5)
|
|
202
200
|
this.fail(node, "invokeInstruction(programId, accounts, data, infos, signerSeeds?) takes 4 or 5 arguments");
|
|
203
201
|
const program = this.expect(this.expr(a[0], PUBKEY), PUBKEY, a[0]);
|
|
204
202
|
const programKey = this.tmp("dprog");
|
|
205
203
|
this.line(`SolPubkey ${programKey} = *(${program.c});`);
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
if (l?.type.kind === "vecArg")
|
|
209
|
-
return { items: `${l.c}.ptr`, count: `((uint64_t)${l.c}.len)`, elem: l.type.elem };
|
|
210
|
-
const r = this.ref(e);
|
|
211
|
-
if (r?.vec && r.type.kind === "vec")
|
|
212
|
-
return { items: `${r.vec.items}`, count: vecCount(r.vec), elem: r.type.elem };
|
|
213
|
-
this.fail(e, `${what}: a Vec or FixedVec (account data, an argument or a local list)`);
|
|
214
|
-
};
|
|
204
|
+
// A Vec, FixedVec or FixedArray (account data, an argument or a local list), the instruction data or a slice of it.
|
|
205
|
+
const list = (e, what) => this.listSpan(e) ?? this.fail(e, `${what}: a Vec or FixedVec (account data, an argument or a local list)`);
|
|
215
206
|
const metas = list(a[1], "the accounts");
|
|
216
207
|
const elem = metas.elem;
|
|
217
208
|
const st = elem.kind === "struct" ? this.model.structs.get(elem.name) : undefined;
|
|
@@ -221,7 +212,9 @@ export class CpiEmitter extends MetaplexEmitter {
|
|
|
221
212
|
const data = list(a[2], "the data");
|
|
222
213
|
if (data.elem.kind !== "int" || data.elem.name !== "u8")
|
|
223
214
|
this.fail(a[2], "the data is a list of u8");
|
|
224
|
-
|
|
215
|
+
// In a helper: its RemainingAccounts parameter (or a slice of it).
|
|
216
|
+
const range = this.remainingRange(a[3]) ??
|
|
217
|
+
this.fail(a[3], "pass the accounts the CPI may use: remainingAccounts() or rest.slice(a, b) (in a helper, its RemainingAccounts parameter)");
|
|
225
218
|
const multi = a.length === 5 ? this.signerSets(a[4]) : undefined;
|
|
226
219
|
const seeds = a.length === 5 && !multi ? this.signingSeeds(a[4]) : undefined;
|
|
227
220
|
const n = this.tmp("dn");
|
|
@@ -236,7 +229,7 @@ export class CpiEmitter extends MetaplexEmitter {
|
|
|
236
229
|
this.line(` ${m}[${i}] = (SolAccountMeta){(SolPubkey *)&e->pubkey, e->isWritable != 0, e->isSigner != 0};`);
|
|
237
230
|
this.line(`}`);
|
|
238
231
|
// Every account offered goes along as an AccountInfo (ts_invoke's scratch holds TS_MAX_ACCOUNTS of them).
|
|
239
|
-
const base =
|
|
232
|
+
const base = range.base;
|
|
240
233
|
this.line(`uint64_t ${k} = 0;`);
|
|
241
234
|
this.line(`TS_INFOS_RESERVE(params, (${range.to}) - (${range.from}));`);
|
|
242
235
|
this.line(`for (uint64_t ${i}b = ${base} + ${range.from}; ${i}b < ${base} + ${range.to}; ${i}b++) ts_info(params->ka[${i}b], ¶ms->infos[${k}++]);`);
|
|
@@ -438,7 +431,8 @@ export class CpiEmitter extends MetaplexEmitter {
|
|
|
438
431
|
const b = this.tmp("evb");
|
|
439
432
|
const w = this.tmp("evw");
|
|
440
433
|
// One pair of heap buffers per emit site, taken on first use: an emit in a loop does not take new heap each pass.
|
|
441
|
-
this.
|
|
434
|
+
this.hoistLazy(t, (n) => `TSS_${s.name} *${n}`);
|
|
435
|
+
this.hoistLazy(b, (n) => `uint8_t *${n}`);
|
|
442
436
|
this.line(`if (${t} == NULL) TS_TRY(ts_alloc(sizeof(TSS_${s.name}), (uint8_t **)&${t}));`);
|
|
443
437
|
this.writeAggregate({ lv: `(*${t})`, type: { kind: "struct", name: s.name }, writable: true }, obj);
|
|
444
438
|
// Borsh never takes more than the fixed layout (a String/Vec is 4 + used bytes, an Option 1 + payload).
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import ts from "typescript";
|
|
2
2
|
import { type AccountParam } from "../model.js";
|
|
3
|
-
import { type Value } from "./shared.js";
|
|
3
|
+
import { type Value, type CpiProgram } from "./shared.js";
|
|
4
4
|
import { CpiCoreEmitter } from "./cpi-core.js";
|
|
5
5
|
/** Creating accounts: `create` / `createIfNeeded` of program accounts, mints, token accounts and ATAs (with Token-2022 mint extensions), System transfers and createAccount. */
|
|
6
6
|
export declare abstract class CreateEmitter extends CpiCoreEmitter {
|
|
@@ -35,7 +35,7 @@ export declare abstract class CreateEmitter extends CpiCoreEmitter {
|
|
|
35
35
|
protected createAta(node: ts.CallExpression, target: AccountParam, topLevel: boolean): Value | undefined;
|
|
36
36
|
protected systemTransfer(node: ts.CallExpression): undefined;
|
|
37
37
|
/** systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?) */
|
|
38
|
-
protected createAccount(node: ts.CallExpression, system:
|
|
38
|
+
protected createAccount(node: ts.CallExpression, system: CpiProgram): undefined;
|
|
39
39
|
/**
|
|
40
40
|
* systemProgram.createPda(payer, account, space, owner, seeds): Anchor's `init` with `seeds`, `space` and `owner = …`
|
|
41
41
|
* on an `UncheckedAccount` — the PDA of this program for `seeds` (2006 otherwise), created owned by `owner`, or over
|
|
@@ -44,5 +44,5 @@ export declare abstract class CreateEmitter extends CpiCoreEmitter {
|
|
|
44
44
|
*/
|
|
45
45
|
protected createPda(node: ts.CallExpression): Value;
|
|
46
46
|
/** systemProgram.allocate(account, space, signerSeeds?) / systemProgram.assign(account, owner, signerSeeds?). */
|
|
47
|
-
protected allocateOrAssign(node: ts.CallExpression, system:
|
|
47
|
+
protected allocateOrAssign(node: ts.CallExpression, system: CpiProgram, method: "allocate" | "assign"): undefined;
|
|
48
48
|
}
|
|
@@ -519,21 +519,23 @@ export class CreateEmitter extends CpiCoreEmitter {
|
|
|
519
519
|
if (a.length !== 3 && a.length !== 4)
|
|
520
520
|
this.fail(node, "transfer(from, to, lamports, signerSeeds?)");
|
|
521
521
|
const [fromN, toN, amtN] = a;
|
|
522
|
-
|
|
523
|
-
|
|
522
|
+
// Declared accounts are checked here; remaining accounts by the runtime (writable, and the source signed).
|
|
523
|
+
const from = this.cpiAccount(fromN, "transfer's source");
|
|
524
|
+
const fp = from.param;
|
|
525
|
+
if (fp && a.length === 3 && (fp.kind.kind !== "signer" || !fp.kind.mut))
|
|
524
526
|
this.fail(fromN, "the source must be a Mut<Signer>, or a Mut<AccountInfo> PDA of this program with signerSeeds");
|
|
525
|
-
if (a.length === 4 && !isWritable(
|
|
527
|
+
if (fp && a.length === 4 && !isWritable(fp.kind))
|
|
526
528
|
this.fail(fromN, "the source must be writable (Mut<...>)");
|
|
527
|
-
const to = this.
|
|
528
|
-
if (!isWritable(to.kind))
|
|
529
|
+
const to = this.cpiAccount(toN, "transfer's destination");
|
|
530
|
+
if (to.param && !isWritable(to.param.kind))
|
|
529
531
|
this.fail(toN, "the destination must be writable (Mut<...>)");
|
|
530
532
|
const amt = this.expect(this.expr(amtN, U64), U64, amtN);
|
|
531
533
|
if (a.length === 3)
|
|
532
|
-
this.line(`TS_TRY(ts_system_transfer(params,
|
|
534
|
+
this.line(`TS_TRY(ts_system_transfer(params, ${from.c}, ${to.c}, ${amt.c}));`);
|
|
533
535
|
else {
|
|
534
536
|
// A system-owned PDA of this program (a SOL vault) pays.
|
|
535
537
|
const s = this.signingSeeds(a[3]);
|
|
536
|
-
this.line(`TS_TRY(ts_system_transfer_signed(params,
|
|
538
|
+
this.line(`TS_TRY(ts_system_transfer_signed(params, ${from.c}, ${to.c}, ${amt.c}, ${s.name}, ${s.count}));`);
|
|
537
539
|
}
|
|
538
540
|
return undefined;
|
|
539
541
|
}
|
|
@@ -542,13 +544,15 @@ export class CreateEmitter extends CpiCoreEmitter {
|
|
|
542
544
|
const a = node.arguments;
|
|
543
545
|
if (a.length !== 5 && a.length !== 6)
|
|
544
546
|
this.fail(node, "createAccount(payer, account, lamports, space, owner, signerSeeds?)");
|
|
545
|
-
const payer = this.
|
|
546
|
-
|
|
547
|
+
const payer = this.cpiAccount(a[0], "the payer");
|
|
548
|
+
const pp = payer.param;
|
|
549
|
+
if (pp && (pp.kind.kind !== "signer" || !pp.kind.mut))
|
|
547
550
|
this.fail(a[0], "the payer must be a Mut<Signer>");
|
|
548
|
-
const acct = this.
|
|
549
|
-
|
|
551
|
+
const acct = this.cpiAccount(a[1], "the new account");
|
|
552
|
+
const ap = acct.param;
|
|
553
|
+
if (ap && !isWritable(ap.kind))
|
|
550
554
|
this.fail(a[1], "the new account must be writable (Mut<Signer> or Mut<AccountInfo>)");
|
|
551
|
-
if (
|
|
555
|
+
if (ap && ap.kind.kind !== "signer" && a.length !== 6)
|
|
552
556
|
this.fail(a[1], "the new account must sign: a Mut<Signer> keypair, or pass signerSeeds for a PDA");
|
|
553
557
|
const { buf, len, put, finish } = this.byteBuffer("sys", 52, "TS_ERR_INSTRUCTION_DATA", "system instruction");
|
|
554
558
|
const tag = this.tmp("tag");
|
|
@@ -559,9 +563,9 @@ export class CreateEmitter extends CpiCoreEmitter {
|
|
|
559
563
|
this.serialize(this.expect(this.expr(a[4], PUBKEY), PUBKEY, a[4]), a[4], put);
|
|
560
564
|
finish(node);
|
|
561
565
|
const seeds = a.length === 6 ? this.signingSeeds(a[5]) : { name: "NULL", count: 0 };
|
|
562
|
-
this.cpi(
|
|
563
|
-
[
|
|
564
|
-
[
|
|
566
|
+
this.cpi(system.c, [
|
|
567
|
+
[payer.c, true, true],
|
|
568
|
+
[acct.c, true, true],
|
|
565
569
|
], buf, len, seeds);
|
|
566
570
|
return undefined;
|
|
567
571
|
}
|
|
@@ -575,21 +579,24 @@ export class CreateEmitter extends CpiCoreEmitter {
|
|
|
575
579
|
const a = node.arguments;
|
|
576
580
|
if (a.length !== 5)
|
|
577
581
|
this.fail(node, "createPda(payer, account, space, owner, seeds)");
|
|
578
|
-
const payer = this.
|
|
579
|
-
|
|
582
|
+
const payer = this.cpiAccount(a[0], "the payer");
|
|
583
|
+
const pp = payer.param;
|
|
584
|
+
if (pp && (pp.kind.kind !== "signer" || !pp.kind.mut))
|
|
580
585
|
this.fail(a[0], "the payer must be a Mut<Signer>");
|
|
581
|
-
const acct = this.
|
|
582
|
-
|
|
586
|
+
const acct = this.cpiAccount(a[1], "the new account");
|
|
587
|
+
const ap = acct.param;
|
|
588
|
+
if (ap && (ap.kind.kind !== "info" || !isWritable(ap.kind)))
|
|
583
589
|
this.fail(a[1], "the new account must be a Mut<AccountInfo>");
|
|
584
590
|
const space = this.tmp("space");
|
|
585
591
|
this.line(`uint64_t ${space} = ${this.expect(this.expr(a[2], U64), U64, a[2]).c};`);
|
|
586
592
|
const owner = this.tmp("owner");
|
|
587
593
|
this.line(`SolPubkey ${owner} = *(${this.expect(this.expr(a[3], PUBKEY), PUBKEY, a[3]).c});`);
|
|
588
594
|
const seeds = this.seeds(a[4], 1);
|
|
589
|
-
|
|
595
|
+
if (ap)
|
|
596
|
+
this.recordPda(ap, seeds.idl);
|
|
590
597
|
const b = this.tmp("bump");
|
|
591
598
|
this.line(`uint8_t ${b};`);
|
|
592
|
-
this.line(`TS_TRY(ts_create_pda_owned(params,
|
|
599
|
+
this.line(`TS_TRY(ts_create_pda_owned(params, ${payer.c}, ${acct.c}, ${seeds.name}, ${seeds.count}, &${owner}, ${space}, &${b}));`);
|
|
593
600
|
return { c: b, type: U8 };
|
|
594
601
|
}
|
|
595
602
|
/** systemProgram.allocate(account, space, signerSeeds?) / systemProgram.assign(account, owner, signerSeeds?). */
|
|
@@ -597,10 +604,11 @@ export class CreateEmitter extends CpiCoreEmitter {
|
|
|
597
604
|
const a = node.arguments;
|
|
598
605
|
if (a.length !== 2 && a.length !== 3)
|
|
599
606
|
this.fail(node, `${method}(account, ${method === "allocate" ? "space" : "owner"}, signerSeeds?)`);
|
|
600
|
-
const acct = this.
|
|
601
|
-
|
|
607
|
+
const acct = this.cpiAccount(a[0], "the account");
|
|
608
|
+
const ap = acct.param;
|
|
609
|
+
if (ap && !isWritable(ap.kind))
|
|
602
610
|
this.fail(a[0], `the account must be writable (Mut<Signer> or Mut<AccountInfo>)`);
|
|
603
|
-
if (
|
|
611
|
+
if (ap && ap.kind.kind !== "signer" && a.length !== 3)
|
|
604
612
|
this.fail(a[0], "the account must sign: a Mut<Signer> keypair, or pass signerSeeds for a PDA");
|
|
605
613
|
const { buf, len, put, finish } = this.byteBuffer("sys", 36, "TS_ERR_INSTRUCTION_DATA", "system instruction");
|
|
606
614
|
const tag = this.tmp("tag");
|
|
@@ -612,7 +620,7 @@ export class CreateEmitter extends CpiCoreEmitter {
|
|
|
612
620
|
this.serialize(this.expect(this.expr(a[1], PUBKEY), PUBKEY, a[1]), a[1], put);
|
|
613
621
|
finish(node);
|
|
614
622
|
const seeds = a.length === 3 ? this.signingSeeds(a[2]) : { name: "NULL", count: 0 };
|
|
615
|
-
this.cpi(
|
|
623
|
+
this.cpi(system.c, [[acct.c, true, true]], buf, len, seeds);
|
|
616
624
|
return undefined;
|
|
617
625
|
}
|
|
618
626
|
}
|
|
@@ -331,7 +331,7 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
331
331
|
if (ts.isArrayLiteralExpression(node))
|
|
332
332
|
this.fail(node, "arrays are only allowed inline as seeds/CPI lists; declare local arrays with fixedArray<T, N>(fill)");
|
|
333
333
|
if (ts.isObjectLiteralExpression(node))
|
|
334
|
-
this.fail(node, "object
|
|
334
|
+
this.fail(node, "an object literal needs a struct type here: give it one (const p: Point = { … }), or pass it where one is known (emit<T>(…), a helper's struct parameter, a struct field, storeBorsh<T>(…))");
|
|
335
335
|
if (ts.isCallExpression(node)) {
|
|
336
336
|
const h = this.handle(node);
|
|
337
337
|
if (h)
|
|
@@ -350,6 +350,12 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
350
350
|
}
|
|
351
351
|
property(node) {
|
|
352
352
|
const field = node.name.text;
|
|
353
|
+
// A BigVec's room: the elements the account holds past the struct.
|
|
354
|
+
if (field === "capacity" && this.peekKind(node.expression) === "vec") {
|
|
355
|
+
const r = this.ref(node.expression);
|
|
356
|
+
if (r?.vec?.big !== undefined && !r.vec.slice)
|
|
357
|
+
return { c: r.vec.big, type: U64 };
|
|
358
|
+
}
|
|
353
359
|
if (field === "length") {
|
|
354
360
|
if (this.isRemaining(node.expression))
|
|
355
361
|
return { c: `((uint64_t)(params->ka_num - ${this.remainingBase(node.expression)}))`, type: U64 };
|
|
@@ -378,6 +384,9 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
378
384
|
if (l?.type.kind === "vecArg")
|
|
379
385
|
return { c: `((uint64_t)${l.c}.len)`, type: U64 };
|
|
380
386
|
}
|
|
387
|
+
// A slice of a Vec argument or the instruction data.
|
|
388
|
+
if (this.isVecArgView(node.expression))
|
|
389
|
+
return { c: `((uint64_t)${this.vecArgView(node.expression).c}.len)`, type: U64 };
|
|
381
390
|
let what = "this value";
|
|
382
391
|
try {
|
|
383
392
|
what = this.checker.typeToString(this.checker.getTypeAtLocation(node.expression));
|
|
@@ -389,6 +398,22 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
389
398
|
this.fail(node, "use byteLength(s) for strings; .length is available on arrays, Vecs and remainingAccounts()");
|
|
390
399
|
this.fail(node, `.length is available on arrays, Vecs, map / filter chains and remainingAccounts(), not on ${what}`);
|
|
391
400
|
}
|
|
401
|
+
if (this.isEpochRewards(node.expression)) {
|
|
402
|
+
const er = this.expr(node.expression).c;
|
|
403
|
+
const fields = {
|
|
404
|
+
distributionStartingBlockHeight: { c: `(${er}.distribution_starting_block_height)`, type: U64 },
|
|
405
|
+
numPartitions: { c: `(${er}.num_partitions)`, type: U64 },
|
|
406
|
+
parentBlockhash: { c: `(&${er}.parent_blockhash)`, type: HASH },
|
|
407
|
+
totalPoints: { c: `(${er}.total_points)`, type: { kind: "int", name: "u128" } },
|
|
408
|
+
totalRewards: { c: `(${er}.total_rewards)`, type: U64 },
|
|
409
|
+
distributedRewards: { c: `(${er}.distributed_rewards)`, type: U64 },
|
|
410
|
+
active: { c: `(${er}.active != 0)`, type: BOOL },
|
|
411
|
+
};
|
|
412
|
+
const v = Object.hasOwn(fields, field) ? fields[field] : undefined;
|
|
413
|
+
if (!v)
|
|
414
|
+
this.fail(node.name, `EpochRewards has ${Object.keys(fields).join(", ")}, not ${field}`);
|
|
415
|
+
return v;
|
|
416
|
+
}
|
|
392
417
|
if (this.isTxIx(node.expression)) {
|
|
393
418
|
const ix = this.expr(node.expression);
|
|
394
419
|
if (field === "programId")
|
|
@@ -400,6 +425,14 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
400
425
|
this.fail(node.name, `a TransactionInstruction has programId, accountsLength and dataLength, not ${field}`);
|
|
401
426
|
}
|
|
402
427
|
const h = this.handle(node.expression);
|
|
428
|
+
// `sysvarAt<StakeHistorySysvar>(acct)`: its count and newest epoch, as on a StakeHistorySysvar parameter.
|
|
429
|
+
const sysvar = h && ts.isIdentifier(node.expression) ? this.lookup(node.expression.text)?.type : undefined;
|
|
430
|
+
if (h && sysvar?.kind === "account" && sysvar.program?.kind === "stakeHistory") {
|
|
431
|
+
if (field === "count")
|
|
432
|
+
return { c: `ts_read_le(${h}->data, 8)`, type: U64 };
|
|
433
|
+
if (field === "latestEpoch")
|
|
434
|
+
return { c: `(${h}->data_len >= 16 && ts_read_le(${h}->data, 8) ? ts_read_le(${h}->data + 8, 8) : 0)`, type: U64 };
|
|
435
|
+
}
|
|
403
436
|
if (h) {
|
|
404
437
|
switch (field) {
|
|
405
438
|
case "key":
|
|
@@ -669,6 +702,15 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
669
702
|
return v.c;
|
|
670
703
|
if (converted)
|
|
671
704
|
converted.yes = true;
|
|
705
|
+
if (v.type.kind === "option" && v.type.inner.kind === "pubkey") {
|
|
706
|
+
// `${key}` of an Option<Pubkey> (or Hash), narrowed or not: its base58, or "null" like JS.
|
|
707
|
+
const o = this.tmp("o");
|
|
708
|
+
const t = this.tmp("txt");
|
|
709
|
+
this.line(`${optC(v.type.inner)} ${o} = ${v.c};`);
|
|
710
|
+
this.line(`TS_Str ${t} = ts_str((const uint8_t *)"null", 4);`);
|
|
711
|
+
this.line(`if (${o}.some) TS_TRY(ts_base58_32((const uint8_t *)&${o}.v, &${t}));`);
|
|
712
|
+
return t;
|
|
713
|
+
}
|
|
672
714
|
if (v.type.kind === "option" && (v.type.inner.kind === "int" || v.type.inner.kind === "bool")) {
|
|
673
715
|
// `${opt}`: the value, or "null" like JS.
|
|
674
716
|
const inner = v.type.inner;
|
|
@@ -716,6 +758,11 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
716
758
|
}
|
|
717
759
|
/** `c ? a : b` on values: only the chosen branch runs (its checks and side effects included). */
|
|
718
760
|
conditional(node, hint) {
|
|
761
|
+
// One of two accounts: `ephemeral ? rest.get(5n) : reserve`.
|
|
762
|
+
if (this.looksLikeAccountHandle(node))
|
|
763
|
+
return this.accountChoice(node);
|
|
764
|
+
if (this.looksLikeAccountHandle(node.whenTrue) || this.looksLikeAccountHandle(node.whenFalse))
|
|
765
|
+
this.fail(node, "choose between accounts of one kind: remaining accounts (rest.get(i), a local or RemainingAccount parameter bound to one) or AccountInfo parameters");
|
|
719
766
|
if (this.looksLikeStructPlace(node.whenTrue))
|
|
720
767
|
this.fail(node, "bind a choice between structs to a const: const o = c ? a.get(i) : b.get(i)");
|
|
721
768
|
const cond = this.expect(this.expr(node.condition, BOOL), BOOL, node.condition);
|
|
@@ -750,7 +797,9 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
750
797
|
});
|
|
751
798
|
this.line(`}`);
|
|
752
799
|
const vt = type;
|
|
753
|
-
if (vt.kind === "account"
|
|
800
|
+
if (vt.kind === "account")
|
|
801
|
+
this.fail(node, "choose between accounts of one kind: remaining accounts (rest.get(i), a local or RemainingAccount parameter bound to one) or AccountInfo parameters");
|
|
802
|
+
if (vt.kind === "remaining" || vt.kind === "structRef" || vt.kind === "vecArg")
|
|
754
803
|
this.fail(node, "choose between plain values (integers, booleans, Pubkeys, strings, options)");
|
|
755
804
|
this.lines[declAt] = this.lines[declAt].replace(`/* ${t} */`, `${vt.kind === "pubkey" ? "SolPubkey" : valueC(vt)} ${t};`);
|
|
756
805
|
return vt.kind === "pubkey" ? { c: `(&${t})`, type: vt } : { c: t, type: vt };
|
|
@@ -21,7 +21,7 @@ export class FunctionEmitter extends StatementEmitter {
|
|
|
21
21
|
this.reporter.guard(() => this.statement(stmt));
|
|
22
22
|
// A helper with a result must return one; falling off the end would leave it unset.
|
|
23
23
|
const end = h.returns ? ` TS_FAIL(TS_ERR_NO_RETURN, "TypeSOL: ${h.display} ended without returning a value");` : ` return SUCCESS;`;
|
|
24
|
-
return [`${helperSignature(h)} {`, ...this.hoisted, ...this.lines, end, `}`].join("\n");
|
|
24
|
+
return [...this.outlinedLoops, `${helperSignature(h)} {`, ...this.hoisted, ...this.lines, end, `}`].join("\n");
|
|
25
25
|
}
|
|
26
26
|
emitInstruction() {
|
|
27
27
|
const ix = this.ix;
|
|
@@ -483,7 +483,7 @@ export class FunctionEmitter extends StatementEmitter {
|
|
|
483
483
|
// The Clock cache is declared first: a constraint (in the head) may read the Clock before the body does.
|
|
484
484
|
const clock = this.hoisted.filter((l) => l.includes("ts_clk_ok"));
|
|
485
485
|
const hoisted = this.hoisted.filter((l) => !clock.includes(l));
|
|
486
|
-
return [head[0], ...clock, ...head.slice(1), ...hoisted, ...this.lines, ...end, `}`].join("\n");
|
|
486
|
+
return [...this.outlinedLoops, head[0], ...clock, ...head.slice(1), ...hoisted, ...this.lines, ...end, `}`].join("\n");
|
|
487
487
|
}
|
|
488
488
|
/**
|
|
489
489
|
* How many statements at the start of `body` create this instruction's Init / InitIfNeeded accounts
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading generated C, for moving a loop into a function of its own (StatementEmitter.outlinedLoop): which names a
|
|
3
|
+
* piece of C uses, which it declares itself, and which are the runtime's, so that every other name it uses is one
|
|
4
|
+
* of the caller's variables the new function has to be given.
|
|
5
|
+
*/
|
|
6
|
+
/** Identifiers, numbers and punctuation of `c`, without comments, string and character literals. */
|
|
7
|
+
export declare function cTokens(c: string): string[];
|
|
8
|
+
/** The names the C uses as variables or functions (not the fields after `.` or `->`). */
|
|
9
|
+
export declare function usedNames(toks: string[]): Set<string>;
|
|
10
|
+
/**
|
|
11
|
+
* The variables and labels the C declares: `T x = …;`, `T *x, *y = …;`, `T x[n];`, a `for (T i = …;` and `label:`.
|
|
12
|
+
* A declaration starts a statement, so a name it misses is only taken for one of the caller's (and the loop then
|
|
13
|
+
* stays where it is).
|
|
14
|
+
*/
|
|
15
|
+
export declare function declaredNames(toks: string[]): Set<string>;
|
|
16
|
+
/**
|
|
17
|
+
* Names that are the runtime's or the SDK's, never one of a function's variables: runtime functions and macros,
|
|
18
|
+
* generated types and constants, helpers (`fn_…`), syscalls, other loops' functions. The emitter's own temporaries
|
|
19
|
+
* with a `ts_` prefix are labels (`ts_continue_12`, `ts_next_3`, `ts_ret_7`), which a loop declares itself; runtime
|
|
20
|
+
* functions whose names end in a number (`ts_base58_32`) are global.
|
|
21
|
+
*/
|
|
22
|
+
export declare function isGlobalName(n: string): boolean;
|
|
23
|
+
/** A C parameter list (`TsParams *params, uint64_t p_rest`) as name → declaration. */
|
|
24
|
+
export declare function parameterDecls(signature: string): Map<string, string>;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading generated C, for moving a loop into a function of its own (StatementEmitter.outlinedLoop): which names a
|
|
3
|
+
* piece of C uses, which it declares itself, and which are the runtime's, so that every other name it uses is one
|
|
4
|
+
* of the caller's variables the new function has to be given.
|
|
5
|
+
*/
|
|
6
|
+
/** Identifiers, numbers and punctuation of `c`, without comments, string and character literals. */
|
|
7
|
+
export function cTokens(c) {
|
|
8
|
+
const bare = c.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*|"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'/g, " 0 ");
|
|
9
|
+
return bare.match(/[A-Za-z_]\w*|\d\w*|->|\S/g) ?? [];
|
|
10
|
+
}
|
|
11
|
+
const isIdent = (t) => t !== undefined && /^[A-Za-z_]/.test(t);
|
|
12
|
+
/** C keywords (and the type words of declarations, which never name a variable). */
|
|
13
|
+
const KEYWORDS = new Set(("auto break case char const continue default do double else enum extern float for goto if inline int long register restrict return short " +
|
|
14
|
+
"signed sizeof static struct switch typedef union unsigned void volatile while _Bool _Static_assert __attribute__ __asm__ __typeof__").split(" "));
|
|
15
|
+
/** The names the C uses as variables or functions (not the fields after `.` or `->`). */
|
|
16
|
+
export function usedNames(toks) {
|
|
17
|
+
const out = new Set();
|
|
18
|
+
toks.forEach((t, i) => {
|
|
19
|
+
if (isIdent(t) && !KEYWORDS.has(t) && toks[i - 1] !== "." && toks[i - 1] !== "->")
|
|
20
|
+
out.add(t);
|
|
21
|
+
});
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The variables and labels the C declares: `T x = …;`, `T *x, *y = …;`, `T x[n];`, a `for (T i = …;` and `label:`.
|
|
26
|
+
* A declaration starts a statement, so a name it misses is only taken for one of the caller's (and the loop then
|
|
27
|
+
* stays where it is).
|
|
28
|
+
*/
|
|
29
|
+
export function declaredNames(toks) {
|
|
30
|
+
const out = new Set();
|
|
31
|
+
for (let i = 0; i < toks.length; i++) {
|
|
32
|
+
const prev = toks[i - 1];
|
|
33
|
+
const start = i === 0 || prev === ";" || prev === "{" || prev === "}" || (prev === "(" && toks[i - 2] === "for");
|
|
34
|
+
if (!start || !isIdent(toks[i]))
|
|
35
|
+
continue;
|
|
36
|
+
if (toks[i + 1] === ":" && !KEYWORDS.has(toks[i])) {
|
|
37
|
+
out.add(toks[i]);
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
let j = i;
|
|
41
|
+
while (toks[j] === "const" || toks[j] === "static" || toks[j] === "struct" || toks[j] === "unsigned")
|
|
42
|
+
j++;
|
|
43
|
+
if (!isIdent(toks[j]) || KEYWORDS.has(toks[j]))
|
|
44
|
+
continue;
|
|
45
|
+
j++; // the type
|
|
46
|
+
for (;;) {
|
|
47
|
+
while (toks[j] === "*" || toks[j] === "const")
|
|
48
|
+
j++;
|
|
49
|
+
const name = toks[j];
|
|
50
|
+
const after = toks[j + 1];
|
|
51
|
+
if (!isIdent(name) || KEYWORDS.has(name) || !["=", ";", "[", ",", ")"].includes(after))
|
|
52
|
+
break;
|
|
53
|
+
out.add(name);
|
|
54
|
+
// Past this declarator's initializer, to the next one (a comma at depth 0) or the statement's end.
|
|
55
|
+
j++;
|
|
56
|
+
let depth = 0;
|
|
57
|
+
while (j < toks.length) {
|
|
58
|
+
const t = toks[j];
|
|
59
|
+
if (t === "(" || t === "[" || t === "{")
|
|
60
|
+
depth++;
|
|
61
|
+
else if (t === ")" || t === "]" || t === "}") {
|
|
62
|
+
if (depth === 0)
|
|
63
|
+
break;
|
|
64
|
+
depth--;
|
|
65
|
+
}
|
|
66
|
+
else if (depth === 0 && (t === "," || t === ";"))
|
|
67
|
+
break;
|
|
68
|
+
j++;
|
|
69
|
+
}
|
|
70
|
+
if (toks[j] !== ",")
|
|
71
|
+
break;
|
|
72
|
+
j++;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Names that are the runtime's or the SDK's, never one of a function's variables: runtime functions and macros,
|
|
79
|
+
* generated types and constants, helpers (`fn_…`), syscalls, other loops' functions. The emitter's own temporaries
|
|
80
|
+
* with a `ts_` prefix are labels (`ts_continue_12`, `ts_next_3`, `ts_ret_7`), which a loop declares itself; runtime
|
|
81
|
+
* functions whose names end in a number (`ts_base58_32`) are global.
|
|
82
|
+
*/
|
|
83
|
+
export function isGlobalName(n) {
|
|
84
|
+
return (/^(?:ts_(?!(?:continue|next|ret)_\d+$)|TS_|TSS_|TSE_|TSV_|TSK_|TSF_|TSW_|Ts[A-Z]|fn_|sol_|Sol[A-Z]|SOL_|__builtin_)/.test(n) ||
|
|
85
|
+
/^(?:SUCCESS|NULL|true|false|abort|bool|u?int(?:8|16|32|64)_t|__u?int128_t|size_t)$/.test(n) ||
|
|
86
|
+
/^(?:fn|ix)_\w+__loop\d+$/.test(n) // a loop inside the loop, moved out first
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
/** A C parameter list (`TsParams *params, uint64_t p_rest`) as name → declaration. */
|
|
90
|
+
export function parameterDecls(signature) {
|
|
91
|
+
const inner = signature.slice(signature.indexOf("(") + 1, signature.lastIndexOf(")"));
|
|
92
|
+
const out = new Map();
|
|
93
|
+
for (const p of inner.split(",")) {
|
|
94
|
+
const decl = p.trim();
|
|
95
|
+
const name = decl.match(/(\w+)\s*$/)?.[1];
|
|
96
|
+
if (name)
|
|
97
|
+
out.set(name, decl);
|
|
98
|
+
}
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { accountLimit, cBytes, scalarStorageC, optC, storageDecl, helperSignature, fieldC, fixedVecC, laterVecC } from "./shared.js";
|
|
2
2
|
import { FunctionEmitter } from "./function.js";
|
|
3
|
-
import { emitBorshCodecs } from "./borsh.js";
|
|
3
|
+
import { emitBorshCodecs, emitNativeBorshCodecs } from "./borsh.js";
|
|
4
4
|
/**
|
|
5
5
|
* The whole C translation unit: type declarations (structs, options, enums, events), every helper and instruction
|
|
6
6
|
* (lowered by FunctionEmitter), and the entry point that dispatches on the instruction discriminator.
|
|
@@ -56,6 +56,11 @@ export function emitProgram(analysis, opts = {}) {
|
|
|
56
56
|
else if (panicFlag.value)
|
|
57
57
|
out.push(`#define TS_PANIC_ON_OVERFLOW 1`);
|
|
58
58
|
}
|
|
59
|
+
// `const NATIVE_ACCOUNT_WRITES = true`: loadRawMut / storeBorsh / BigVec writes leave writability and aliasing to the
|
|
60
|
+
// runtime, as a native program does (read by the emitter; nothing to define in C).
|
|
61
|
+
const nativeWrites = model.constants.get("NATIVE_ACCOUNT_WRITES");
|
|
62
|
+
if (nativeWrites && typeof nativeWrites.value !== "boolean")
|
|
63
|
+
reporter.error(analysis.sourceFile, "NATIVE_ACCOUNT_WRITES must be true or false");
|
|
59
64
|
// An error with code 0 must not return 0 (success): see ts_fail.
|
|
60
65
|
if ([...model.errorEnums.values()].some((m) => [...m.values()].some((e) => e.code === 0)))
|
|
61
66
|
out.push(`#define TS_CUSTOM_ZERO 1`);
|
|
@@ -164,7 +169,7 @@ export function emitProgram(analysis, opts = {}) {
|
|
|
164
169
|
for (const k of model.constants.values())
|
|
165
170
|
if (typeof k.value === "object")
|
|
166
171
|
out.push(`static const SolPubkey TSK_${k.name} = {${cBytes(k.value.pubkey)}};`);
|
|
167
|
-
out.push(...emitBorshCodecs(model));
|
|
172
|
+
out.push(...emitBorshCodecs(model), ...emitNativeBorshCodecs(model));
|
|
168
173
|
const helpers = [...model.helpers.values()];
|
|
169
174
|
for (const h of helpers)
|
|
170
175
|
out.push(helperSignature(h) + ";");
|