@typesol/cli 0.48.0 → 0.50.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 +556 -1
- package/NOTICE +17 -1
- package/README.md +122 -43
- package/SECURITY.md +6 -0
- package/dist/compiler/analyze.d.ts +2 -0
- package/dist/compiler/analyze.js +7 -1
- package/dist/compiler/emit/base.d.ts +7 -4
- package/dist/compiler/emit/base.js +17 -5
- package/dist/compiler/emit/borsh.js +8 -8
- package/dist/compiler/emit/calls.d.ts +6 -0
- package/dist/compiler/emit/calls.js +110 -11
- package/dist/compiler/emit/cpi-core.js +3 -3
- package/dist/compiler/emit/cpi.js +2 -2
- package/dist/compiler/emit/expressions.d.ts +1 -0
- package/dist/compiler/emit/expressions.js +15 -1
- package/dist/compiler/emit/function.js +12 -8
- package/dist/compiler/emit/program.js +10 -4
- package/dist/compiler/emit/rbtree.js +1 -1
- package/dist/compiler/emit/shared.d.ts +12 -2
- package/dist/compiler/emit/shared.js +26 -6
- package/dist/compiler/emit/statements.d.ts +8 -1
- package/dist/compiler/emit/statements.js +53 -5
- package/dist/compiler/emit/storage.js +20 -13
- package/dist/compiler/emit/views.js +1 -1
- package/dist/compiler/hints.js +3 -0
- package/dist/compiler/index.d.ts +15 -1
- package/dist/compiler/index.js +50 -9
- package/dist/keys.d.ts +12 -1
- package/dist/keys.js +57 -7
- package/dist/workspace.d.ts +8 -0
- package/dist/workspace.js +90 -15
- package/docker/deps/0.49.0.lock.json +1206 -0
- package/docker/deps/0.50.0.lock.json +1206 -0
- package/docs/architecture.md +3 -3
- package/docs/audit.md +33 -16
- package/docs/case-study-escrow.md +7 -5
- package/docs/case-study-jito-mev.md +14 -14
- package/docs/case-study-marginfi.md +142 -129
- package/docs/case-study-multisig.md +18 -5
- package/docs/case-study-raydium-amm.md +2 -1
- package/docs/case-study-raydium-clmm.md +44 -28
- package/docs/case-study-raydium-cp-swap.md +18 -18
- package/docs/case-study-spl-stake-pool.md +4 -3
- package/docs/cli.md +4 -3
- package/docs/language-accounts.md +21 -16
- package/docs/language-basics.md +4 -1
- package/docs/language-builtins.md +6 -2
- package/docs/language-cpi.md +34 -0
- package/docs/language-errors-events.md +1 -1
- package/docs/language-native.md +73 -7
- package/docs/language-statements.md +5 -3
- package/docs/language-types.md +13 -3
- package/docs/language.md +2 -2
- package/docs/mainnet.md +1 -1
- package/docs/runtime.md +25 -1
- package/docs/security-model.md +12 -4
- package/docs/stability.md +10 -4
- package/docs/testing.md +22 -6
- package/docs/troubleshooting.md +1 -1
- package/lib/typesol.d.ts +43 -3
- package/llms-full.txt +190 -51
- package/llms.txt +2 -1
- package/package.json +3 -3
- package/releases/0.48.0.json +847 -0
- package/releases/0.49.0.json +857 -0
- package/runtime/typesol_builtins.c +47 -2
- package/runtime/typesol_rt.h +131 -4
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import ts from "typescript";
|
|
2
2
|
import { calleeName, discriminator, resolveScalarType, resolveValueType, snakeCase, structNameOf, typesolName } from "../analyze.js";
|
|
3
|
-
import { borshIdentical, borshNativeStructUnsupported } from "./borsh.js";
|
|
3
|
+
import { borshIdentical, borshMinSize, borshNativeStructUnsupported } from "./borsh.js";
|
|
4
4
|
import { ANCHOR_ERRORS } from "../anchor-errors.js";
|
|
5
5
|
import { decodeAddress } from "../../keys.js";
|
|
6
6
|
import { INT_INFO, INT_NAMES, isScalar, isWritable, sameType, scalarSize, typeName, } from "../model.js";
|
|
@@ -42,6 +42,19 @@ const LIST_METHODS = new Set(["forEach", "some", "every", "find", "findIndex", "
|
|
|
42
42
|
/** The byte builders of a FixedVec<u8, N> (byteListMethod). */
|
|
43
43
|
const BYTE_METHODS = new Set(["pushLE", "pushKey", "pushBorsh", "setLE", "truncate"]);
|
|
44
44
|
export class CallEmitter extends ExpressionEmitter {
|
|
45
|
+
/**
|
|
46
|
+
* Closing an account of this program (`close`, `CloseTo<…>`): TS_CLOSE with the smallest size the account was
|
|
47
|
+
* checked to hold when it loaded (its discriminator and the struct's empty size, or a @layout borsh struct's smallest
|
|
48
|
+
* Borsh form). From TS_ZERO_RUN_MIN bytes on its data is zeroed by the memset syscall; below, by stores as before.
|
|
49
|
+
*/
|
|
50
|
+
closeCall(a, dest) {
|
|
51
|
+
const k = a.kind;
|
|
52
|
+
if (k.kind !== "account" || !k.struct)
|
|
53
|
+
return `ts_close(a_${a.name}, ${dest})`;
|
|
54
|
+
const s = k.struct;
|
|
55
|
+
const min = s.layout === "borsh" ? String(s.accountDiscriminator.length + borshMinSize(s, this.model)) : `${s.accountDiscriminator.length} + ${emptySizeC(s)}`;
|
|
56
|
+
return `TS_CLOSE(a_${a.name}, ${dest}, ${min})`;
|
|
57
|
+
}
|
|
45
58
|
call(node, topLevel) {
|
|
46
59
|
const callee = node.expression;
|
|
47
60
|
const args = node.arguments;
|
|
@@ -78,10 +91,13 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
78
91
|
case "require": {
|
|
79
92
|
if (args.length !== 2)
|
|
80
93
|
this.fail(node, "require(condition, error) takes two arguments");
|
|
81
|
-
|
|
94
|
+
let cond = this.expect(this.expr(args[0], BOOL), BOOL, args[0]);
|
|
82
95
|
if (!this.namesError(args[1])) {
|
|
83
96
|
// A code computed at run time (a helper that returns its error as a value): u32, the program error it names.
|
|
97
|
+
// The condition is evaluated first, as JS does: held when computing the code runs code that may change it.
|
|
98
|
+
const mark = this.lines.length;
|
|
84
99
|
const v = this.expr(args[1], U32);
|
|
100
|
+
cond = this.settle(cond, mark);
|
|
85
101
|
if (v.type.kind === "string")
|
|
86
102
|
this.fail(args[1], "require's error is a string literal, a member of an error enum (CounterError.X) or a u32 code; a template string or string variable is not: give the message to an error enum member");
|
|
87
103
|
const code = v.literal !== undefined ? this.literal(v.literal, U32, args[1]) : this.expect(v, U32, args[1]);
|
|
@@ -122,12 +138,13 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
122
138
|
if (args.length > 2 || args.some((a, i) => !(i === 0 && silent) && text(a) === undefined))
|
|
123
139
|
this.fail(node, 'panic() takes an optional message (or null to log nothing) and an optional "file:line:column" location: string literals or string constants');
|
|
124
140
|
const msg = silent ? undefined : args.length ? text(args[0]) : "explicit panic";
|
|
125
|
-
|
|
126
|
-
|
|
141
|
+
const style = this.panicStyle();
|
|
142
|
+
if (silent && (style === "solana-1.14" || style === "solana-1.18"))
|
|
143
|
+
this.fail(args[0], "under PANIC_STYLE a panic logs its message, as solana_program's panic handler always does: pass the message");
|
|
127
144
|
// The location the runtime reports ("SBF program Panicked in <file> at <line>:<column>"), or the panic line
|
|
128
145
|
// logs: the given one, as a ported program's panic reports it, else this source line (with its column under
|
|
129
|
-
// PANIC_STYLE, as Rust always gives one).
|
|
130
|
-
const at = args.length > 1 ? text(args[1]) :
|
|
146
|
+
// PANIC_STYLE, as Rust always gives one). Under "pinocchio" only its file is logged (a bare file is accepted).
|
|
147
|
+
const at = args.length > 1 ? text(args[1]) : style ? this.locationWithColumn(node) : this.location(node);
|
|
131
148
|
for (const l of this.panicC(msg, at))
|
|
132
149
|
this.line(l);
|
|
133
150
|
return undefined;
|
|
@@ -242,7 +259,7 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
242
259
|
else if (a === d)
|
|
243
260
|
this.fail(args[1], "the destination is the account being closed; name another writable account");
|
|
244
261
|
this.assertNotUsedAfterClose(a, node);
|
|
245
|
-
this.line(`TS_TRY(
|
|
262
|
+
this.line(`TS_TRY(${this.closeCall(a, `a_${d.name}`)});`);
|
|
246
263
|
this.forgetOwners();
|
|
247
264
|
return undefined;
|
|
248
265
|
}
|
|
@@ -423,7 +440,13 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
423
440
|
const payer = this.accountParam(args[2], "the payer");
|
|
424
441
|
if (payer.kind.kind !== "signer" || !payer.kind.mut)
|
|
425
442
|
this.fail(args[2], "the payer must be a Mut<Signer>");
|
|
426
|
-
|
|
443
|
+
// The smallest size the account may take: its discriminator and the struct, or for a @layout borsh struct its
|
|
444
|
+
// smallest Borsh form (as its load checks); the value written back at the end must still fit (3004 if not).
|
|
445
|
+
const min = !struct
|
|
446
|
+
? "0"
|
|
447
|
+
: struct.layout === "borsh"
|
|
448
|
+
? String(struct.accountDiscriminator.length + borshMinSize(struct, this.model))
|
|
449
|
+
: `${struct.accountDiscriminator.length} + sizeof(TSS_${struct.name})`;
|
|
427
450
|
this.line(`TS_TRY(ts_realloc(params, a_${payer.name}, a_${acct.name}, ${size.c}, entry_${acct.name}, ${min}));`);
|
|
428
451
|
return undefined;
|
|
429
452
|
}
|
|
@@ -659,6 +682,8 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
659
682
|
const s = targ && ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) ? this.model.structs.get(targ.typeName.text) : undefined;
|
|
660
683
|
if (!s || s.size === undefined || s.vec || s.layout === "borsh")
|
|
661
684
|
this.fail(node, "initAccount<T>(account) takes a fixed-layout account struct of this program (no growable Vec, not @layout borsh)");
|
|
685
|
+
if (s.accountDiscriminator.length !== 8)
|
|
686
|
+
this.fail(node, `${s.name}'s discriminator is shorter than 8 bytes: it is another program's account`);
|
|
662
687
|
if (args.length !== 1)
|
|
663
688
|
this.fail(node, "initAccount<T>(account) takes one account");
|
|
664
689
|
let h = this.handle(args[0]);
|
|
@@ -700,6 +725,8 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
700
725
|
this.line(`ts_log_base64(${cString(prefix)}, ${Buffer.byteLength(prefix)}, (const uint8_t *)${place.ptr}, sizeof(TSS_${sd.name}));`);
|
|
701
726
|
return undefined;
|
|
702
727
|
}
|
|
728
|
+
case "getReturnData":
|
|
729
|
+
this.fail(node, "bind both results where it is called: const [program, data] = getReturnData()");
|
|
703
730
|
case "findProgramAddressWithBump":
|
|
704
731
|
this.fail(node, "bind both results where it is called: const [address, bump] = findProgramAddressWithBump(seeds, program)");
|
|
705
732
|
case "findProgramAddress": {
|
|
@@ -863,6 +890,78 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
863
890
|
this.line(`sol_set_return_data((const uint8_t *)${s.items}, ${s.count});`);
|
|
864
891
|
return undefined;
|
|
865
892
|
}
|
|
893
|
+
case "zeroData": {
|
|
894
|
+
// Rust's `for b in data[offset..offset + length].iter_mut() { *b = 0; }` (a memset): the memset syscall, about
|
|
895
|
+
// constant compute units whatever the length, as the original's compiled loop.
|
|
896
|
+
if (args.length !== 3)
|
|
897
|
+
this.fail(node, "zeroData(account, offset, length) takes an account, a byte offset and a length");
|
|
898
|
+
// The length does not change: views of the account made before stay valid (they read the zeros).
|
|
899
|
+
let a = this.handle(args[0]);
|
|
900
|
+
if (a) {
|
|
901
|
+
if (!this.nativeAccountWrites())
|
|
902
|
+
this.line(`TS_TRY(ts_check_writable(${a}));`);
|
|
903
|
+
}
|
|
904
|
+
else {
|
|
905
|
+
const acct = this.accountParam(args[0], "zeroData's account");
|
|
906
|
+
if (acct.kind.kind !== "info" || (!isWritable(acct.kind) && !this.nativeAccountWrites()))
|
|
907
|
+
this.fail(args[0], "zeroData needs a Mut<AccountInfo> parameter or a remaining account");
|
|
908
|
+
a = `a_${acct.name}`;
|
|
909
|
+
}
|
|
910
|
+
const off = this.expect(this.expr(args[1], U64), U64, args[1]);
|
|
911
|
+
const o = this.tmp("off");
|
|
912
|
+
this.line(`uint64_t ${o} = ${off.c};`);
|
|
913
|
+
const len = this.expect(this.expr(args[2], U64), U64, args[2]);
|
|
914
|
+
const n = this.tmp("len");
|
|
915
|
+
this.line(`uint64_t ${n} = ${len.c};`);
|
|
916
|
+
this.line(`if (${o} > ${a}->data_len || ${a}->data_len - ${o} < ${n}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: write past the end of the account data");`);
|
|
917
|
+
this.line(`ts_memzero_bulk(${a}->data + ${o}, ${n});`);
|
|
918
|
+
return undefined;
|
|
919
|
+
}
|
|
920
|
+
case "copyData": {
|
|
921
|
+
// A native program's `data.copy_within(from..from + length, to)` (or a copy of a struct out of the account and
|
|
922
|
+
// back in at another offset): the memmove syscall, about constant compute units whatever the length, where a
|
|
923
|
+
// whole-struct assignment moves words one by one. Overlapping ranges are allowed.
|
|
924
|
+
if (args.length !== 4)
|
|
925
|
+
this.fail(node, "copyData(account, from, to, length) takes an account, two byte offsets and a length");
|
|
926
|
+
// The length does not change: views of the account made before stay valid (they read the copied bytes).
|
|
927
|
+
let a = this.handle(args[0]);
|
|
928
|
+
if (a) {
|
|
929
|
+
if (!this.nativeAccountWrites())
|
|
930
|
+
this.line(`TS_TRY(ts_check_writable(${a}));`);
|
|
931
|
+
}
|
|
932
|
+
else {
|
|
933
|
+
const acct = this.accountParam(args[0], "copyData's account");
|
|
934
|
+
if (acct.kind.kind !== "info" || (!isWritable(acct.kind) && !this.nativeAccountWrites()))
|
|
935
|
+
this.fail(args[0], "copyData needs a Mut<AccountInfo> parameter or a remaining account");
|
|
936
|
+
a = `a_${acct.name}`;
|
|
937
|
+
}
|
|
938
|
+
const from = this.expect(this.expr(args[1], U64), U64, args[1]);
|
|
939
|
+
const f = this.tmp("from");
|
|
940
|
+
this.line(`uint64_t ${f} = ${from.c};`);
|
|
941
|
+
const to = this.expect(this.expr(args[2], U64), U64, args[2]);
|
|
942
|
+
const t = this.tmp("to");
|
|
943
|
+
this.line(`uint64_t ${t} = ${to.c};`);
|
|
944
|
+
const len = this.expect(this.expr(args[3], U64), U64, args[3]);
|
|
945
|
+
const n = this.tmp("len");
|
|
946
|
+
this.line(`uint64_t ${n} = ${len.c};`);
|
|
947
|
+
this.line(`if (${f} > ${a}->data_len || ${a}->data_len - ${f} < ${n} || ${t} > ${a}->data_len || ${a}->data_len - ${t} < ${n}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: copy past the end of the account data");`);
|
|
948
|
+
this.line(`ts_memmove_bulk(${a}->data + ${t}, ${a}->data + ${f}, ${n});`);
|
|
949
|
+
return undefined;
|
|
950
|
+
}
|
|
951
|
+
case "log64": {
|
|
952
|
+
// Rust's `sol_log_64(a, b, c, d, e)`: the runtime writes "Program log: 0x<a>, 0x<b>, 0x<c>, 0x<d>, 0x<e>" (hex).
|
|
953
|
+
if (args.length !== 5)
|
|
954
|
+
this.fail(node, "log64(a, b, c, d, e) takes five u64 values");
|
|
955
|
+
// Left to right, each value held before the next argument is lowered (a later one may run code that changes it).
|
|
956
|
+
const ts_ = args.map((a) => {
|
|
957
|
+
const v = this.expect(this.expr(a, U64), U64, a).c;
|
|
958
|
+
const t = this.tmp("l64");
|
|
959
|
+
this.line(`uint64_t ${t} = ${v};`);
|
|
960
|
+
return t;
|
|
961
|
+
});
|
|
962
|
+
this.line(`sol_log_64(${ts_.join(", ")});`);
|
|
963
|
+
return undefined;
|
|
964
|
+
}
|
|
866
965
|
case "logComputeUnits": {
|
|
867
966
|
if (args.length)
|
|
868
967
|
this.fail(node, "logComputeUnits() takes no arguments");
|
|
@@ -1143,7 +1242,7 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1143
1242
|
if (!st) {
|
|
1144
1243
|
this.line(`${fieldC(vt.elem)} ${t};`);
|
|
1145
1244
|
this.writeAggregate({ lv: t, type: vt.elem, writable: true }, valueNode);
|
|
1146
|
-
return (el) => this.line(`
|
|
1245
|
+
return (el) => this.line(`TS_MEMCPY(&${el.lv}, &${t}, sizeof(${t}));`);
|
|
1147
1246
|
}
|
|
1148
1247
|
const val = this.ownedString(this.expect(this.expr(valueNode, st), st, valueNode));
|
|
1149
1248
|
if (st.kind === "pubkey")
|
|
@@ -2361,7 +2460,7 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
2361
2460
|
this.writeAggregate({ lv: `(*${tmp})`, type: { kind: "struct", name: To }, writable: true }, node.arguments[1]);
|
|
2362
2461
|
this.line(`TS_TRY(ts_resize(params, a_${payer.name}, a_${a.name}, 8 + sizeof(TSS_${To}), entry_${a.name}));`);
|
|
2363
2462
|
this.line(`ts_memcpy(a_${a.name}->data, TS_DISC_${To}, 8);`);
|
|
2364
|
-
this.line(`
|
|
2463
|
+
this.line(`TS_MEMCPY(a_${a.name}->data + 8, ${tmp}, sizeof(TSS_${To}));`);
|
|
2365
2464
|
this.line(`TSS_${To} *dt_${a.name} = (TSS_${To} *)(a_${a.name}->data + 8);`);
|
|
2366
2465
|
this.line(`(void)dt_${a.name};`);
|
|
2367
2466
|
this.created.add(a.name);
|
|
@@ -2972,7 +3071,7 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
2972
3071
|
const t = this.tmp("argc");
|
|
2973
3072
|
this.hoistLazy(t, (n) => (type.kind === "array" ? storageDecl(type, `(*${n})`) : `${fieldC(type)} *${n}`));
|
|
2974
3073
|
this.line(`if (${t} == NULL) TS_TRY(ts_alloc(${n}, (uint8_t **)&${t}));`);
|
|
2975
|
-
this.line(`
|
|
3074
|
+
this.line(`TS_MEMCPY(${t}, &${lv}, ${n});`);
|
|
2976
3075
|
return t;
|
|
2977
3076
|
}
|
|
2978
3077
|
/**
|
|
@@ -330,7 +330,7 @@ export class CpiCoreEmitter extends ViewEmitter {
|
|
|
330
330
|
fixed += bytes;
|
|
331
331
|
if (dynamic)
|
|
332
332
|
this.line(`if (${len} + ${n} > ${max}) TS_FAIL(${errorCode}, "TypeSOL: ${what} too large");`);
|
|
333
|
-
this.line(
|
|
333
|
+
this.line(`${bytes === undefined ? "ts_memcpy" : "TS_MEMCPY"}(${buf} + ${len}, ${src}, ${n});`);
|
|
334
334
|
this.line(`${len} += ${n};`);
|
|
335
335
|
};
|
|
336
336
|
const finish = (at) => {
|
|
@@ -542,7 +542,7 @@ export class CpiCoreEmitter extends ViewEmitter {
|
|
|
542
542
|
this.line(`uint64_t ${at} = ${count};`);
|
|
543
543
|
write((src, n) => {
|
|
544
544
|
this.line(`if (${n} > ${cap} - ${at}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: ${method}() past the FixedVec's room");`);
|
|
545
|
-
this.line(
|
|
545
|
+
this.line(`${/^\d+$/.test(n) ? "TS_MEMCPY" : "ts_memcpy"}(${bytes} + ${at}, ${src}, ${n});`);
|
|
546
546
|
this.line(`${at} += ${n};`);
|
|
547
547
|
}, { dst: bytes, cap: String(cap), at });
|
|
548
548
|
this.line(`${info.len} = (uint32_t)${at};`);
|
|
@@ -603,7 +603,7 @@ export class CpiCoreEmitter extends ViewEmitter {
|
|
|
603
603
|
const t = this.tmp("bv");
|
|
604
604
|
this.line(`${fieldC(type)} ${t};`);
|
|
605
605
|
if (type.kind === "struct")
|
|
606
|
-
this.line(`
|
|
606
|
+
this.line(`TS_ZERO_LOCAL(&${t}, sizeof(${t}));`);
|
|
607
607
|
this.writeAggregate({ lv: t, type, writable: true }, arg, true);
|
|
608
608
|
r = { lv: t, type, writable: true };
|
|
609
609
|
}
|
|
@@ -389,7 +389,7 @@ export class CpiEmitter extends MetaplexEmitter {
|
|
|
389
389
|
if (!src || src.type.kind !== "dataEnum" || src.type.name !== enumName)
|
|
390
390
|
this.fail(e, `expected a ${enumName}`);
|
|
391
391
|
this.line(`TSE_${enumName} ${t};`);
|
|
392
|
-
this.line(`
|
|
392
|
+
this.line(`TS_MEMCPY(&${t}, &${src.lv}, sizeof(${t}));`);
|
|
393
393
|
return (put) => this.serializeDataEnumLv(t, enumName, put);
|
|
394
394
|
}
|
|
395
395
|
else if (vt) {
|
|
@@ -415,7 +415,7 @@ export class CpiEmitter extends MetaplexEmitter {
|
|
|
415
415
|
this.fail(e, `expected a ${typeName(f.type)} from account data`);
|
|
416
416
|
const n = this.fieldBytes(f.type);
|
|
417
417
|
this.line(`uint8_t ${t}[${n}];`);
|
|
418
|
-
this.line(`
|
|
418
|
+
this.line(`TS_MEMCPY(${t}, &${src.lv}, ${n});`);
|
|
419
419
|
return (put) => put(t, String(n), n);
|
|
420
420
|
}
|
|
421
421
|
};
|
|
@@ -86,6 +86,7 @@ export declare abstract class ExpressionEmitter extends StorageEmitter {
|
|
|
86
86
|
* that overflows then would make the result overflow too). A negative exponent aborts, as JS throws a RangeError.
|
|
87
87
|
*/
|
|
88
88
|
protected power(node: ts.BinaryExpression, hint?: ValueType): Value;
|
|
89
|
+
private powerOf;
|
|
89
90
|
protected binary(node: ts.BinaryExpression, hint?: ValueType): Value;
|
|
90
91
|
/** Checked integer arithmetic into a fresh temporary. */
|
|
91
92
|
protected arith(op: ts.BinaryOperator, left: Value, right: Value, node: ts.Node): Value;
|
|
@@ -493,8 +493,10 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
493
493
|
return { c: `${h}->is_signer`, type: BOOL };
|
|
494
494
|
case "isWritable":
|
|
495
495
|
return { c: `${h}->is_writable`, type: BOOL };
|
|
496
|
+
case "executable":
|
|
497
|
+
return { c: `${h}->executable`, type: BOOL };
|
|
496
498
|
}
|
|
497
|
-
this.fail(node.name, `remaining accounts expose key, owner, lamports, dataLen, isSigner and
|
|
499
|
+
this.fail(node.name, `remaining accounts expose key, owner, lamports, dataLen, isSigner, isWritable and executable, not ${field}`);
|
|
498
500
|
}
|
|
499
501
|
// A struct loaded with loadAccount / loadAccountMut is also its account: key, lamports, dataLen, isSigner, isWritable.
|
|
500
502
|
if (ts.isIdentifier(node.expression)) {
|
|
@@ -898,6 +900,18 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
898
900
|
const exp = this.expr(node.right);
|
|
899
901
|
// JS reads the base first: if the exponent ran statements (a helper that changes it), use the value read before.
|
|
900
902
|
base = this.settle(base, mark);
|
|
903
|
+
// Inside panicsAt the operands keep its location, but `**` itself keeps TypeSOL's failure (5100 on overflow):
|
|
904
|
+
// Rust's `pow` panics with other messages, so its multiplications do not take the panic.
|
|
905
|
+
const outer = this.panicAt;
|
|
906
|
+
this.panicAt = undefined;
|
|
907
|
+
try {
|
|
908
|
+
return this.powerOf(node, hint, base, exp);
|
|
909
|
+
}
|
|
910
|
+
finally {
|
|
911
|
+
this.panicAt = outer;
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
powerOf(node, hint, base, exp) {
|
|
901
915
|
this.refuseF64(node, "**", base, exp);
|
|
902
916
|
if (base.literal !== undefined)
|
|
903
917
|
base = this.literal(base.literal, hint?.kind === "int" ? hint : U64, node.left);
|
|
@@ -64,7 +64,7 @@ export class FunctionEmitter extends StatementEmitter {
|
|
|
64
64
|
const n = k.struct.accountDiscriminator.length;
|
|
65
65
|
// A shorter discriminator (another program's zero-copy account): AccountLoader's checks with its length.
|
|
66
66
|
if (n !== 8)
|
|
67
|
-
head.push(` if (!ts_key_eq(&${v}->owner, ${owner})) TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: ${a.name} is not owned by the expected program");`, ` if (${v}->data_len < ${n}) TS_FAIL(TS_ERR_DISC_NOT_FOUND, "TypeSOL: ${a.name} has no discriminator");`, ` if (!ts_mem_eq(${v}->data, TS_DISC_${k.struct.name}, ${n})) TS_FAIL(TS_ERR_DISCRIMINATOR, "TypeSOL: ${a.name}: discriminator mismatch");`, ` if (${v}->data_len < ${n} + ${emptySizeC(k.struct)}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: ${a.name} is too small");`);
|
|
67
|
+
head.push(` if (!ts_key_eq(&${v}->owner, ${owner})) TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: ${a.name} is not owned by the expected program");`, ` if (${v}->data_len < ${n}) TS_FAIL(TS_ERR_DISC_NOT_FOUND, "TypeSOL: ${a.name} has no discriminator");`, ` if (!ts_mem_eq(${v}->data, TS_DISC_${k.struct.name}, ${n})) TS_FAIL(TS_ERR_DISCRIMINATOR, "TypeSOL: ${a.name}: discriminator mismatch");`, ` if (${v}->data_len < ${n} + ${k.struct.layout === "borsh" ? borshMinSize(k.struct, this.model) : emptySizeC(k.struct)}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: ${a.name} is too small");`);
|
|
68
68
|
else
|
|
69
69
|
head.push(k.struct.idlMeta?.serialization?.startsWith("bytemuck")
|
|
70
70
|
? ` TS_TRY(ts_check_loader_account(${v}, ${owner}, TS_DISC_${k.struct.name}, ${emptySizeC(k.struct)}));`
|
|
@@ -144,15 +144,18 @@ export class FunctionEmitter extends StatementEmitter {
|
|
|
144
144
|
// unused slots start as zero: ts_unpack_* only writes what the Borsh bytes hold.
|
|
145
145
|
const S = k.struct.name;
|
|
146
146
|
head.push(` TSS_${S} *d_${a.name} = NULL;`, ` TS_TRY(ts_alloc(sizeof(TSS_${S}), (uint8_t **)&d_${a.name}));`);
|
|
147
|
+
// The Borsh bytes start after the discriminator, of whichever length the struct declares (the checks above
|
|
148
|
+
// ensured the account holds it and the smallest Borsh form after it).
|
|
149
|
+
const n = k.struct.accountDiscriminator.length;
|
|
147
150
|
if (k.kind === "account")
|
|
148
|
-
head.push(` TS_TRY(ts_unpack_${S}(${v}->data +
|
|
151
|
+
head.push(` TS_TRY(ts_unpack_${S}(${v}->data + ${n}, ${v}->data_len - ${n}, d_${a.name}, NULL));`);
|
|
149
152
|
}
|
|
150
153
|
else if (k.kind === "account" || k.kind === "init" || k.kind === "zeroed" || k.kind === "initIfNeeded") {
|
|
151
154
|
head.push(` TSS_${k.struct.name} *d_${a.name} = (TSS_${k.struct.name} *)(${v}->data + ${k.struct.accountDiscriminator.length});`);
|
|
152
155
|
if (k.struct.vec) {
|
|
153
156
|
head.push(` uint64_t entry_${a.name} = ${v}->data_len;`, ` (void)entry_${a.name};`);
|
|
154
157
|
if (k.kind === "account")
|
|
155
|
-
head.push(...vecLenCheck(k.struct, v, `d_${a.name}
|
|
158
|
+
head.push(...vecLenCheck(k.struct, v, `d_${a.name}`, " ", k.struct.accountDiscriminator.length));
|
|
156
159
|
}
|
|
157
160
|
}
|
|
158
161
|
// realloc(x, …) needs the size the account had when the instruction started (the 10 KiB growth limit), as does
|
|
@@ -366,7 +369,7 @@ export class FunctionEmitter extends StatementEmitter {
|
|
|
366
369
|
const ft = a.type.kind === "structRef" ? { kind: "struct", name: a.type.struct } : a.type.array;
|
|
367
370
|
const size = this.fieldBytes(ft);
|
|
368
371
|
need(String(size));
|
|
369
|
-
head.push(` ${decl};`, ` TS_TRY(ts_alloc(${size}, (uint8_t **)&${v}));`, `
|
|
372
|
+
head.push(` ${decl};`, ` TS_TRY(ts_alloc(${size}, (uint8_t **)&${v}));`, ` TS_MEMCPY(${v}, ${at}, ${size});`, ` off += ${size};`);
|
|
370
373
|
head.push(...this.validation(`(*${v})`, ft, " "));
|
|
371
374
|
}
|
|
372
375
|
else if (a.type.kind === "dataEnumArg") {
|
|
@@ -374,7 +377,7 @@ export class FunctionEmitter extends StatementEmitter {
|
|
|
374
377
|
const e = this.model.dataEnums.get(a.type.name);
|
|
375
378
|
const v = `arg_${a.name}__v`;
|
|
376
379
|
need("1");
|
|
377
|
-
head.push(` TSE_${e.name} ${v};`, `
|
|
380
|
+
head.push(` TSE_${e.name} ${v};`, ` TS_ZERO_LOCAL(&${v}, sizeof(${v}));`, ` ${v}.tag = *(${at});`, ` off += 1;`);
|
|
378
381
|
head.push(` switch (${v}.tag) {`);
|
|
379
382
|
e.variants.forEach((variant, i) => {
|
|
380
383
|
head.push(` case ${i}: {`);
|
|
@@ -394,7 +397,7 @@ export class FunctionEmitter extends StatementEmitter {
|
|
|
394
397
|
const lv = `${v}.v.${variant.name}.${f.name}`;
|
|
395
398
|
const size = this.fieldBytes(f.type);
|
|
396
399
|
head.push(` if (params->data_len < off + ${size}) TS_FAIL(TS_ERR_INSTRUCTION_DATA, "TypeSOL: instruction data too short");`);
|
|
397
|
-
head.push(`
|
|
400
|
+
head.push(` TS_MEMCPY(&${lv}, params->data + off, ${size});`, ` off += ${size};`);
|
|
398
401
|
head.push(...this.validation(lv, f.type, " "));
|
|
399
402
|
continue;
|
|
400
403
|
}
|
|
@@ -549,14 +552,15 @@ export class FunctionEmitter extends StatementEmitter {
|
|
|
549
552
|
.map((a) => {
|
|
550
553
|
const v = `a_${a.name}`;
|
|
551
554
|
const S = a.kind.struct.name;
|
|
552
|
-
|
|
555
|
+
const n = a.kind.struct.accountDiscriminator.length;
|
|
556
|
+
return `if (${a.optional ? `${v} != NULL && ` : ""}${v}->data_len >= ${n} && ts_key_eq(&${v}->owner, params->program_id)) TS_TRY(ts_pack_${S}(d_${a.name}, ${v}->data + ${n}, ${v}->data_len - ${n}, NULL));`;
|
|
553
557
|
});
|
|
554
558
|
return [
|
|
555
559
|
...packs,
|
|
556
560
|
...this.ix.accounts
|
|
557
561
|
.filter((a) => a.constraints.closeTo)
|
|
558
562
|
.map((a) => {
|
|
559
|
-
const line = `TS_TRY(
|
|
563
|
+
const line = `TS_TRY(${this.closeCall(a, `a_${a.constraints.closeTo}`)});`;
|
|
560
564
|
const optional = this.optionalIn(line);
|
|
561
565
|
return optional.length ? `if (${optional.map((n) => `a_${n} != NULL`).join(" && ")}) ${line}` : line;
|
|
562
566
|
}),
|
|
@@ -59,12 +59,18 @@ export function emitProgram(analysis, opts = {}) {
|
|
|
59
59
|
else if (panicFlag.value)
|
|
60
60
|
out.push(`#define TS_PANIC_ON_OVERFLOW 1`);
|
|
61
61
|
}
|
|
62
|
-
// `const PANIC_STYLE = "solana-1.14"`: panics log as solana_program
|
|
63
|
-
// emitter); PANIC_ON_OVERFLOW's panics abort too instead of calling sol_panic_.
|
|
62
|
+
// `const PANIC_STYLE = "solana-1.14"` / `"solana-1.18"`: panics log as that solana_program's panic handler does and
|
|
63
|
+
// abort (read by the emitter); PANIC_ON_OVERFLOW's panics abort too instead of calling sol_panic_.
|
|
64
|
+
// `"pinocchio"`: pinocchio's panic hook (the location's file, then "** PANICKED **", then abort), through one helper.
|
|
64
65
|
const panicStyle = model.constants.get("PANIC_STYLE");
|
|
65
66
|
if (panicStyle) {
|
|
66
|
-
if (panicStyle.value !== "solana-1.14")
|
|
67
|
-
reporter.error(analysis.sourceFile,
|
|
67
|
+
if (panicStyle.value !== "solana-1.14" && panicStyle.value !== "solana-1.18" && panicStyle.value !== "pinocchio")
|
|
68
|
+
reporter.error(analysis.sourceFile, 'PANIC_STYLE must be "solana-1.14" (panics log `panicked at \'<message>\', <file>:<line>:<col>` and abort, as programs built with solana-program 1.14 to 1.17 do), "solana-1.18" (`panicked at <file>:<line>:<col>:` and the message on the next line, then abort, as solana-program 1.18\'s) or "pinocchio" (the file alone, then `** PANICKED **`, then abort, as pinocchio\'s entrypoint! hook); leave it out for the default');
|
|
69
|
+
else if (panicStyle.value === "pinocchio") {
|
|
70
|
+
if (panicFlag?.value === true)
|
|
71
|
+
reporter.error(analysis.sourceFile, 'PANIC_ON_OVERFLOW cannot be used with PANIC_STYLE = "pinocchio": that panic hook logs the file the panic is in, which an overflow outside panicsAt does not have; wrap the arithmetic in panicsAt(location, …) instead');
|
|
72
|
+
out.push(`#define TS_PANIC_PINOCCHIO 1`);
|
|
73
|
+
}
|
|
68
74
|
else if (panicFlag?.value === true)
|
|
69
75
|
out.push(`#define TS_PANIC_ABORT 1`);
|
|
70
76
|
}
|
|
@@ -49,7 +49,7 @@ function emitTree(model, t) {
|
|
|
49
49
|
` int c;`,
|
|
50
50
|
` TS_TRY(${p}_cmp(params, key, (const ${K} *)(ts_rbt_node(t, ${S}, parent) + 16), &c));`,
|
|
51
51
|
` if (c == 0) {`,
|
|
52
|
-
`
|
|
52
|
+
` TS_MEMCPY(ts_rbt_node(t, ${S}, parent) + ${16 + ks}, value, ${vs});`,
|
|
53
53
|
` *out = parent;`,
|
|
54
54
|
` return SUCCESS;`,
|
|
55
55
|
` }`,
|
|
@@ -218,9 +218,10 @@ export declare function vecPlace(s: StructDef, base: string, k: number): {
|
|
|
218
218
|
};
|
|
219
219
|
/**
|
|
220
220
|
* C lines checking that an account's size matches its growable Vecs' lengths (`d`: its TSS_<S> pointer, `a`: its
|
|
221
|
-
* TsAccount
|
|
221
|
+
* TsAccount, `disc`: its discriminator's length). One Vec after an 8-byte discriminator: ts_check_vec_len; otherwise
|
|
222
|
+
* each length read only once the bytes before it are known to exist.
|
|
222
223
|
*/
|
|
223
|
-
export declare function vecLenCheck(s: StructDef, a: string, d: string, pad?: string): string[];
|
|
224
|
+
export declare function vecLenCheck(s: StructDef, a: string, d: string, pad?: string, disc?: number): string[];
|
|
224
225
|
/** C typedef name of a FixedVec<T, N>: `{ uint32_t len; T items[N]; }`. */
|
|
225
226
|
export declare function fixedVecC(t: FieldType & {
|
|
226
227
|
kind: "vec";
|
|
@@ -237,3 +238,12 @@ export declare const F64_TO_INT: (to: string) => string;
|
|
|
237
238
|
export declare const F64_TEXT = "an f64 cannot be written as text: there is no float formatting, and the digits would be its IEEE 754 bits read as an integer; to show the bits, write f64Bits(x)";
|
|
238
239
|
/** An integer used where an f64 is expected. */
|
|
239
240
|
export declare const INT_TO_F64: (from: string) => string;
|
|
241
|
+
/**
|
|
242
|
+
* Whether a C lvalue is reached through a pointer the optimizer cannot see behind: account data (`d_acct->f`, a
|
|
243
|
+
* Migrate's `(*df_a)`, a view made in place), a view or reference local, a helper's pointer parameter (`(*p_x).f`). Not a local of the
|
|
244
|
+
* function (`st3.f`, `l_x___v`) nor a helper's result (`(*ret)`, `(*(&t4))`), whose copies clang may fold away when it
|
|
245
|
+
* unrolls them: those take the memory syscalls only where it would emit a loop (runtime/typesol_rt.h).
|
|
246
|
+
*/
|
|
247
|
+
export declare function throughPointer(lv: string): boolean;
|
|
248
|
+
/** A whole copy between two places of one type: TS_COPY when both are reached through pointers, else TS_COPY_LOCAL. */
|
|
249
|
+
export declare function copyMacro(dst: string, src: string): string;
|
|
@@ -295,19 +295,20 @@ export function vecPlace(s, base, k) {
|
|
|
295
295
|
}
|
|
296
296
|
/**
|
|
297
297
|
* C lines checking that an account's size matches its growable Vecs' lengths (`d`: its TSS_<S> pointer, `a`: its
|
|
298
|
-
* TsAccount
|
|
298
|
+
* TsAccount, `disc`: its discriminator's length). One Vec after an 8-byte discriminator: ts_check_vec_len; otherwise
|
|
299
|
+
* each length read only once the bytes before it are known to exist.
|
|
299
300
|
*/
|
|
300
|
-
export function vecLenCheck(s, a, d, pad = " ") {
|
|
301
|
+
export function vecLenCheck(s, a, d, pad = " ", disc = 8) {
|
|
301
302
|
const vs = s.vecs ?? [];
|
|
302
|
-
if (vs.length === 1)
|
|
303
|
+
if (vs.length === 1 && disc === 8)
|
|
303
304
|
return [`${pad}TS_TRY(ts_check_vec_len(${a}, sizeof(TSS_${s.name}), ${d}->${vs[0].name}__len, TS_ELEM_${s.name}));`];
|
|
304
305
|
const o = `${d.replace(/\W/g, "")}__vo`;
|
|
305
306
|
const lines = [`${pad}{`, `${pad} uint64_t ${o} = sizeof(TSS_${s.name}) + (uint64_t)${d}->${vs[0].name}__len * ${vs[0].elemSize};`];
|
|
306
307
|
for (const v of vs.slice(1)) {
|
|
307
|
-
lines.push(`${pad} if (${a}->data_len <
|
|
308
|
-
lines.push(`${pad} ${o} += 4 + (uint64_t)((${laterVecC(s.name, v.name)} *)(${a}->data +
|
|
308
|
+
lines.push(`${pad} if (${a}->data_len < ${disc} + ${o} + 4) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account size does not match its Vec lengths");`);
|
|
309
|
+
lines.push(`${pad} ${o} += 4 + (uint64_t)((${laterVecC(s.name, v.name)} *)(${a}->data + ${disc} + ${o}))->len * ${v.elemSize};`);
|
|
309
310
|
}
|
|
310
|
-
lines.push(`${pad} if (${a}->data_len !=
|
|
311
|
+
lines.push(`${pad} if (${a}->data_len != ${disc} + ${o}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account size does not match its Vec lengths");`, `${pad}}`);
|
|
311
312
|
return lines;
|
|
312
313
|
}
|
|
313
314
|
/** C typedef name of a FixedVec<T, N>: `{ uint32_t len; T items[N]; }`. */
|
|
@@ -330,3 +331,22 @@ export const F64_TO_INT = (to) => `an f64 is not an integer, so it is not conver
|
|
|
330
331
|
export const F64_TEXT = "an f64 cannot be written as text: there is no float formatting, and the digits would be its IEEE 754 bits read as an integer; to show the bits, write f64Bits(x)";
|
|
331
332
|
/** An integer used where an f64 is expected. */
|
|
332
333
|
export const INT_TO_F64 = (from) => `a ${from} is not an f64, so it is not converted: an f64 is made from its IEEE 754 bits with f64FromBits(bits)`;
|
|
334
|
+
/**
|
|
335
|
+
* Whether a C lvalue is reached through a pointer the optimizer cannot see behind: account data (`d_acct->f`, a
|
|
336
|
+
* Migrate's `(*df_a)`, a view made in place), a view or reference local, a helper's pointer parameter (`(*p_x).f`). Not a local of the
|
|
337
|
+
* function (`st3.f`, `l_x___v`) nor a helper's result (`(*ret)`, `(*(&t4))`), whose copies clang may fold away when it
|
|
338
|
+
* unrolls them: those take the memory syscalls only where it would emit a loop (runtime/typesol_rt.h).
|
|
339
|
+
*/
|
|
340
|
+
export function throughPointer(lv) {
|
|
341
|
+
const m = /^\(\*([A-Za-z_][A-Za-z0-9_]*)\)/.exec(lv);
|
|
342
|
+
if (m)
|
|
343
|
+
return m[1] !== "ret";
|
|
344
|
+
// A view made where it is read (`(*((TSS_T *)(acct->data + off)))`, a tree node's value), not a local's address.
|
|
345
|
+
if (lv.startsWith("(*(") && !lv.startsWith("(*(&"))
|
|
346
|
+
return true;
|
|
347
|
+
return /^d_[A-Za-z0-9_]+->/.test(lv);
|
|
348
|
+
}
|
|
349
|
+
/** A whole copy between two places of one type: TS_COPY when both are reached through pointers, else TS_COPY_LOCAL. */
|
|
350
|
+
export function copyMacro(dst, src) {
|
|
351
|
+
return throughPointer(dst) && throughPointer(src) ? "TS_COPY" : "TS_COPY_LOCAL";
|
|
352
|
+
}
|
|
@@ -164,9 +164,16 @@ export declare abstract class StatementEmitter extends CpiEmitter {
|
|
|
164
164
|
protected heapLocal(d: ts.VariableDeclaration, aggregate: boolean): boolean;
|
|
165
165
|
/** A `@heap` local must fit in the heap (32 KiB, or HEAP_SIZE_KIB), which other allocations share. */
|
|
166
166
|
protected checkHeapRoom(bytes: number, at: ts.Node): void;
|
|
167
|
+
/**
|
|
168
|
+
* `const [program, data] = getReturnData()`: Rust's `get_return_data()`, the return data as the runtime holds it
|
|
169
|
+
* (sol_get_return_data): the program that set it and its bytes, read into 1 KiB of this function's stack frame (the
|
|
170
|
+
* runtime's maximum, so nothing is cut). Rust's `None` is `data.length === 0n` (the runtime keeps no empty return
|
|
171
|
+
* data), with `program` then all zeros.
|
|
172
|
+
*/
|
|
173
|
+
protected programAndReturnData(d: ts.VariableDeclaration, pattern: ts.ArrayBindingPattern, call: ts.CallExpression, mutable: boolean): void;
|
|
167
174
|
/**
|
|
168
175
|
* `const [address, bump] = findProgramAddressWithBump(seeds, program)`: Rust's `let (address, bump) =
|
|
169
|
-
* Pubkey::find_program_address(…)`, both from one search (the only array destructuring
|
|
176
|
+
* Pubkey::find_program_address(…)`, both from one search (with getReturnData, the only array destructuring).
|
|
170
177
|
*/
|
|
171
178
|
protected addressAndBump(d: ts.VariableDeclaration, pattern: ts.ArrayBindingPattern, mutable: boolean): void;
|
|
172
179
|
/**
|
|
@@ -664,7 +664,7 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
664
664
|
const closure = { node: st.fn, name: "map's callback", scopes: [...this.scopes], env: this.envNow(), imports: this.scope.imports };
|
|
665
665
|
const sc = this.tmp("lm_s");
|
|
666
666
|
this.line(`TSS_${S.name} ${sc}__v;`);
|
|
667
|
-
this.line(`
|
|
667
|
+
this.line(`TS_ZERO_LOCAL(&${sc}__v, sizeof(${sc}__v));`);
|
|
668
668
|
this.expandClosure(closure, [element, idx].slice(0, st.fn.parameters.length), st.fn, {
|
|
669
669
|
lv: `${sc}__v`,
|
|
670
670
|
type: { kind: "struct", name: S.name },
|
|
@@ -1370,7 +1370,7 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1370
1370
|
if (frame.type.kind === "pubkey")
|
|
1371
1371
|
this.line(`${frame.result} = *(${v.c});`);
|
|
1372
1372
|
else if (frame.type.kind === "option" && v.isNull)
|
|
1373
|
-
this.line(`
|
|
1373
|
+
this.line(`TS_ZERO_LOCAL(&${frame.result}, sizeof(${frame.result}));`);
|
|
1374
1374
|
else
|
|
1375
1375
|
this.line(`${frame.result} = ${this.ownedString(v).c};`);
|
|
1376
1376
|
this.line(`goto ${frame.label};`);
|
|
@@ -1485,7 +1485,11 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1485
1485
|
continue;
|
|
1486
1486
|
}
|
|
1487
1487
|
if (ts.isArrayBindingPattern(d.name)) {
|
|
1488
|
-
|
|
1488
|
+
const init = d.initializer;
|
|
1489
|
+
if (init && ts.isCallExpression(init) && this.exportName(init.expression) === "getReturnData")
|
|
1490
|
+
this.programAndReturnData(d, d.name, init, mutable);
|
|
1491
|
+
else
|
|
1492
|
+
this.addressAndBump(d, d.name, mutable);
|
|
1489
1493
|
continue;
|
|
1490
1494
|
}
|
|
1491
1495
|
if (!ts.isIdentifier(d.name) || !d.initializer)
|
|
@@ -1830,15 +1834,59 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1830
1834
|
if (bytes > room)
|
|
1831
1835
|
this.fail(at, `this local takes ${bytes} bytes and the heap holds ${room} (raise HEAP_SIZE_KIB, at most 256)`);
|
|
1832
1836
|
}
|
|
1837
|
+
/**
|
|
1838
|
+
* `const [program, data] = getReturnData()`: Rust's `get_return_data()`, the return data as the runtime holds it
|
|
1839
|
+
* (sol_get_return_data): the program that set it and its bytes, read into 1 KiB of this function's stack frame (the
|
|
1840
|
+
* runtime's maximum, so nothing is cut). Rust's `None` is `data.length === 0n` (the runtime keeps no empty return
|
|
1841
|
+
* data), with `program` then all zeros.
|
|
1842
|
+
*/
|
|
1843
|
+
programAndReturnData(d, pattern, call, mutable) {
|
|
1844
|
+
const usage = "const [program, data] = getReturnData()";
|
|
1845
|
+
if (mutable)
|
|
1846
|
+
this.fail(d, `bind them with const: ${usage}`);
|
|
1847
|
+
if (d.type)
|
|
1848
|
+
this.fail(d.type, "leave the type out: the program is a Pubkey and the data a read-only list of u8 (InstructionBytes)");
|
|
1849
|
+
if (call.arguments.length)
|
|
1850
|
+
this.fail(call, "getReturnData() takes no arguments");
|
|
1851
|
+
if (pattern.elements.length > 2)
|
|
1852
|
+
this.fail(pattern, `getReturnData gives two values: ${usage}`);
|
|
1853
|
+
const names = pattern.elements.map((el) => {
|
|
1854
|
+
if (ts.isOmittedExpression(el))
|
|
1855
|
+
return undefined;
|
|
1856
|
+
if (el.dotDotDotToken || el.initializer || !ts.isIdentifier(el.name))
|
|
1857
|
+
this.fail(el, `name the program and the data: ${usage}`);
|
|
1858
|
+
const name = el.name.text;
|
|
1859
|
+
if (this.scopes.at(-1).has(name))
|
|
1860
|
+
this.fail(el.name, `"${name}" is already declared`);
|
|
1861
|
+
if (this.accounts.has(name) || this.args.has(name) || this.isGroup(name))
|
|
1862
|
+
this.fail(el.name, `"${name}" shadows the parameter "${name}"; use another name`);
|
|
1863
|
+
return name;
|
|
1864
|
+
});
|
|
1865
|
+
const [program, data] = names;
|
|
1866
|
+
const key = program ? `l_${program}_${this.temp++}` : this.tmp("rdfrom");
|
|
1867
|
+
const buf = this.tmp("rdbuf");
|
|
1868
|
+
const len = this.tmp("rdlen");
|
|
1869
|
+
this.line(`SolPubkey ${key} = {0}; uint8_t ${buf}[1024];`);
|
|
1870
|
+
this.line(`uint64_t ${len} = sol_get_return_data(${buf}, sizeof(${buf}), &${key});`);
|
|
1871
|
+
if (program)
|
|
1872
|
+
this.scopes.at(-1).set(program, { c: key, type: PUBKEY, mutable: false });
|
|
1873
|
+
if (data) {
|
|
1874
|
+
const c = `l_${data}_${this.temp++}`;
|
|
1875
|
+
this.line(`TS_VecArg ${c} = {${buf}, (uint32_t)(${len} < sizeof(${buf}) ? ${len} : sizeof(${buf}))};`);
|
|
1876
|
+
this.scopes.at(-1).set(data, { c, type: { kind: "vecArg", elem: { kind: "int", name: "u8" } }, mutable: false });
|
|
1877
|
+
}
|
|
1878
|
+
else
|
|
1879
|
+
this.line(`(void)${len};`);
|
|
1880
|
+
}
|
|
1833
1881
|
/**
|
|
1834
1882
|
* `const [address, bump] = findProgramAddressWithBump(seeds, program)`: Rust's `let (address, bump) =
|
|
1835
|
-
* Pubkey::find_program_address(…)`, both from one search (the only array destructuring
|
|
1883
|
+
* Pubkey::find_program_address(…)`, both from one search (with getReturnData, the only array destructuring).
|
|
1836
1884
|
*/
|
|
1837
1885
|
addressAndBump(d, pattern, mutable) {
|
|
1838
1886
|
const init = d.initializer;
|
|
1839
1887
|
const call = init && ts.isCallExpression(init) && this.exportName(init.expression) === "findProgramAddressWithBump" ? init : undefined;
|
|
1840
1888
|
if (!call)
|
|
1841
|
-
this.fail(d.name, "array destructuring is only for const [address, bump] = findProgramAddressWithBump(seeds, program)");
|
|
1889
|
+
this.fail(d.name, "array destructuring is only for const [address, bump] = findProgramAddressWithBump(seeds, program) and const [program, data] = getReturnData()");
|
|
1842
1890
|
if (mutable)
|
|
1843
1891
|
this.fail(d, "bind them with const: const [address, bump] = findProgramAddressWithBump(seeds, program)");
|
|
1844
1892
|
if (d.type)
|