@typesol/cli 0.42.0 → 0.44.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 +350 -0
- package/NOTICE +71 -0
- package/README.md +35 -18
- package/SECURITY.md +32 -5
- package/dist/ai.d.ts +1 -1
- package/dist/ai.js +5 -5
- package/dist/cli.js +196 -72
- package/dist/compiler/analyze.js +447 -12
- package/dist/compiler/diagnostics.d.ts +1 -0
- package/dist/compiler/diagnostics.js +13 -0
- package/dist/compiler/emit/alias.d.ts +45 -1
- package/dist/compiler/emit/alias.js +143 -6
- package/dist/compiler/emit/base.d.ts +28 -1
- package/dist/compiler/emit/base.js +77 -9
- package/dist/compiler/emit/borsh.js +11 -5
- package/dist/compiler/emit/calls.d.ts +80 -0
- package/dist/compiler/emit/calls.js +612 -54
- package/dist/compiler/emit/cpi-core.d.ts +23 -4
- package/dist/compiler/emit/cpi-core.js +261 -12
- package/dist/compiler/emit/cpi.js +8 -2
- package/dist/compiler/emit/create.js +3 -0
- package/dist/compiler/emit/expressions.js +44 -8
- package/dist/compiler/emit/function.js +10 -0
- package/dist/compiler/emit/program.js +30 -1
- package/dist/compiler/emit/rbtree.d.ts +7 -0
- package/dist/compiler/emit/rbtree.js +142 -0
- package/dist/compiler/emit/shared.d.ts +25 -0
- package/dist/compiler/emit/shared.js +45 -4
- package/dist/compiler/emit/statements.d.ts +27 -1
- package/dist/compiler/emit/statements.js +305 -23
- package/dist/compiler/emit/storage.d.ts +25 -2
- package/dist/compiler/emit/storage.js +116 -64
- package/dist/compiler/emit/token.js +2 -2
- package/dist/compiler/emit/views.d.ts +60 -0
- package/dist/compiler/emit/views.js +523 -0
- package/dist/compiler/idl.js +2 -1
- package/dist/compiler/index.d.ts +15 -1
- package/dist/compiler/index.js +40 -3
- package/dist/compiler/model.d.ts +65 -4
- package/dist/compiler/model.js +14 -0
- package/dist/compiler/toolchain.d.ts +56 -1
- package/dist/compiler/toolchain.js +246 -12
- package/dist/testing-stake.d.ts +2 -1
- package/dist/testing-stake.js +2 -1
- package/dist/testing.js +6 -4
- package/dist/tools/clientgen.d.ts +15 -0
- package/dist/tools/clientgen.js +173 -7
- package/dist/tools/cpigen.d.ts +0 -15
- package/dist/tools/cpigen.js +19 -8
- package/dist/tools/doctor.d.ts +17 -2
- package/dist/tools/doctor.js +64 -4
- package/dist/tools/portgen.js +43 -18
- package/dist/workspace.d.ts +20 -0
- package/dist/workspace.js +173 -6
- package/docs/ai.md +10 -5
- package/docs/architecture.md +10 -3
- package/docs/audit.md +63 -17
- package/docs/case-study-escrow.md +1 -1
- package/docs/case-study-phoenix.md +226 -0
- package/docs/case-study-raydium-amm.md +3 -3
- package/docs/case-study-spl-stake-pool.md +5 -5
- package/docs/cli.md +17 -8
- package/docs/client.md +11 -3
- package/docs/errors.md +1 -1
- package/docs/language.md +148 -12
- package/docs/mainnet.md +21 -10
- package/docs/migrate-from-anchor.md +3 -1
- package/docs/runtime.md +12 -2
- package/docs/security-model.md +38 -6
- package/docs/stability.md +42 -4
- package/docs/testing.md +25 -0
- package/docs/troubleshooting.md +17 -2
- package/lib/typesol.d.ts +221 -4
- package/llms-full.txt +336 -65
- package/llms.txt +2 -2
- package/package.json +4 -2
- package/runtime/typesol_rt.h +429 -13
- package/test/programs/LICENSE-Apache-2.0.txt +201 -0
package/dist/tools/clientgen.js
CHANGED
|
@@ -78,7 +78,7 @@ export const TYPESOL_ERRORS = {
|
|
|
78
78
|
5114: "NoReturnData",
|
|
79
79
|
5115: "AccountMissing",
|
|
80
80
|
};
|
|
81
|
-
const INTS = { u8: 8, u16: 16, u32: 32, u64: 64, u128: 128, i8: 8, i16: 16, i32: 32, i64: 64, i128: 128 };
|
|
81
|
+
const INTS = { u8: 8, u16: 16, u32: 32, u64: 64, u128: 128, u256: 256, i8: 8, i16: 16, i32: 32, i64: 64, i128: 128, i256: 256 };
|
|
82
82
|
const FLOATS = { f32: 32, f64: 64 };
|
|
83
83
|
const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
84
84
|
/** A seed path: `arg`, `arg.field…`, or `opt.unwrap_or(N)` (Anchor's text for an Option argument with a default). */
|
|
@@ -105,6 +105,8 @@ const TAKEN = [
|
|
|
105
105
|
"fixedString",
|
|
106
106
|
"fixedOption",
|
|
107
107
|
"unitEnum",
|
|
108
|
+
"lazyCodec",
|
|
109
|
+
"wideInt",
|
|
108
110
|
// exports
|
|
109
111
|
"PROGRAM_ADDRESS",
|
|
110
112
|
"ERRORS",
|
|
@@ -117,6 +119,9 @@ const TAKEN = [
|
|
|
117
119
|
"AccountRole",
|
|
118
120
|
"Address",
|
|
119
121
|
"Codec",
|
|
122
|
+
"Option",
|
|
123
|
+
"OptionOrNullable",
|
|
124
|
+
"getOptionCodec",
|
|
120
125
|
"FetchAccountConfig",
|
|
121
126
|
"GetAccountInfoApi",
|
|
122
127
|
"Instruction",
|
|
@@ -128,6 +133,7 @@ const TAKEN = [
|
|
|
128
133
|
"addCodecSizePrefix",
|
|
129
134
|
"address",
|
|
130
135
|
"createCodec",
|
|
136
|
+
"isFixedSize",
|
|
131
137
|
"fetchEncodedAccount",
|
|
132
138
|
"fixCodecSize",
|
|
133
139
|
"getAddressCodec",
|
|
@@ -205,6 +211,8 @@ const KIT_TYPES = [
|
|
|
205
211
|
"ReadonlyUint8Array",
|
|
206
212
|
"Rpc",
|
|
207
213
|
"TransactionSigner",
|
|
214
|
+
"Option",
|
|
215
|
+
"OptionOrNullable",
|
|
208
216
|
];
|
|
209
217
|
const KIT_VALUES = [
|
|
210
218
|
"AccountRole",
|
|
@@ -227,6 +235,7 @@ const KIT_VALUES = [
|
|
|
227
235
|
"addCodecSizePrefix",
|
|
228
236
|
"address",
|
|
229
237
|
"createCodec",
|
|
238
|
+
"isFixedSize",
|
|
230
239
|
"fetchEncodedAccount",
|
|
231
240
|
"fixCodecSize",
|
|
232
241
|
"getAddressCodec",
|
|
@@ -245,6 +254,7 @@ const KIT_VALUES = [
|
|
|
245
254
|
"getI64Codec",
|
|
246
255
|
"getI8Codec",
|
|
247
256
|
"getNullableCodec",
|
|
257
|
+
"getOptionCodec",
|
|
248
258
|
"getProgramDerivedAddress",
|
|
249
259
|
"getStructCodec",
|
|
250
260
|
"getTupleCodec",
|
|
@@ -289,16 +299,49 @@ const pascal = (s) => {
|
|
|
289
299
|
};
|
|
290
300
|
const prop = (s) => (NAME.test(s) && !JS_RESERVED.has(s) ? s : JSON.stringify(s));
|
|
291
301
|
/** Text safe to print on a terminal (notes, errors): C0 and C1 control characters and bidi overrides escaped. */
|
|
292
|
-
const printable = (s) => s.replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
293
|
-
/** Text that can sit inside a block comment: printable ASCII, no comment terminator. */
|
|
294
|
-
const commentText = (s) => s.replace(/[^\x20-\x7e]/g, " ").replace(/\*\//g, "* /");
|
|
302
|
+
export const printable = (s) => s.replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
303
|
+
/** Text that can sit inside a block or line comment: printable ASCII (no line breaks), no comment terminator. */
|
|
304
|
+
export const commentText = (s) => s.replace(/[^\x20-\x7e]/g, " ").replace(/\*\//g, "* /");
|
|
295
305
|
const doc = (lines, indent = "") => Array.isArray(lines) && lines.length && lines.every((l) => typeof l === "string")
|
|
296
306
|
? `${indent}/** ${lines.map(commentText).join(`\n${indent} * `)} */\n`
|
|
297
307
|
: "";
|
|
298
308
|
const bytes = (b) => `new Uint8Array([${b.join(", ")}])`;
|
|
299
309
|
const definedName = (t) => typeof t === "object" && t !== null && t.defined ? (typeof t.defined === "string" ? t.defined : t.defined.name) : undefined;
|
|
310
|
+
/** An `option` type (Anchor's Option; not a COption, whose fixed layout differs). */
|
|
311
|
+
const nestedOption = (t) => typeof t === "object" && t !== null && t.option !== undefined;
|
|
300
312
|
const isField = (f) => typeof f === "object" && f !== null && "name" in f && "type" in f;
|
|
301
313
|
const sortCodeUnits = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
|
|
314
|
+
/** What to do with an IDL written before Anchor 0.30's format (the generators read only 0.30+ / 1.x and TypeSOL IDLs). */
|
|
315
|
+
const LEGACY_IDL = "this is a pre-0.30 Anchor IDL (accounts marked isMut / isSigner, no discriminators): convert it first with `anchor idl convert <idl.json>` (Anchor 0.30+), then pass the converted file";
|
|
316
|
+
/** Whether `idl` is in the format Anchor wrote before 0.30: `isMut` / `isSigner` accounts, or a name and version at the top and no discriminators. */
|
|
317
|
+
export function isLegacyAnchorIdl(idl) {
|
|
318
|
+
if (typeof idl !== "object" || idl === null)
|
|
319
|
+
return false;
|
|
320
|
+
const o = idl;
|
|
321
|
+
const ixs = Array.isArray(o.instructions) ? o.instructions : [];
|
|
322
|
+
const obj = (x) => typeof x === "object" && x !== null;
|
|
323
|
+
const flagged = (items) => Array.isArray(items) && items.some((a) => obj(a) && ("isMut" in a || "isSigner" in a || flagged(a.accounts)));
|
|
324
|
+
if (ixs.some((ix) => obj(ix) && flagged(ix.accounts)))
|
|
325
|
+
return true;
|
|
326
|
+
return typeof o.name === "string" && typeof o.version === "string" && ixs.length > 0 && ixs.every((ix) => obj(ix) && ix.discriminator === undefined);
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Throws ClientIdlError unless `idl` is an Anchor 0.30+ / 1.x or TypeSOL IDL whose values are safe to paste into generated
|
|
330
|
+
* source: identifiers that are identifiers, base58 addresses, byte lists. `typesol client`, `typesol cpi` and `typesol port`
|
|
331
|
+
* all check an IDL this way first. `instructions: "required"` also refuses an IDL without any (nothing to generate).
|
|
332
|
+
*/
|
|
333
|
+
export function checkIdl(idl, opts = {}) {
|
|
334
|
+
if (typeof idl !== "object" || idl === null || Array.isArray(idl))
|
|
335
|
+
throw new ClientIdlError("not an Anchor IDL: expected a JSON object");
|
|
336
|
+
if (isLegacyAnchorIdl(idl))
|
|
337
|
+
throw new ClientIdlError(LEGACY_IDL);
|
|
338
|
+
const ixs = idl.instructions;
|
|
339
|
+
if (!Array.isArray(ixs))
|
|
340
|
+
throw new ClientIdlError("not an Anchor IDL: it has no `instructions` list");
|
|
341
|
+
if (opts.instructions === "required" && !ixs.length)
|
|
342
|
+
throw new ClientIdlError("the IDL has no instructions: nothing to generate");
|
|
343
|
+
validate(idl, opts.address ?? idl.address);
|
|
344
|
+
}
|
|
302
345
|
/** Throws ClientIdlError unless every value that reaches the generated source is well-formed. */
|
|
303
346
|
function validate(idl, programAddress) {
|
|
304
347
|
const fail = (what) => {
|
|
@@ -371,6 +414,8 @@ function validate(idl, programAddress) {
|
|
|
371
414
|
if (!Array.isArray(idl.instructions))
|
|
372
415
|
fail("no instructions list");
|
|
373
416
|
for (const ix of idl.instructions) {
|
|
417
|
+
if (typeof ix !== "object" || ix === null)
|
|
418
|
+
fail("an instruction is not an object");
|
|
374
419
|
name(ix.name, "instruction");
|
|
375
420
|
if (ix.discriminator === undefined)
|
|
376
421
|
fail(`instruction ${ix.name} has no discriminator: this looks like a pre-0.30 Anchor IDL (convert it with \`anchor idl convert\`)`);
|
|
@@ -379,6 +424,8 @@ function validate(idl, programAddress) {
|
|
|
379
424
|
if (!Array.isArray(items))
|
|
380
425
|
fail(`${where}: accounts must be a list`);
|
|
381
426
|
for (const a of items) {
|
|
427
|
+
if (typeof a !== "object" || a === null)
|
|
428
|
+
fail(`${where}: an account is not an object`);
|
|
382
429
|
name(a.name, where);
|
|
383
430
|
if (a.accounts) {
|
|
384
431
|
walk(a.accounts, `${where}.${a.name}`);
|
|
@@ -410,7 +457,11 @@ function validate(idl, programAddress) {
|
|
|
410
457
|
if (ix.returns !== undefined)
|
|
411
458
|
type(ix.returns, `instruction ${ix.name} return`);
|
|
412
459
|
}
|
|
460
|
+
if (idl.types !== undefined && !Array.isArray(idl.types))
|
|
461
|
+
fail("types must be a list");
|
|
413
462
|
for (const t of idl.types ?? []) {
|
|
463
|
+
if (typeof t !== "object" || t === null)
|
|
464
|
+
fail("a type definition is not an object");
|
|
414
465
|
name(t.name, "type");
|
|
415
466
|
if (typeof t.type !== "object" || t.type === null)
|
|
416
467
|
fail(`type ${t.name} has no definition`);
|
|
@@ -428,7 +479,11 @@ function validate(idl, programAddress) {
|
|
|
428
479
|
fail(`type ${t.name}: repr align ${JSON.stringify(align)} is not a power of two`);
|
|
429
480
|
}
|
|
430
481
|
fields(t.type.fields, `type ${t.name}`);
|
|
482
|
+
if (t.type.variants !== undefined && !Array.isArray(t.type.variants))
|
|
483
|
+
fail(`type ${t.name}: variants must be a list`);
|
|
431
484
|
for (const v of t.type.variants ?? []) {
|
|
485
|
+
if (typeof v !== "object" || v === null)
|
|
486
|
+
fail(`type ${t.name}: a variant is not an object`);
|
|
432
487
|
name(v.name, `type ${t.name} variant`);
|
|
433
488
|
fields(v.fields, `type ${t.name}.${v.name}`);
|
|
434
489
|
}
|
|
@@ -438,12 +493,21 @@ function validate(idl, programAddress) {
|
|
|
438
493
|
for (const [list, what] of [
|
|
439
494
|
[idl.accounts, "account"],
|
|
440
495
|
[idl.events, "event"],
|
|
441
|
-
])
|
|
496
|
+
]) {
|
|
497
|
+
if (list !== undefined && !Array.isArray(list))
|
|
498
|
+
fail(`${what}s must be a list`);
|
|
442
499
|
for (const a of list ?? []) {
|
|
500
|
+
if (typeof a !== "object" || a === null)
|
|
501
|
+
fail(`an ${what} entry is not an object`);
|
|
443
502
|
name(a.name, what);
|
|
444
503
|
byteList(a.discriminator, `${what} ${a.name}`);
|
|
445
504
|
}
|
|
505
|
+
}
|
|
506
|
+
if (idl.errors !== undefined && !Array.isArray(idl.errors))
|
|
507
|
+
fail("errors must be a list");
|
|
446
508
|
for (const e of idl.errors ?? []) {
|
|
509
|
+
if (typeof e !== "object" || e === null)
|
|
510
|
+
fail("an error entry is not an object");
|
|
447
511
|
if (!Number.isInteger(e.code) || e.code < 0 || e.code > 0xffffffff)
|
|
448
512
|
fail(`error code ${JSON.stringify(e.code)} is not a u32`);
|
|
449
513
|
name(e.name, "error");
|
|
@@ -597,8 +661,8 @@ export function generateClient(idl, opts = {}) {
|
|
|
597
661
|
}
|
|
598
662
|
}
|
|
599
663
|
function generate(idl, opts) {
|
|
664
|
+
checkIdl(idl, { address: opts.address });
|
|
600
665
|
const programAddress = opts.address ?? idl.address;
|
|
601
|
-
validate(idl, programAddress);
|
|
602
666
|
idl = monomorphize(idl);
|
|
603
667
|
if (!programAddress)
|
|
604
668
|
throw new ClientIdlError("the IDL has no program address; pass one");
|
|
@@ -705,8 +769,12 @@ function generate(idl, opts) {
|
|
|
705
769
|
return Number.isInteger(Number(t.array[1])) ? issue(t.array[0]) : "array lengths must be numbers (generic lengths are not supported)";
|
|
706
770
|
if (t.vec !== undefined)
|
|
707
771
|
return issue(t.vec);
|
|
708
|
-
if (t.option !== undefined)
|
|
772
|
+
if (t.option !== undefined) {
|
|
773
|
+
// Option<Option<T>> is held as `Option<T> | null` (kit's Option inside), so Some(None) is expressible; one level more is not.
|
|
774
|
+
if (nestedOption(t.option) && nestedOption(t.option.option))
|
|
775
|
+
return "Option<Option<Option<…>>> is not supported";
|
|
709
776
|
return issue(t.option);
|
|
777
|
+
}
|
|
710
778
|
if (t.coption !== undefined)
|
|
711
779
|
return issue(t.coption);
|
|
712
780
|
const n = definedName(t);
|
|
@@ -757,6 +825,9 @@ function generate(idl, opts) {
|
|
|
757
825
|
const tsName = (n) => tsNames.get(n);
|
|
758
826
|
const isU8 = (t) => t === "u8";
|
|
759
827
|
function tsType(t, dir) {
|
|
828
|
+
// Option<Option<T>>: null is None, kit's none() is Some(None), some(x) (or x) is Some(Some(x)).
|
|
829
|
+
if (typeof t === "object" && t.option !== undefined && nestedOption(t.option))
|
|
830
|
+
return `${dir === "in" ? "OptionOrNullable" : "Option"}<${tsType(t.option.option, dir)}> | null`;
|
|
760
831
|
if (typeof t === "string") {
|
|
761
832
|
if (t in INTS)
|
|
762
833
|
return INTS[t] >= 64 ? (dir === "in" ? "number | bigint" : "bigint") : "number";
|
|
@@ -795,8 +866,56 @@ function generate(idl, opts) {
|
|
|
795
866
|
let needsFixedVec = false;
|
|
796
867
|
let needsUnitEnum = false;
|
|
797
868
|
let needsCStruct = false;
|
|
869
|
+
let needsLazy = false;
|
|
870
|
+
let needsWideInt = false;
|
|
871
|
+
// Types that hold themselves (`Shape { Rec { kids: Vec<Shape> } }`): their codecs refer to each other lazily, or
|
|
872
|
+
// building one would build itself again without end.
|
|
873
|
+
const recursive = new Set();
|
|
874
|
+
{
|
|
875
|
+
const refs = (t, out) => {
|
|
876
|
+
if (t === undefined || t === null || typeof t === "string")
|
|
877
|
+
return;
|
|
878
|
+
if (t.array)
|
|
879
|
+
return refs(t.array[0], out);
|
|
880
|
+
for (const inner of [t.vec, t.option, t.coption])
|
|
881
|
+
if (inner !== undefined)
|
|
882
|
+
return refs(inner, out);
|
|
883
|
+
const n = definedName(t);
|
|
884
|
+
if (n !== undefined)
|
|
885
|
+
out.push(n);
|
|
886
|
+
};
|
|
887
|
+
const edges = new Map();
|
|
888
|
+
for (const d of defs.values()) {
|
|
889
|
+
const out = [];
|
|
890
|
+
for (const f of d.type.fields ?? [])
|
|
891
|
+
refs(isField(f) ? f.type : f, out);
|
|
892
|
+
for (const v of d.type.variants ?? [])
|
|
893
|
+
for (const f of v.fields ?? [])
|
|
894
|
+
refs(isField(f) ? f.type : f, out);
|
|
895
|
+
refs(d.type.alias, out);
|
|
896
|
+
edges.set(d.name, out);
|
|
897
|
+
}
|
|
898
|
+
for (const start of edges.keys()) {
|
|
899
|
+
const seen = new Set();
|
|
900
|
+
const stack = [...edges.get(start)];
|
|
901
|
+
while (stack.length) {
|
|
902
|
+
const n = stack.pop();
|
|
903
|
+
if (n === start) {
|
|
904
|
+
recursive.add(start);
|
|
905
|
+
break;
|
|
906
|
+
}
|
|
907
|
+
if (seen.has(n))
|
|
908
|
+
continue;
|
|
909
|
+
seen.add(n);
|
|
910
|
+
stack.push(...(edges.get(n) ?? []));
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
}
|
|
798
914
|
function codec(t) {
|
|
799
915
|
if (typeof t === "string") {
|
|
916
|
+
// kit has no 256-bit codecs: 32 bytes, little-endian, as Borsh (and Anchor) write them.
|
|
917
|
+
if (INTS[t] === 256)
|
|
918
|
+
return ((needsWideInt = true), `wideInt(${t === "i256"})`);
|
|
800
919
|
if (t in INTS || t in FLOATS) {
|
|
801
920
|
const fn = `get${t.toUpperCase()}Codec`;
|
|
802
921
|
use(fn);
|
|
@@ -821,6 +940,8 @@ function generate(idl, opts) {
|
|
|
821
940
|
return (use("addCodecSizePrefix", "getBytesCodec", "getU32Codec"), "addCodecSizePrefix(getBytesCodec(), getU32Codec())");
|
|
822
941
|
return (use("getArrayCodec"), `getArrayCodec(${codec(t.vec)})`);
|
|
823
942
|
}
|
|
943
|
+
if (t.option !== undefined && nestedOption(t.option))
|
|
944
|
+
return (use("getNullableCodec", "getOptionCodec"), `getNullableCodec(getOptionCodec(${codec(t.option.option)}))`);
|
|
824
945
|
if (t.option !== undefined)
|
|
825
946
|
return (use("getNullableCodec"), `getNullableCodec(${codec(t.option)})`);
|
|
826
947
|
if (t.coption !== undefined) {
|
|
@@ -850,6 +971,8 @@ function generate(idl, opts) {
|
|
|
850
971
|
}
|
|
851
972
|
if (s?.kind === "fenum")
|
|
852
973
|
return (use("fixCodecSize"), `fixCodecSize(get${tsName(s.base)}Codec(), ${s.size})`);
|
|
974
|
+
if (recursive.has(n))
|
|
975
|
+
return ((needsLazy = true), `lazyCodec(() => get${tsName(n)}Codec())`);
|
|
853
976
|
return `get${tsName(n)}Codec()`;
|
|
854
977
|
}
|
|
855
978
|
/** Byte size of a fixed-size IDL type (undefined when it varies). Memoized by type name, so shared types are sized once. */
|
|
@@ -1672,6 +1795,49 @@ function generate(idl, opts) {
|
|
|
1672
1795
|
` });`,
|
|
1673
1796
|
],
|
|
1674
1797
|
});
|
|
1798
|
+
if (needsWideInt)
|
|
1799
|
+
helperDefs.push({
|
|
1800
|
+
name: "wideInt",
|
|
1801
|
+
lines: [
|
|
1802
|
+
`/** A u256 (or, signed, an i256): 32 bytes, little-endian, two's complement. */`,
|
|
1803
|
+
`const wideInt = (signed: boolean): Codec<number | bigint, bigint> =>`,
|
|
1804
|
+
` createCodec<number | bigint, bigint>({`,
|
|
1805
|
+
` fixedSize: 32,`,
|
|
1806
|
+
` write: (value, bytes, offset) => {`,
|
|
1807
|
+
` let v = BigInt(value);`,
|
|
1808
|
+
` const [min, max] = signed ? [-(1n << 255n), (1n << 255n) - 1n] : [0n, (1n << 256n) - 1n];`,
|
|
1809
|
+
` if (v < min || v > max) throw new RangeError(String(value) + " does not fit in " + (signed ? "i256" : "u256"));`,
|
|
1810
|
+
` if (v < 0n) v += 1n << 256n;`,
|
|
1811
|
+
` for (let i = 0; i < 32; i++, v >>= 8n) bytes[offset + i] = Number(v & 0xffn);`,
|
|
1812
|
+
` return offset + 32;`,
|
|
1813
|
+
` },`,
|
|
1814
|
+
` read: (bytes, offset) => {`,
|
|
1815
|
+
` let v = 0n;`,
|
|
1816
|
+
` for (let i = 31; i >= 0; i--) v = (v << 8n) | BigInt(bytes[offset + i] ?? 0);`,
|
|
1817
|
+
` return [signed && v >> 255n ? v - (1n << 256n) : v, offset + 32];`,
|
|
1818
|
+
` },`,
|
|
1819
|
+
` });`,
|
|
1820
|
+
],
|
|
1821
|
+
});
|
|
1822
|
+
if (needsLazy)
|
|
1823
|
+
helperDefs.push({
|
|
1824
|
+
name: "lazyCodec",
|
|
1825
|
+
lines: [
|
|
1826
|
+
`/** A codec made on first use: a type that holds itself (through a Vec or an Option) refers to its own codec. */`,
|
|
1827
|
+
`const lazyCodec = <From, To extends From>(make: () => Codec<From, To>): Codec<From, To> => {`,
|
|
1828
|
+
` let inner: Codec<From, To> | undefined;`,
|
|
1829
|
+
` const get = () => (inner ??= make());`,
|
|
1830
|
+
` return createCodec<From, To>({`,
|
|
1831
|
+
` getSizeFromValue: (value) => {`,
|
|
1832
|
+
` const c = get();`,
|
|
1833
|
+
` return isFixedSize(c) ? c.fixedSize : c.getSizeFromValue(value);`,
|
|
1834
|
+
` },`,
|
|
1835
|
+
` write: (value, bytes, offset) => get().write(value, bytes, offset),`,
|
|
1836
|
+
` read: (bytes, offset) => get().read(bytes, offset),`,
|
|
1837
|
+
` });`,
|
|
1838
|
+
`};`,
|
|
1839
|
+
],
|
|
1840
|
+
});
|
|
1675
1841
|
if (needsUnitEnum)
|
|
1676
1842
|
helperDefs.push({
|
|
1677
1843
|
name: "unitEnum",
|
package/dist/tools/cpigen.d.ts
CHANGED
|
@@ -1,18 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* `typesol cpi <idl.json>`: TypeSOL helper functions that call another program's instructions,
|
|
3
|
-
* generated from its Anchor IDL (spec 0.1.0, as written by Anchor 0.30+ and by TypeSOL itself).
|
|
4
|
-
*
|
|
5
|
-
* Each instruction becomes
|
|
6
|
-
*
|
|
7
|
-
* export function vaultDeposit(program: Program<"…">, vault: Mut<AccountMeta>, owner: AccountMeta,
|
|
8
|
-
* amount: u64, seeds: SignerSeeds): void {
|
|
9
|
-
* invoke(program, [writable(vault), readonlySigner(owner)], [hex("f223c689…"), amount], seeds);
|
|
10
|
-
* }
|
|
11
|
-
*
|
|
12
|
-
* Call it with `signer([...])` for a PDA of the calling program that must sign, or `signer([])`.
|
|
13
|
-
* Argument types without a Borsh-identical TypeSOL type (strings or Options inside structs, data-carrying
|
|
14
|
-
* enums, nested Vecs, generics) are reported and the instruction is left out.
|
|
15
|
-
*/
|
|
16
1
|
type IdlType = string | {
|
|
17
2
|
vec?: IdlType;
|
|
18
3
|
option?: IdlType;
|
package/dist/tools/cpigen.js
CHANGED
|
@@ -12,7 +12,12 @@
|
|
|
12
12
|
* Call it with `signer([...])` for a PDA of the calling program that must sign, or `signer([])`.
|
|
13
13
|
* Argument types without a Borsh-identical TypeSOL type (strings or Options inside structs, data-carrying
|
|
14
14
|
* enums, nested Vecs, generics) are reported and the instruction is left out.
|
|
15
|
+
*
|
|
16
|
+
* The IDL is checked as `typesol client` checks it (checkIdl): names, addresses and byte lists reach the generated
|
|
17
|
+
* source only when well-formed, and text from the IDL (docs, the program's name) only inside comments, escaped.
|
|
15
18
|
*/
|
|
19
|
+
import { checkIdl, commentText, printable } from "./clientgen.js";
|
|
20
|
+
const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
16
21
|
const INTS = new Set(["u8", "u16", "u32", "u64", "u128", "i8", "i16", "i32", "i64", "i128"]);
|
|
17
22
|
const RESERVED = new Set("break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await program seeds".split(" "));
|
|
18
23
|
class Unsupported extends Error {
|
|
@@ -60,13 +65,16 @@ const camel = (s) => s.replace(/[_-]+([a-zA-Z0-9])/g, (_, c) => c.toUpperCase())
|
|
|
60
65
|
const pascal = (s) => camel(s).replace(/^[a-z]/, (c) => c.toUpperCase());
|
|
61
66
|
const safe = (s) => (RESERVED.has(s) ? `${s}_` : s);
|
|
62
67
|
export function generateCpi(idl, opts = {}) {
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
const address = opts.address ?? idl.address;
|
|
68
|
+
const address = opts.address ?? (typeof idl === "object" && idl !== null ? idl.address : undefined);
|
|
69
|
+
checkIdl(idl, { address, instructions: "required" });
|
|
66
70
|
if (!address)
|
|
67
71
|
throw new Error("the IDL has no program address; pass --address <base58>");
|
|
68
|
-
|
|
69
|
-
|
|
72
|
+
if (opts.prefix !== undefined && !IDENT.test(opts.prefix))
|
|
73
|
+
throw new Error("the prefix must be an identifier");
|
|
74
|
+
const rawName = idl.metadata?.name;
|
|
75
|
+
// The program's name in comments as written (escaped); in the helpers' names only when it is an identifier.
|
|
76
|
+
const programName = typeof rawName === "string" && rawName ? commentText(rawName) : "program";
|
|
77
|
+
const prefix = opts.prefix ?? (typeof rawName === "string" && IDENT.test(rawName) ? camel(rawName) : "program");
|
|
70
78
|
const typeDefs = new Map((idl.types ?? []).map((t) => [t.name, t]));
|
|
71
79
|
const typeImports = new Set(["Program", "SignerSeeds"]);
|
|
72
80
|
const valueImports = new Set(["invoke", "hex"]);
|
|
@@ -230,7 +238,8 @@ export function generateCpi(idl, opts = {}) {
|
|
|
230
238
|
}
|
|
231
239
|
const name = `${prefix}${pascal(ix.name)}`;
|
|
232
240
|
const disc = Buffer.from(ix.discriminator).toString("hex");
|
|
233
|
-
const
|
|
241
|
+
const docs = Array.isArray(ix.docs) ? ix.docs.filter((l) => typeof l === "string") : [];
|
|
242
|
+
const doc = [...docs, `${programName}.${ix.name} through CPI.`, ...notes].map((l) => ` * ${commentText(l)}`).join("\n");
|
|
234
243
|
functions.push([
|
|
235
244
|
`/**\n${doc}\n */`,
|
|
236
245
|
`export function ${name}(${params.join(", ")}): ${returns} {`,
|
|
@@ -243,13 +252,15 @@ export function generateCpi(idl, opts = {}) {
|
|
|
243
252
|
catch (e) {
|
|
244
253
|
if (!(e instanceof Unsupported))
|
|
245
254
|
throw e;
|
|
246
|
-
skipped.push({ instruction: ix.name, reason: e.message });
|
|
255
|
+
skipped.push({ instruction: ix.name, reason: printable(e.message) });
|
|
247
256
|
}
|
|
248
257
|
}
|
|
249
258
|
const imports = [...[...typeImports].sort().map((t) => `type ${t}`), ...[...valueImports].sort()];
|
|
250
259
|
const header = [
|
|
251
260
|
`// Generated by \`typesol cpi\` from the ${programName} IDL (${address}). Edit freely.`,
|
|
252
|
-
...(skipped.length
|
|
261
|
+
...(skipped.length
|
|
262
|
+
? [`// Left out (no Borsh-identical TypeSOL type): ${commentText(skipped.map((s) => `${s.instruction} (${s.reason})`).join("; "))}.`]
|
|
263
|
+
: []),
|
|
253
264
|
`import { ${imports.join(", ")} } from "typesol";`,
|
|
254
265
|
];
|
|
255
266
|
const body = [...[...declarations.values()].filter(Boolean), ...functions];
|
package/dist/tools/doctor.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
|
|
1
|
+
import type { Rpc, SolanaRpcApi } from "@solana/kit";
|
|
2
|
+
/** The Agave CLI release TypeSOL is tested with (its platform-tools are the tested ones). */
|
|
3
|
+
export declare const INSTALL_AGAVE: "sh -c \"$(curl -sSfL https://release.anza.xyz/v3.1.10/install)\"";
|
|
2
4
|
export interface Check {
|
|
3
5
|
ok: boolean;
|
|
4
6
|
/** A missing optional piece (the Solana CLI is only needed to deploy). */
|
|
@@ -9,6 +11,11 @@ export interface Check {
|
|
|
9
11
|
}
|
|
10
12
|
/** The platform-tools the compiler needs: found, or what to run. */
|
|
11
13
|
export declare function toolchainCheck(): Check;
|
|
14
|
+
/**
|
|
15
|
+
* Whether the active platform-tools are the ones TypeSOL is tested with. An untested one is a warning, or an error
|
|
16
|
+
* under TYPESOL_TOOLCHAIN=strict (as it is for a build then). Undefined when there are no platform-tools at all.
|
|
17
|
+
*/
|
|
18
|
+
export declare function testedToolchainCheck(): Check | undefined;
|
|
12
19
|
/** json_rpc_url / keypair_path from a Solana CLI config (the given file, or the CLI's default one). */
|
|
13
20
|
export declare function solanaConfig(file?: string): {
|
|
14
21
|
url?: string;
|
|
@@ -22,7 +29,15 @@ export declare function clusterUrl(url: string): string;
|
|
|
22
29
|
export declare function rpcHost(url: string): string;
|
|
23
30
|
export declare function rpc<T>(url: string, method: string, params?: unknown[]): Promise<T>;
|
|
24
31
|
/** fetch's "fetch failed" says little: the cause's code (ECONNREFUSED, ENOTFOUND, a timeout) says more. */
|
|
25
|
-
export declare const errText: (e: unknown) => string;
|
|
32
|
+
export declare const errText: (e: unknown, timeoutSeconds?: number) => string;
|
|
33
|
+
/** How long one RPC request of the kit-based commands may take: TYPESOL_RPC_TIMEOUT seconds, default 30. */
|
|
34
|
+
export declare function rpcTimeoutSeconds(): number;
|
|
35
|
+
/**
|
|
36
|
+
* A kit RPC client for `clone`, `client --address`, `verify` and `idl publish`: each request gives up after
|
|
37
|
+
* rpcTimeoutSeconds(), and a request that fails on the way names only the host and the cause, as `doctor` and
|
|
38
|
+
* `deploy` do (the URL can carry an API key).
|
|
39
|
+
*/
|
|
40
|
+
export declare function cliRpc(url: string): Promise<Rpc<SolanaRpcApi>>;
|
|
26
41
|
/**
|
|
27
42
|
* Before `solana program deploy`: the RPC answers, and the payer holds enough for the program's rent (a first deploy
|
|
28
43
|
* holds about twice the binary's rent while the buffer exists; an upgrade, the buffer's). Throws with what to do.
|
package/dist/tools/doctor.js
CHANGED
|
@@ -5,10 +5,11 @@ import { execFileSync } from "node:child_process";
|
|
|
5
5
|
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
6
6
|
import os from "node:os";
|
|
7
7
|
import path from "node:path";
|
|
8
|
-
import { findToolchain } from "../compiler/toolchain.js";
|
|
8
|
+
import { findToolchain, INSTALL_TESTED_TOOLCHAIN, shortClang, TESTED_TOOLCHAIN, toolchainInfo, toolchainStrict } from "../compiler/toolchain.js";
|
|
9
9
|
import { base58, readKeypair } from "../keys.js";
|
|
10
10
|
import { findWorkspace } from "../workspace.js";
|
|
11
|
-
|
|
11
|
+
/** The Agave CLI release TypeSOL is tested with (its platform-tools are the tested ones). */
|
|
12
|
+
export const INSTALL_AGAVE = INSTALL_TESTED_TOOLCHAIN[0];
|
|
12
13
|
const MIN_NODE = [22, 12];
|
|
13
14
|
/** The platform-tools the compiler needs: found, or what to run. */
|
|
14
15
|
export function toolchainCheck() {
|
|
@@ -34,6 +35,36 @@ export function toolchainCheck() {
|
|
|
34
35
|
};
|
|
35
36
|
}
|
|
36
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* Whether the active platform-tools are the ones TypeSOL is tested with. An untested one is a warning, or an error
|
|
40
|
+
* under TYPESOL_TOOLCHAIN=strict (as it is for a build then). Undefined when there are no platform-tools at all.
|
|
41
|
+
*/
|
|
42
|
+
export function testedToolchainCheck() {
|
|
43
|
+
let info;
|
|
44
|
+
try {
|
|
45
|
+
info = toolchainInfo();
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return undefined; // the platform-tools row says what is missing
|
|
49
|
+
}
|
|
50
|
+
const tested = `${shortClang(TESTED_TOOLCHAIN.clang)}, platform-tools ${TESTED_TOOLCHAIN.platformTools}`;
|
|
51
|
+
if (info.tested)
|
|
52
|
+
return { ok: true, what: "toolchain", detail: `tested: ${shortClang(info.clang)}, platform-tools ${info.platformTools ?? "unknown"}` };
|
|
53
|
+
let strict = true;
|
|
54
|
+
try {
|
|
55
|
+
strict = toolchainStrict();
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
/* a bad TYPESOL_TOOLCHAIN value fails the build itself; here it counts as strict */
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
ok: false,
|
|
62
|
+
optional: !strict,
|
|
63
|
+
what: "toolchain",
|
|
64
|
+
detail: `untested: ${shortClang(info.clang)}, platform-tools ${info.platformTools ?? "unknown"}; TypeSOL is tested with ${tested} (Agave ${TESTED_TOOLCHAIN.agave}): binaries from another toolchain are not covered by its tests${strict ? " (TYPESOL_TOOLCHAIN=strict refuses it)" : ""}`,
|
|
65
|
+
fix: [`${INSTALL_TESTED_TOOLCHAIN[1]} # the tested platform-tools`],
|
|
66
|
+
};
|
|
67
|
+
}
|
|
37
68
|
/** json_rpc_url / keypair_path from a Solana CLI config (the given file, or the CLI's default one). */
|
|
38
69
|
export function solanaConfig(file) {
|
|
39
70
|
const configPath = file ?? path.join(os.homedir(), ".config/solana/cli/config.yml");
|
|
@@ -91,10 +122,36 @@ export async function rpc(url, method, params = []) {
|
|
|
91
122
|
return body.result;
|
|
92
123
|
}
|
|
93
124
|
/** fetch's "fetch failed" says little: the cause's code (ECONNREFUSED, ENOTFOUND, a timeout) says more. */
|
|
94
|
-
export const errText = (e) => {
|
|
125
|
+
export const errText = (e, timeoutSeconds = 10) => {
|
|
95
126
|
const err = e;
|
|
96
|
-
return err.cause?.code ?? err.cause?.message ?? (err.name === "TimeoutError" ?
|
|
127
|
+
return err.cause?.code ?? err.cause?.message ?? (err.name === "TimeoutError" ? `no answer in ${timeoutSeconds} s` : err.message);
|
|
97
128
|
};
|
|
129
|
+
/** How long one RPC request of the kit-based commands may take: TYPESOL_RPC_TIMEOUT seconds, default 30. */
|
|
130
|
+
export function rpcTimeoutSeconds() {
|
|
131
|
+
const s = Number(process.env.TYPESOL_RPC_TIMEOUT);
|
|
132
|
+
return Number.isFinite(s) && s > 0 ? s : 30;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* A kit RPC client for `clone`, `client --address`, `verify` and `idl publish`: each request gives up after
|
|
136
|
+
* rpcTimeoutSeconds(), and a request that fails on the way names only the host and the cause, as `doctor` and
|
|
137
|
+
* `deploy` do (the URL can carry an API key).
|
|
138
|
+
*/
|
|
139
|
+
export async function cliRpc(url) {
|
|
140
|
+
const kit = await import("@solana/kit");
|
|
141
|
+
const host = rpcHost(url);
|
|
142
|
+
const seconds = rpcTimeoutSeconds();
|
|
143
|
+
const base = kit.createDefaultRpcTransport({ url });
|
|
144
|
+
const transport = (async (config) => {
|
|
145
|
+
const timeout = AbortSignal.timeout(seconds * 1000);
|
|
146
|
+
try {
|
|
147
|
+
return await base({ ...config, signal: config.signal ? AbortSignal.any([config.signal, timeout]) : timeout });
|
|
148
|
+
}
|
|
149
|
+
catch (e) {
|
|
150
|
+
throw new Error(`cannot reach ${host} (${errText(e, seconds)}): check --url, or json_rpc_url in the Solana CLI config`, { cause: e });
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
return kit.createSolanaRpcFromTransport(transport);
|
|
154
|
+
}
|
|
98
155
|
const sol = (lamports) => lamports === 0 ? "0 SOL" : lamports < 100_000 ? `${lamports} lamports` : `${(lamports / 1e9).toFixed(lamports < 1e7 ? 4 : 2)} SOL`;
|
|
99
156
|
/** A cost, rounded up so the advice is enough. */
|
|
100
157
|
const solUp = (lamports) => `${(Math.ceil(lamports / 1e7) / 100).toFixed(2)} SOL`;
|
|
@@ -144,6 +201,9 @@ export async function doctorChecks(opts) {
|
|
|
144
201
|
fix: nodeOk ? undefined : [`install Node.js ${MIN_NODE.join(".")} or later (https://nodejs.org)`],
|
|
145
202
|
});
|
|
146
203
|
checks.push(toolchainCheck());
|
|
204
|
+
const tested = testedToolchainCheck();
|
|
205
|
+
if (tested)
|
|
206
|
+
checks.push(tested);
|
|
147
207
|
let solanaVersion;
|
|
148
208
|
try {
|
|
149
209
|
solanaVersion = execFileSync("solana", ["--version"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] })
|