Develop and Deploy Programs Using Solana Playground

Introduction

Solana Playground is a web-based integrated development environment (IDE) designed to simplify the process of building, testing, and deploying smart contracts on the Solana blockchain. It has an easy-to-use interface and a variety of tools for both new and experienced developers, making it a versatile platform for blockchain development.

Solana

Key Features of Solana Playground

The following are the main features of Solana playground:-

  • Interactive Interface: Solana Playground offers an intuitive interface that allows developers to write, compile, and deploy smart contracts directly from their web browser. This eliminates the need for lengthy local setup and configuration, freeing developers to concentrate on building and testing code.
  • Preconfigured Environment: The playground provides a preconfigured development environment, removing the hassle of setting up the necessary tools and dependencies. This feature is particularly beneficial for newcomers who might find the initial setup process daunting.
  • Built-in Templates: Solana Playground includes several templates and examples to help developers get started quickly. These templates cover common use cases and standard contract structures, providing a solid foundation for new projects.
  • Real-time Collaboration: One of the standout features of Solana Playground is its support for real-time collaboration. Multiple users can work on the same project simultaneously, making it an excellent tool for team-based development. This feature enhances productivity and enables collective problem-solving.
  • Integration with Solana CLI: Solana Playground integrates with the Solana Command Line Interface (CLI) to allow sophisticated deployment and management functions. This enables developers to carry out difficult tasks and manage their projects more efficiently.

Advantages of Using Solana Playground

The following are the main advantages of Solana playground:-

  • Ease of Use: The playground's user-friendly interface makes it accessible for developers of all skill levels. Whether you're a seasoned developer or a newcomer to blockchain technology, Solana Playground offers an intuitive platform to work on.
  • Speed: Quick setup and immediate access to development tools speed up the development process. With everything ready to go from the start, you can focus on coding and testing rather than spending time on configuration.
  • Collaboration: Real-time collaboration features enhance teamwork and collective problem-solving. Working with others in real-time enables rapid feedback and faster project iteration.
  • Learning Resource: For beginners, Solana Playground is a wonderful educational tool. It provides a hands-on environment to understand Solana’s ecosystem and smart contract development, making the learning curve less steep.

Getting Started with Solana Playground

To begin using Solana Playground, visit the official Solana Playground website - beta.solpg.io/. The website looks like the following.

Solana Playground

Creating a New Project

Start a new project by selecting from available templates that are Native (Rust), Anchor (Rust), or Seahorse (Python), name your project, and click Create. Here, I am selecting Anchor(Rust), you can choose according to your needs.

Writing Smart Contracts

After creating a project, a program structure gets created which looks like the below-

Here, we have three main folders 'src', 'client', and 'tests'. In the 'src' folder, we have a file named 'lib.rs'. In the 'client' folder, we have a file named 'client.ts' and in the 'tests' folder, we have a file named 'anchor.test.ts'. Initially, we have a default program written in these files. We can modify these files according to our requirements. In this article, we will not be creating our program but rather using the default program to explore how the playground works.

In lib.rs-

use anchor_lang::prelude::*;

// This is your program's public key and it will update
// automatically when you build the project.
declare_id!("11111111111111111111111111111111");

#[program]
mod hello_anchor {
    use super::*;
    pub fn initialize(ctx: Context<Initialize>, data: u64) -> Result<()> {
        ctx.accounts.new_account.data = data;
        msg!("Changed data to: {}!", data); // Message will show up in the tx logs
        Ok(())
    }
}

#[derive(Accounts)]
pub struct Initialize<'info> {
    // We must specify the space in order to initialize an account.
    // First 8 bytes are default account discriminator,
    // next 8 bytes come from NewAccount.data being type u64.
    // (u64 = 64 bits unsigned integer = 8 bytes)
    #[account(init, payer = signer, space = 8 + 8)]
    pub new_account: Account<'info, NewAccount>,
    #[account(mut)]
    pub signer: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[account]
pub struct NewAccount {
    data: u64
}

This program demonstrates how to use the Anchor framework to create a new account and initialize it with a value on the Solana blockchain. It shows the basic structure of an Anchor program, including how to define instructions, specify account constraints, and log messages for transaction tracing. This example is a good starting point for understanding how to build more complex Solana programs using Anchor.

In Client.ts,

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

In the above file, we have a typescript file that logs my address and my balance.

In anchor.tests.rs

// No imports needed: web3, anchor, pg and more are globally available
describe("Test", () => {
  it("initialize", async () => {
    // Generate keypair for the new account
    const newAccountKp = new web3.Keypair();

    // Send transaction
    const data = new BN(42);
    const txHash = await pg.program.methods
      .initialize(data)
      .accounts({
        newAccount: newAccountKp.publicKey,
        signer: pg.wallet.publicKey,
        systemProgram: web3.SystemProgram.programId,
      })
      .signers([newAccountKp])
      .rpc();
    console.log(`Use 'solana confirm -v ${txHash}' to see the logs`);

    // Confirm transaction
    await pg.connection.confirmTransaction(txHash);

    // Fetch the created account
    const newAccount = await pg.program.account.newAccount.fetch(
      newAccountKp.publicKey
    );

    console.log("On-chain data is:", newAccount.data.toString());

    // Check whether the data on-chain is equal to local 'data'
    assert(data.eq(newAccount.data));
  });
});

In the above code, we have a test case for a Solana program using the Anchor framework. It initializes a new account with a value of `42`, sends the transaction, and confirms it. After fetching the account data from the blockchain, it checks if the on-chain data matches the expected value. Finally, it asserts that the stored data is correct, ensuring the smart contract functions as intended.

Building the program in the playground

To build this program, click the second option from the left navbar. Here, we have the Build button in the Explorer. Click on build to build your program, if there are no errors in your program, your program will build successfully.

Build and Deploy

Here, we have successfully built our program. Here, if you notice, our program public key is updated as we build the program.

Deploying to the Solana Network using the playground

Once our program is successfully built, we can deploy it to the Solana devnet, testnet, or mainnet.

To deploy the program, click on the Deploy button. After a while, you'll notice that your program has been deployed, and a few SOLs have deducted your balance. This deduction is the cost of program deployment.

Once the program is deployed on the chain, you will have a button to upgrade. This is used when you want to update or upgrade the program after the deployment. You can make changes and click on Upgrade to update the on-chain program.

Testing the program using the playground

Now, we can test this on-chain program, by clicking on the third option from the left navbar. Here, we have the necessary data for the testing. Before testing, we will need the values for Args, Accounts, etc. we can either fill it up by ourselves or we can click on the Fill button. the values will be automatically filled and we are ready to test our program.

Now, click the Test button, and test cases written in the anchor.test.ts file will be executed. If the test cases pass successfully, the playground terminal will look like the below.

If any test case fails during this, the playground terminal will show the error related to the failed test case.

If you click on Accounts and then click the Fetch All button, you will have the account generated with the same data value we provided in our test.

Now, we have successfully developed, deployed, and tested the program using the Solana playground. Similarly, you can use the playground to create programs according to your requirements without using the IDEs.

Conclusion

Solana Playground is a powerful tool that simplifies the development and deployment of smart contracts on the Solana blockchain. It provides a comprehensive suite of features and a user-friendly interface, it empowers developers to build, test, and deploy blockchain applications efficiently. Whether you are a novice exploring blockchain technology or an experienced developer working on complex projects, Solana Playground offers the resources and tools to support your development journey.

By leveraging Solana Playground, you can accelerate your development process, collaborate effectively with your team, and deploy high-quality smart contracts on one of the fastest-growing blockchain platforms.


Similar Articles