What is @coral-xyz/anchor?
@coral-xyz/anchor is a framework for Solana's Sealevel runtime providing several developer tools to build, deploy, and interact with smart contracts on the Solana blockchain. It simplifies the process of writing Solana programs by offering a set of Rust macros and a TypeScript client for interacting with these programs.
What are @coral-xyz/anchor's main functionalities?
Smart Contract Development
This code demonstrates how to set up a client to interact with a Solana smart contract using the @coral-xyz/anchor framework. It shows how to load the program's IDL, set up a provider, and call a function on the smart contract.
const anchor = require('@coral-xyz/anchor');
// Define the provider
const provider = anchor.AnchorProvider.env();
anchor.setProvider(provider);
// Load the IDL
const idl = JSON.parse(require('fs').readFileSync('./target/idl/my_program.json', 'utf8'));
// Address of the deployed program
const programId = new anchor.web3.PublicKey('YourProgramPublicKey');
// Generate the program client from IDL
const program = new anchor.Program(idl, programId);
// Interact with the program
async function main() {
// Call a function from the smart contract
await program.rpc.initialize();
}
main().catch(err => console.error(err));
Testing Smart Contracts
This code provides a basic test setup for a Solana smart contract using the @coral-xyz/anchor framework. It uses Mocha for testing and demonstrates how to initialize a program and assert the state of an account.
const anchor = require('@coral-xyz/anchor');
const assert = require('assert');
describe('my-program', () => {
// Configure the client to use the local cluster.
const provider = anchor.AnchorProvider.local();
anchor.setProvider(provider);
const program = anchor.workspace.MyProgram;
it('Initializes the account', async () => {
// Add your test here.
const tx = await program.rpc.initialize();
console.log('Transaction signature', tx);
// Fetch the account and assert its state
const account = await program.account.myAccount.fetch(provider.wallet.publicKey);
assert.ok(account.data.eq(new anchor.BN(0)));
});
});
Other packages similar to @coral-xyz/anchor
@solana/web3.js
@solana/web3.js is a JavaScript API for interacting with the Solana blockchain. While it provides lower-level access to Solana's features, it lacks the higher-level abstractions and developer tools that @coral-xyz/anchor offers, such as IDL generation and client-side program interaction.