@typesol/cli 0.31.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +10 -9
  3. package/dist/cli.js +50 -5
  4. package/dist/compiler/analyze.js +187 -42
  5. package/dist/compiler/emit/alias.js +5 -1
  6. package/dist/compiler/emit/base.d.ts +5 -0
  7. package/dist/compiler/emit/base.js +24 -6
  8. package/dist/compiler/emit/calls.d.ts +5 -1
  9. package/dist/compiler/emit/calls.js +109 -15
  10. package/dist/compiler/emit/cpi-core.d.ts +8 -0
  11. package/dist/compiler/emit/cpi-core.js +17 -2
  12. package/dist/compiler/emit/cpi.js +10 -4
  13. package/dist/compiler/emit/create.d.ts +2 -0
  14. package/dist/compiler/emit/create.js +56 -13
  15. package/dist/compiler/emit/expressions.js +16 -6
  16. package/dist/compiler/emit/function.d.ts +3 -1
  17. package/dist/compiler/emit/function.js +21 -12
  18. package/dist/compiler/emit/statements.js +53 -3
  19. package/dist/compiler/emit/storage.js +8 -8
  20. package/dist/compiler/emit/token.js +43 -0
  21. package/dist/compiler/idl.js +47 -6
  22. package/dist/compiler/model.d.ts +19 -1
  23. package/dist/templates.js +13 -36
  24. package/dist/testing.d.ts +30 -0
  25. package/dist/testing.js +85 -3
  26. package/dist/workspace.d.ts +16 -1
  27. package/dist/workspace.js +49 -5
  28. package/docs/audit.md +1 -1
  29. package/docs/case-study-escrow.md +3 -3
  30. package/docs/case-study-multisig.md +3 -3
  31. package/docs/case-study-raydium-cp-swap.md +51 -21
  32. package/docs/cli.md +5 -3
  33. package/docs/errors.md +3 -1
  34. package/docs/language.md +17 -5
  35. package/docs/migrate-from-anchor.md +6 -0
  36. package/docs/test-your-program.md +12 -3
  37. package/docs/testing.md +1 -1
  38. package/lib/typesol.d.ts +51 -15
  39. package/package.json +1 -1
  40. package/runtime/typesol_rt.h +85 -7
package/lib/typesol.d.ts CHANGED
@@ -29,6 +29,8 @@ export type i128 = bigint;
29
29
  export interface Pubkey {
30
30
  readonly __pubkey: unique symbol;
31
31
  equals(other: Pubkey): boolean;
32
+ /** Rust's order on the 32 bytes (lexicographic): -1, 0 or 1. `a.compare(b) < 0n` is Rust's `a < b`. */
33
+ compare(other: Pubkey): i64;
32
34
  }
33
35
 
34
36
  /**
@@ -394,6 +396,17 @@ export interface TokenMetadataProgram extends AccountMeta {
394
396
  export declare function masterEditionAddress(mint: Pubkey): Pubkey;
395
397
  /** The canonical program address of `seeds` under `program` (Rust `Pubkey::find_program_address(seeds, program).0`). */
396
398
  export declare function findProgramAddress(seeds: Seed[], program: Pubkey): Pubkey;
399
+ /** The bump of that canonical program address (`Pubkey::find_program_address(seeds, program).1`), to sign with it. */
400
+ export declare function findProgramAddressBump(seeds: Seed[], program: Pubkey): u8;
401
+ /** This program's address (`crate::ID`). */
402
+ export declare function programId(): Pubkey;
403
+ /**
404
+ * Anchor's `AccountLoader::load_init` on an account the instruction created itself (`systemProgram.createAccount`, or
405
+ * `allocate` + `assign` on a pre-funded address): it must be owned by this program (3007), writable (3006), hold the
406
+ * struct (3003) and have no discriminator yet (3000). The discriminator is written and the data is returned to fill.
407
+ * Takes a `Mut<AccountInfo>` parameter or a remaining account.
408
+ */
409
+ export declare function initAccount<T>(account: AccountMeta | RemainingAccount): T;
397
410
  /** The Metaplex metadata account address of a mint. */
398
411
  export declare function metadataAddress(mint: Pubkey): Pubkey;
399
412
 
@@ -456,8 +469,11 @@ export interface AccountMeta {
456
469
  */
457
470
  export declare function pubkey(base58: string): Pubkey;
458
471
 
459
- /** The account must be this exact address (Anchor `address = …`, error 2012): `Address<Mut<AccountInfo>, "4Nd1…">`. */
460
- export type Address<A, Base58 extends string> = A & { readonly __address?: Base58 };
472
+ /**
473
+ * The account must be this exact address (Anchor `address = …`, error 2012): `Address<Mut<AccountInfo>, "4Nd1…">`.
474
+ * A third argument fails with one of your errors instead (Anchor's `address = … @ ErrorCode.X`).
475
+ */
476
+ export type Address<A, Base58 extends string, E = never> = A & { readonly __address?: [Base58, E] };
461
477
 
462
478
  /**
463
479
  * Token constraints, checked before your code runs:
@@ -548,8 +564,11 @@ export interface AccountInfo extends AccountMeta {
548
564
  /** A program-owned account holding struct `T`. Owner and discriminator are checked. */
549
565
  export type Account<T> = Readonly<T> & AccountMeta;
550
566
 
551
- /** Like `Account<T>` but writable. Also usable as `Mut<Signer>`, `Mut<AccountInfo>`, `Mut<TokenAccount>`. */
552
- export type Mut<T> = T & AccountMeta;
567
+ /**
568
+ * Like `Account<T>` but writable. Also usable as `Mut<Signer>`, `Mut<AccountInfo>`, `Mut<TokenAccount>`. A second
569
+ * argument fails with one of your errors when the account is not writable (Anchor's `mut @ ErrorCode.X`; else 2000).
570
+ */
571
+ export type Mut<T, E = never> = T & AccountMeta;
553
572
 
554
573
  /** A PDA seed: a string, a Pubkey, an integer (at its width) or a unit enum value (one byte). */
555
574
  export type Seed = string | Pubkey | bigint | number;
@@ -575,7 +594,7 @@ export type InitIfNeeded<T> = T extends TokenAccount
575
594
  * associated token account when it does not exist yet, with `payer` funding rent; true when it created it now.
576
595
  * An existing account must be that ATA, of that mint and owner.
577
596
  */
578
- createIfNeeded(payer: Mut<Signer>): boolean;
597
+ createIfNeeded(payer: Mut<Signer>, tokenProgram?: TokenProgram | Token2022Program | TokenInterface): boolean;
579
598
  /**
580
599
  * Anchor `init_if_needed` + `token::…`: create it as `create(payer, seeds, mint, authority)` does unless it exists;
581
600
  * an existing one must be that PDA, a token account of `mint` owned by `authority`. True when it created it now.
@@ -634,8 +653,12 @@ export type InitIfNeeded<T> = T extends TokenAccount
634
653
  * ("@param" names a program parameter, or give a base58 address).
635
654
  * - `CloseTo<Mut<Vault>, "owner">`: close the account into `owner` when the instruction succeeds.
636
655
  * They nest: `CloseTo<HasOne<Mut<Vault>, "owner">, "owner">`.
656
+ *
657
+ * `HasOne`, `Address`, `Owner`, `Signed` and `Mut` take one of your errors as their last argument, as Anchor's
658
+ * `has_one = owner @ ErrorCode.NotOwner` does: `HasOne<Mut<Vault>, "owner", ErrorCode.NotOwner>` (for one field each
659
+ * its own error, nest them: `HasOne<HasOne<Mut<Vault>, "owner", E.A>, "admin", E.B>`).
637
660
  */
638
- export type HasOne<A, Field extends string> = A & { readonly __hasOne?: Field };
661
+ export type HasOne<A, Field extends string, E = never> = A & { readonly __hasOne?: [Field, E] };
639
662
  /**
640
663
  * Anchor's `token::mint = mintParam, token::authority = authorityParam, token::token_program = tokenProgramParam` on an
641
664
  * existing token account, naming the parameters (2014 / 2015 / 2021: owned by that token program); `never` leaves one out.
@@ -660,7 +683,7 @@ export type Dup<A> = A & { readonly __dup?: true };
660
683
  * The account must sign the transaction (Anchor's `signer` constraint on an account that is not a `Signer`; 2002), e.g.
661
684
  * `Signed<Zeroed<Multisig>>` for an account the client creates with a fresh keypair in the same transaction.
662
685
  */
663
- export type Signed<A> = A & { readonly __signed?: true };
686
+ export type Signed<A, E = never> = A & { readonly __signed?: E | true };
664
687
  /**
665
688
  * Anchor 1.0's `Migration<From, To>`: an existing `From` account (owner, discriminator and size checked) that this
666
689
  * instruction rewrites as `To` with `acct.migrate(payer, value)`, a top-level statement every path must reach. Read
@@ -681,8 +704,8 @@ export type Seeds<A, Names extends readonly string[], Bump extends string = neve
681
704
  /** The PDA's bump (Anchor `ctx.bumps.<account>`): the stored bump field when one is named, else the canonical bump found. */
682
705
  readonly pdaBump: u8;
683
706
  };
684
- /** The account's owner program must be this address (Anchor `owner = …`, 2004). */
685
- export type Owner<A, Base58 extends string> = A & { readonly __owner?: Base58 };
707
+ /** The account's owner program must be this address (Anchor `owner = …`, 2004; a third argument: one of your errors). */
708
+ export type Owner<A, Base58 extends string, E = never> = A & { readonly __owner?: [Base58, E] };
686
709
  /**
687
710
  * An optional account (Anchor `Option<Account<…>>`): the client passes this program's id in its slot to leave it out.
688
711
  * Same as `A | null`. Check `x !== null` before using it; its checks and constraints run only when it is passed.
@@ -1347,7 +1370,7 @@ export type Init<T> = T extends TokenAccount
1347
1370
  * In `Ata<Init<TokenAccount>, "owner", "mint">` (Anchor `init` + `associated_token`): create the associated token
1348
1371
  * account of those parameters, with `payer` funding rent. Fails if it already exists.
1349
1372
  */
1350
- create(payer: Mut<Signer>): void;
1373
+ create(payer: Mut<Signer>, tokenProgram?: TokenProgram | Token2022Program | TokenInterface): void;
1351
1374
  /**
1352
1375
  * Anchor `init` + `token::mint` / `token::authority`: create a token account of `mint` owned by `authority`, at the
1353
1376
  * PDA of `seeds` (or, with `null`, a new keypair account that signs), under the instruction's token program, with
@@ -1440,12 +1463,17 @@ export interface Mint extends AccountMeta {
1440
1463
  /** The System Program. Its address is checked. */
1441
1464
  export interface SystemProgram extends AccountMeta {
1442
1465
  readonly __system: void;
1443
- transfer(from: Mut<Signer>, to: AccountMeta, lamports: u64): void;
1466
+ /** `from` signs: a `Mut<Signer>`, or a system-owned PDA of this program (a SOL vault) with its `signerSeeds`. */
1467
+ transfer(from: AccountMeta, to: AccountMeta, lamports: u64, signerSeeds?: Seed[] | SignerSeeds): void;
1444
1468
  /**
1445
1469
  * Create `account` with `space` bytes owned by `owner`, funded by `payer`. The new account signs: a
1446
1470
  * `Mut<Signer>` keypair, or a PDA of this program when you pass its `signerSeeds` (with the bump).
1447
1471
  */
1448
1472
  createAccount(payer: Mut<Signer>, account: AccountMeta, lamports: u64, space: u64, owner: Pubkey, signerSeeds?: Seed[] | SignerSeeds): void;
1473
+ /** System Allocate: give `account` `space` bytes of data. It signs: a keypair, or a PDA of this program with `signerSeeds`. */
1474
+ allocate(account: AccountMeta, space: u64, signerSeeds?: Seed[] | SignerSeeds): void;
1475
+ /** System Assign: make `owner` the account's owner. It signs: a keypair, or a PDA of this program with `signerSeeds`. */
1476
+ assign(account: AccountMeta, owner: Pubkey, signerSeeds?: Seed[] | SignerSeeds): void;
1449
1477
  }
1450
1478
 
1451
1479
  /**
@@ -1463,6 +1491,10 @@ interface TokenOps {
1463
1491
  /** Let `delegate` move up to `amount` from `source`. */
1464
1492
  approve(source: TokenAccount, delegate: AccountMeta, owner: AccountMeta, amount: u64, signerSeeds?: Seed[] | SignerSeeds): void;
1465
1493
  revoke(source: TokenAccount, owner: AccountMeta, signerSeeds?: Seed[] | SignerSeeds): void;
1494
+ /** The checked forms read the decimals from `mint`; Token-2022 mints with some extensions require them. */
1495
+ approveChecked(source: TokenAccount, mint: Mint, delegate: AccountMeta, owner: AccountMeta, amount: u64, signerSeeds?: Seed[] | SignerSeeds): void;
1496
+ mintToChecked(mint: Mint, to: TokenAccount, authority: AccountMeta, amount: u64, signerSeeds?: Seed[] | SignerSeeds): void;
1497
+ burnChecked(from: TokenAccount, mint: Mint, authority: AccountMeta, amount: u64, signerSeeds?: Seed[] | SignerSeeds): void;
1466
1498
  /** Change or remove (null) an authority of a mint or token account: `AuthorityType.MintTokens`, …. */
1467
1499
  setAuthority(target: AccountMeta, currentAuthority: AccountMeta, authorityType: u8, newAuthority: Pubkey | null, signerSeeds?: Seed[] | SignerSeeds): void;
1468
1500
  freezeAccount(account: TokenAccount, mint: AccountMeta, freezeAuthority: AccountMeta, signerSeeds?: Seed[] | SignerSeeds): void;
@@ -1633,7 +1665,8 @@ export declare function invoke(
1633
1665
  program: Program<string> | UncheckedProgram | SystemProgram | TokenProgram | Token2022Program | TokenInterface | RemainingAccount,
1634
1666
  accounts: CpiAccount[],
1635
1667
  data: CpiData[],
1636
- signerSeeds?: Seed[] | SignerSeeds,
1668
+ /** One PDA's seeds (with its bump), or a list of them when several PDAs sign: `[["vault", key, b1], ["fees", b2]]`. */
1669
+ signerSeeds?: Seed[] | SignerSeeds | (Seed[] | SignerSeeds)[],
1637
1670
  ): void;
1638
1671
 
1639
1672
  /** One account of an instruction built at run time (Rust's `AccountMeta`): any struct with these three fields. */
@@ -1659,7 +1692,7 @@ export declare function invokeInstruction(
1659
1692
  accounts: IndexedList<InstructionAccountMeta>,
1660
1693
  data: IndexedList<u8>,
1661
1694
  infos: RemainingAccounts | RemainingSlice,
1662
- signerSeeds?: Seed[] | SignerSeeds,
1695
+ signerSeeds?: Seed[] | SignerSeeds | (Seed[] | SignerSeeds)[],
1663
1696
  ): void;
1664
1697
 
1665
1698
  /**
@@ -1770,9 +1803,12 @@ export declare function emit<T>(event: T): void;
1770
1803
 
1771
1804
  /**
1772
1805
  * Read the return data the last invoke() left behind, checking it came from `program`
1773
- * and has exactly the size of T: `const n = returnData<u64>(counterProgram)`.
1806
+ * and has exactly the size of T: `const n = returnData<u64>(counterProgram)`. A struct is bound to a local:
1807
+ * `const quote = returnData<Quote>(amm)`. A fixed layout of integers, booleans, Pubkeys, unit enums and arrays is its
1808
+ * own Borsh form; a struct with Options, strings or Vecs is declared `@layout borsh` and Borsh-decoded (5106 when the
1809
+ * bytes do not decode to exactly it).
1774
1810
  */
1775
- export declare function returnData<T extends bigint | boolean | Pubkey | Hash>(program: AccountMeta): T;
1811
+ export declare function returnData<T extends bigint | boolean | Pubkey | Hash | object>(program: AccountMeta): T;
1776
1812
 
1777
1813
  /**
1778
1814
  * Verify `account.key` is the PDA for `seeds` + `bump` under this program. Any bump that gives a PDA passes (Anchor's
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typesol/cli",
3
- "version": "0.31.0",
3
+ "version": "0.33.0",
4
4
  "description": "Compile a TypeScript-syntax language directly to Solana SBF programs.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -37,6 +37,7 @@
37
37
  #define TS_ERR_MINT_TOKEN_PROGRAM 2022 /* ConstraintMintTokenProgram */
38
38
  #define TS_ERR_DUPLICATE_MUT 2040 /* ConstraintDuplicateMutableAccount */
39
39
  #define TS_ERR_ALREADY_INITIALIZED 3000 /* AccountDiscriminatorAlreadySet */
40
+ #define TS_ERR_INIT_PAYER 4101 /* TryingToInitPayerAsProgramAccount */
40
41
  #define TS_ERR_DISCRIMINATOR 3002 /* AccountDiscriminatorMismatch */
41
42
  #define TS_ERR_ACCOUNT_TOO_SMALL 3003 /* AccountDidNotDeserialize */
42
43
  #define TS_ERR_DID_NOT_SERIALIZE 3004 /* AccountDidNotSerialize */
@@ -160,6 +161,31 @@ static inline __attribute__((always_inline)) bool ts_mul_overflow_u64(uint64_t a
160
161
  return __builtin_mul_overflow(a, b, out);
161
162
  }
162
163
 
164
+ /*
165
+ * u128 arithmetic: the 128-bit library routines (__muloti4, __udivti3) cost hundreds of CU on SBF. Values that fit in
166
+ * 64 bits (most amounts and rates) take the native 64-bit instructions instead; the results are the same.
167
+ */
168
+ static inline __attribute__((always_inline)) bool ts_mul_overflow_u128(unsigned __int128 a, unsigned __int128 b, unsigned __int128 *out) {
169
+ if (((a | b) >> 32) == 0) {
170
+ const uint64_t product = (uint64_t)a * (uint64_t)b; /* both below 2^32: the product fits in 64 bits */
171
+ *out = product;
172
+ return false;
173
+ }
174
+ if (((a | b) >> 64) == 0) {
175
+ *out = (unsigned __int128)(uint64_t)a * (uint64_t)b; /* below 2^128: cannot overflow */
176
+ return false;
177
+ }
178
+ return __builtin_mul_overflow(a, b, out);
179
+ }
180
+ static inline __attribute__((always_inline)) unsigned __int128 ts_div_u128(unsigned __int128 a, unsigned __int128 b) {
181
+ if (((a | b) >> 64) == 0) return (uint64_t)a / (uint64_t)b;
182
+ return a / b;
183
+ }
184
+ static inline __attribute__((always_inline)) unsigned __int128 ts_rem_u128(unsigned __int128 a, unsigned __int128 b) {
185
+ if (((a | b) >> 64) == 0) return (uint64_t)a % (uint64_t)b;
186
+ return a % b;
187
+ }
188
+
163
189
  /* ---- Well-known program ids --------------------------------------------- */
164
190
  static const SolPubkey TS_SYSTEM_PROGRAM_ID = {{0}};
165
191
  /* TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA */
@@ -687,6 +713,12 @@ static inline uint64_t ts_event_dispatch(TsParams *params) {
687
713
  return ts_check_event_authority(params->ka[0], params->program_id, &bump);
688
714
  }
689
715
 
716
+ /* The Clock sysvar into `clock` (an instruction keeps it: the Clock does not change within a transaction). */
717
+ static inline uint64_t ts_read_clock(uint64_t clock[5]) {
718
+ if (sol_get_clock_sysvar(clock) != SUCCESS) TS_FAIL(TS_ERR_SYSVAR, "TypeSOL: clock sysvar unavailable");
719
+ return SUCCESS;
720
+ }
721
+
690
722
  static inline uint64_t ts_now(int64_t *out) {
691
723
  /* Clock { slot, epoch_start_timestamp, epoch, leader_schedule_epoch, unix_timestamp } */
692
724
  uint64_t clock[5] = {0};
@@ -716,6 +748,23 @@ static inline uint64_t ts_init_zeroed(TsAccount *a, const uint8_t disc[8]) {
716
748
  return SUCCESS;
717
749
  }
718
750
 
751
+ /* initAccount<T>: Anchor's AccountLoader::load_init on an account the body created. */
752
+ static inline uint64_t ts_init_account(TsAccount *a, const SolPubkey *program_id, const uint8_t disc[8], uint64_t size) {
753
+ if (!ts_key_eq(&a->owner, program_id)) TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: account not owned by this program");
754
+ if (!a->is_writable) TS_FAIL(TS_ERR_NOT_WRITABLE, "TypeSOL: account is not writable");
755
+ if (a->data_len < 8 + size) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account data too small");
756
+ if (ts_ld64(a->data) != 0) TS_FAIL(TS_ERR_ALREADY_INITIALIZED, "TypeSOL: account already initialized");
757
+ ts_memcpy(a->data, disc, 8);
758
+ return SUCCESS;
759
+ }
760
+
761
+ /* Pubkey order: Rust's Ord on [u8; 32], lexicographic. */
762
+ static inline int64_t ts_key_cmp(const SolPubkey *a, const SolPubkey *b) {
763
+ for (int i = 0; i < 32; i++)
764
+ if (a->x[i] != b->x[i]) return a->x[i] < b->x[i] ? -1 : 1;
765
+ return 0;
766
+ }
767
+
719
768
  /* ---- PDA ----------------------------------------------------------------- */
720
769
  static inline uint64_t ts_require_pda(const TsAccount *a, const SolSignerSeed *seeds, int n,
721
770
  const SolPubkey *program_id) {
@@ -726,15 +775,22 @@ static inline uint64_t ts_require_pda(const TsAccount *a, const SolSignerSeed *s
726
775
  }
727
776
 
728
777
  /* ---- System program CPIs ------------------------------------------------- */
729
- static inline uint64_t ts_system_transfer(TsParams *params, TsAccount *from, TsAccount *to,
730
- uint64_t lamports) {
778
+ static inline uint64_t ts_system_transfer_signed(TsParams *params, TsAccount *from, TsAccount *to,
779
+ uint64_t lamports, const SolSignerSeed *seeds, int nseeds) {
731
780
  uint8_t data[12];
732
781
  uint32_t tag = 2;
733
782
  ts_memcpy(data, &tag, 4);
734
783
  ts_memcpy(data + 4, &lamports, 8);
735
784
  SolAccountMeta metas[2] = {{&from->key, true, true}, {&to->key, true, false}};
736
785
  SolInstruction ix = {(SolPubkey *)&TS_SYSTEM_PROGRAM_ID, metas, 2, data, sizeof(data)};
737
- return ts_invoke(params, &ix, NULL, 0);
786
+ if (nseeds == 0) return ts_invoke(params, &ix, NULL, 0);
787
+ SolSignerSeeds signer = {seeds, (uint64_t)nseeds};
788
+ return ts_invoke(params, &ix, &signer, 1);
789
+ }
790
+
791
+ static inline uint64_t ts_system_transfer(TsParams *params, TsAccount *from, TsAccount *to,
792
+ uint64_t lamports) {
793
+ return ts_system_transfer_signed(params, from, to, lamports, NULL, 0);
738
794
  }
739
795
 
740
796
  /*
@@ -749,8 +805,8 @@ static inline uint64_t ts_create_pda(TsParams *params, TsAccount *payer, TsAccou
749
805
  if (ts_find_pda(seeds, n, params->program_id, &derived, &bump) != SUCCESS ||
750
806
  !ts_key_eq(&derived, &acct->key))
751
807
  TS_FAIL(TS_ERR_SEEDS, "TypeSOL: PDA seeds do not match account");
752
- if (acct->data_len != 0 || !ts_key_eq(&acct->owner, &TS_SYSTEM_PROGRAM_ID))
753
- TS_FAIL(TS_ERR_ALREADY_INITIALIZED, "TypeSOL: account already exists");
808
+ /* No check that the address is free: as Anchor's init, the System Program refuses one in use (AccountAlreadyInUse,
809
+ custom 0), so a second create fails with the same error under both. */
754
810
  uint64_t lamports;
755
811
  TS_TRY(ts_minimum_balance(space, &lamports));
756
812
  seeds[n].addr = &bump;
@@ -769,6 +825,7 @@ static inline uint64_t ts_create_pda(TsParams *params, TsAccount *payer, TsAccou
769
825
  TS_TRY(ts_invoke(params, &ix, &signer, 1));
770
826
  } else {
771
827
  /* Someone pre-funded the address (CreateAccount would fail): top up, allocate, assign. */
828
+ if (ts_key_eq(&payer->key, &acct->key)) TS_FAIL(TS_ERR_INIT_PAYER, "TypeSOL: the payer cannot be the account created");
772
829
  if (acct->lamports < lamports) TS_TRY(ts_system_transfer(params, payer, acct, lamports - acct->lamports));
773
830
  uint8_t alloc[12];
774
831
  uint32_t alloc_tag = 8; /* Allocate */
@@ -808,8 +865,8 @@ static inline uint64_t ts_create_owned(TsParams *params, TsAccount *payer, TsAcc
808
865
  } else if (!acct->is_signer) {
809
866
  TS_FAIL(TS_ERR_NOT_SIGNER, "TypeSOL: a new keypair account must sign");
810
867
  }
811
- if (acct->data_len != 0 || !ts_key_eq(&acct->owner, &TS_SYSTEM_PROGRAM_ID))
812
- TS_FAIL(TS_ERR_ALREADY_INITIALIZED, "TypeSOL: account already exists");
868
+ /* No check that the address is free: as Anchor's init, the System Program refuses one in use (AccountAlreadyInUse,
869
+ custom 0), so a second create fails with the same error under both. */
813
870
  uint64_t lamports;
814
871
  TS_TRY(ts_minimum_balance(space, &lamports));
815
872
  SolSignerSeeds signer = {seeds, (uint64_t)(n + 1)};
@@ -826,6 +883,7 @@ static inline uint64_t ts_create_owned(TsParams *params, TsAccount *payer, TsAcc
826
883
  SolInstruction ix = {(SolPubkey *)&TS_SYSTEM_PROGRAM_ID, metas, 2, data, sizeof(data)};
827
884
  TS_TRY(ts_invoke(params, &ix, signers, nsigners));
828
885
  } else {
886
+ if (ts_key_eq(&payer->key, &acct->key)) TS_FAIL(TS_ERR_INIT_PAYER, "TypeSOL: the payer cannot be the account created");
829
887
  if (acct->lamports < lamports) TS_TRY(ts_system_transfer(params, payer, acct, lamports - acct->lamports));
830
888
  uint8_t alloc[12];
831
889
  uint32_t alloc_tag = 8; /* Allocate */
@@ -1191,6 +1249,15 @@ static inline uint64_t ts_return_data(const TsAccount *program, uint8_t *out, ui
1191
1249
  return SUCCESS;
1192
1250
  }
1193
1251
 
1252
+ /* Return data of exactly `size` bytes (a struct), copied straight into `out`. */
1253
+ static inline uint64_t ts_return_data_exact(const TsAccount *program, void *out, uint64_t size) {
1254
+ SolPubkey from;
1255
+ uint64_t n = sol_get_return_data((uint8_t *)out, size, &from);
1256
+ if (n != size || !ts_key_eq(&from, &program->key))
1257
+ TS_FAIL(TS_ERR_RETURN_DATA, "TypeSOL: missing or mismatched return data");
1258
+ return SUCCESS;
1259
+ }
1260
+
1194
1261
  /* ---- Crypto ---------------------------------------------------------------- */
1195
1262
  static const SolPubkey TS_ED25519_PROGRAM_ID = {{3,125,70,214,124,147,251,190,18,249,66,143,131,141,64,255,5,112,116,73,39,244,138,100,252,202,112,68,128,0,0,0}};
1196
1263
  static const SolPubkey TS_INSTRUCTIONS_SYSVAR_ID = {{6,167,213,23,24,123,209,102,53,218,212,4,85,253,194,192,193,36,198,143,33,86,117,165,219,186,203,95,8,0,0,0}};
@@ -1373,6 +1440,17 @@ static inline uint64_t ts_alloc(uint64_t n, uint8_t **out) {
1373
1440
  return SUCCESS;
1374
1441
  }
1375
1442
 
1443
+ /* Return data of any size (Borsh, at most 1024 bytes) into a heap buffer: its bytes and length. */
1444
+ static inline uint64_t ts_return_data_any(const TsAccount *program, uint8_t **out, uint64_t *len) {
1445
+ TS_TRY(ts_alloc(1024, out));
1446
+ SolPubkey from;
1447
+ uint64_t n = sol_get_return_data(*out, 1024, &from);
1448
+ if (n == 0 || n > 1024 || !ts_key_eq(&from, &program->key))
1449
+ TS_FAIL(TS_ERR_RETURN_DATA, "TypeSOL: missing or mismatched return data");
1450
+ *len = n;
1451
+ return SUCCESS;
1452
+ }
1453
+
1376
1454
  /* A heap Vec (a Vec<T> in a @layout borsh struct, held on the heap while the instruction runs): room for at least
1377
1455
  `need` elements of `size` bytes, doubling as Rust's Vec does. Elements move when it grows (the compiler refuses
1378
1456
  references into it that would outlive a push). Bounded by the heap; the account bounds it when it is packed (3004). */