Search code examples
solanaanchor-solana

export solpg project locally but got error TS1378 running the client script due to top-level await


I converted & exported this solpg project https://beta.solpg.io/658d772ecffcf4b13384ceb6 to local. Note the project runs all fine on solpg, including running client.

After running anchor build locally, I run anchor run client trying to run the client.ts code. However this is what I get:

/Users/0xbe1/solana-programs/transfer_tokens/node_modules/ts-node/src/index.ts:261
    return new TSError(diagnosticText, diagnosticCodes)
           ^
TSError: ⨯ Unable to compile TypeScript:
client/client.ts(12,17): error TS1378: Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher.

Note this is my client.ts script

import * as anchor from "@coral-xyz/anchor";
import * as web3 from "@solana/web3.js";
import type { SolanaLamportTransfer } from "../target/types/solana_lamport_transfer";

// Configure the client to use the local cluster
anchor.setProvider(anchor.AnchorProvider.env());

const program = anchor.workspace.SolanaLamportTransfer as anchor.Program<SolanaLamportTransfer>;

// Client
console.log("My address:", program.provider.publicKey.toString());
const balance = await program.provider.connection.getBalance(program.provider.publicKey);
console.log(`My balance: ${balance / web3.LAMPORTS_PER_SOL} SOL`);

And here's my tsconfig.json

{
  "compilerOptions": {
    "types": ["mocha", "chai"],
    "typeRoots": ["./node_modules/@types"],
    "lib": ["es2015"],
    "module": "commonjs",
    "target": "es6",
    "esModuleInterop": true
  }
}

Ideally it should run well as in solpg.


Solution

  • Because solpg uses a different layout than Anchor framework, make sure you use the "Convert and export" option when exporting your project.

    To fix your issue, you can wrap client.ts code in a async function:

    (async () => {
       // Configure the client to use the local cluster
       anchor.setProvider(anchor.AnchorProvider.env());
       const program = anchor.workspace.HelloAnchor as anchor.Program<HelloAnchor>;
    
       // Client
       console.log("My address:", program.provider.publicKey.toString());
       const balance = await program.provider.connection.getBalance(program.provider.publicKey);
       console.log(`My balance: ${balance / web3.LAMPORTS_PER_SOL} SOL`);
    })();
    

    Note that anchor run client will by default run against a local cluster that you have to start manually with anchor localnet.

    You can also change the cluster using the --provider.cluster argument: anchor run client --provider.cluster https://api.mainnet-beta.solana.com.

    Hope this helps!