Git Product home page Git Product logo

program-examples's Introduction

Program Examples

Onchain program examples for βš“ Anchor πŸ¦€ Native Rust, and 🐍 Python

This repo contains Solana onchain programs (referred to as 'Smart Contracts' in other blockchains).

Note

If you're new to Solana, you don't need to create your own programs to perform basic things like making accounts, creating tokens, sending tokens, or minting NFTs. These common tasks are handled with existing programs, for example the System Program (for making account or transferring SOL) or the token program (for creating tokens and NFTs). See the Solana Developer site to learn more.

Each folder includes examples for one or more of the following

  • anchor - Written using Anchor, the most popular framework for Solana Development, which uses Rust. Use anchor build && anchor deploy to build & deploy the program. Run anchor run test to test it.
  • native - Written using Solana's native Rust crates and vanilla Rust. Use cicd.sh to build & deploy the program. Run yarn run test to test it.
  • seahorse - Written using the Seahorse framework, which converts your Python code to Anchor Rust. Use seahorse build && anchor deploy to build & deploy the program. Run anchor run test to test it.

If a given example is missing, please send us a PR to add it! Our aim is to have every examples available in every option. We'd also love to see more programs involving staking, wrapped tokens, oracles, compression and VRF. Follow the contributing guidelines to keep things consistent.

Basics

Hello world

Hello World on Solana! A minimal program that logs a greeting.

anchor native seahorse

Account-data

Store and retrieve data using Solana accounts.

anchor native

Storing global state - Counter

Use a PDA to store global state, making a counter that increments when called.

anchor native seahorse

Saving per-user state - Favorites

Save and update per-user state on the blockchain, ensuring users can only update their own information.

anchor

Checking Instruction Accounts

Check that the accounts provided in incoming instructions meet particular criteria.

anchor native

Closing Accounts

Close an account and get the Lamports back.

anchor native

Creating Accounts

Make new accounts on the blockchain.

anchor native

Cross program invocations

Invoke an instruction handler from one onchain program in another onchain program.

anchor native

PDA rent-payer

Use a PDA to pay the rent for the creation of a new account.

anchor native

Processing instructions

Add parameters to an instruction handler and use them.

anchor native

Storing date in program derived addresses

Store and retrieve state in Solana.

anchor native

Handling accounts that expland in size

How to store state that changes size in Solana.

anchor native

Calculating account size to determine rent

Determine the necessary minimum rent by calculating an account's size.

anchor native

Laying out larger programs

Layout larger Solana onchain programs.

anchor native

Transferring SOL

Send SOL between two accounts.

anchor native seahorse

Tokens

Creating tokens

Create a token on Solana with a token symbol and icon.

anchor native

Minting NFTS

Mint an NFT from inside your own onchain program using the Token and Metaplex Token Metadata programs. Reminder: you don't need your own program just to mint an NFT, see the note at the top of this README.

anchor native

Minting a token from inside a program

Mint a Token from inside your own onchain program using the Token program. Reminder: you don't need your own program just to mint an NFT, see the note at the top of this README.

anchor native

Transferring Tokens

Transfer tokens between accounts

anchor native seahorse

Allowing users to swap digital assets - Escrow

Allow two users to swap digital assets with each other, each getting 100% of what the other has offered due to the power of decentralization!

anchor

Minting a token from inside a program with a PDA as the mint authority

Mint a Token from inside your own onchain program using the Token program. Reminder: you don't need your own program just to mint an NFT, see the note at the top of this README.

anchor native

Creating an Automated Market Maker

Create liquidity pools to allow trading of new digital assets and allows users that provide liquidity to be rewarded by creating an Automated Market Maker.

anchor

Token Extensions

Basics - create token mints, mint tokens, and transfer tokens with Token Extensions

Create token mints, mint tokens, and transferr tokens using Token Extensions.

anchor

Preventing CPIs with CPI guard

Enable CPI guard to prevents certain token action from occurring within CPI (Cross-Program Invocation).

anchor

Using default account state

Create new token accounts that are frozen by default.

anchor native

Grouping tokens

Create tokens that belong to larger groups of tokens using the Group Pointer extension.

anchor

Creating token accounts whose owner cannot be changed

Create tokens whose owning program cannot be changed.

anchor

Interest bearing tokens

Create tokens that show an 'interest' calculation.

anchor

Requiring transactions to include descriptive memos

Create tokens where transfers must have a memo describing the transaction attached.

anchor

Adding on-chain metadata to the token mint

Create tokens that store their onchain metadata inside the token mint, without needing to use or pay for additional programs.

anchor

Allow a designedated account to close a mint

Allow a designated account to close a Mint.

anchor native

Usng multiple token extensions

Use multiple Token Extensions at once.

native

Non-transferrable - create tokens that can't be transferred.

Create tokens that cannot be transferred.

anchor native

Permanent Delegate - Create tokens permanently under the control of a particular account

Create tokens that remain under the control of an account, even when transferred elsewhere.

anchor

Create tokens with a transfer-fee.

Create tokens with an inbuilt transfer fee.

anchor native

Compression

Cnft-burn

Burn compressed NFTs.

anchor

Cnft-vault

Store Metaplex compressed NFTs inside a PDA.

anchor

Cutils

Work with Metaplex compressed NFTs.

anchor

Oracles

pyth

Use a data source for offchain data (called an Oracle) to perform activities onchain.

anchor seahorse


program-examples's People

Contributors

0xpratik avatar acheroncrypto avatar aiyualive avatar ascorreia avatar beeman avatar buffalojoec avatar cdhiraj40 avatar dadepo avatar davirain-su avatar heyayushh avatar ksolana avatar lucasste avatar mikemaccana avatar ngundotra avatar nickfrosty avatar ohaddahan avatar shivamsspirit avatar valentinmadrid avatar woody4618 avatar zyjliu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

program-examples's Issues

Why token swap only works in devnet?

If update the anchor.toml to localnet

[programs.localnet]
swap_example = "C3ti6PFK6PoYShRFx1BNNTQU3qeY1iVwjwCA6SjJhiuW"

[provider]
cluster = "Localnet"
wallet = "~/.config/solana/id.json"


runing the test will fail

TypeError: Cannot read properties of undefined (reading 'programId')

why and how to modify it works in local net ?

Overflow issue in swap ?

Why does the token-swap use whole u64 amounts in the following I64F64 calculation - which in my view could lead to overflow issues. The maximum Integer part from I6F64 is 2^63 -1. In their deposit_liquidity.rs file they calculated liquidity like:

pub fn deposit_liquidity(
    ctx: Context<DepositLiquidity>,
    amount_a: u64,
    amount_b: u64,
) -> Result<()> {
...
    let mut liquidity = I64F64::from_num(amount_a)
            .checked_mul(I64F64::from_num(amount_b))
            .unwrap()
            .sqrt()
            .to_num::<u64>();

That means if for example amount_a and amount_b is give in lamports which is sol * 10^9 they could only provide the square root of (2^63 - 1) / 10^9 = 3 SOL into the contract on each side. Why not cut amount/10^9 before the calculations as I64F64 has its floating precision also set to 2^-64 . Meaning, the overflow issue isnt a problem if the arguments are lamports - great for precision. But why don't they convert and calculate in SOL / use U128F0 within the contract? Or am I misunderstanding something here ?

anchor test `basic/account-data` meet this problem

(node:28858) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
    1) Create the address info account
    2) Read the new account's data


  0 passing (81ms)
  2 failing

  1) Account Data!
       Create the address info account:
     Error: AnchorError caused by account: address_info. Error Code: AccountNotInitialized. Error Number: 3012. Error Message: The program expected this account to be already initialized.
      at Function.parse (node_modules/@project-serum/anchor/src/error.ts:167:14)
      at translateError (node_modules/@project-serum/anchor/src/error.ts:276:35)
      at MethodsBuilder.rpc [as _rpcFn] (node_modules/@project-serum/anchor/src/program/namespace/rpc.ts:35:29)
      at processTicksAndRejections (node:internal/process/task_queues:95:5)

  2) Account Data!
       Read the new account's data:
     Error: Account does not exist ESowwGuph5bQso9ycdi7R7hKNvirUpYErzfU19ATdZhb
      at AccountClient.fetch (node_modules/@project-serum/anchor/src/program/namespace/account.ts:154:13)
      at processTicksAndRejections (node:internal/process/task_queues:95:5)



error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Create account fails

Looks like after commit e76ac6c, running the test for create account now fails.

My guess is, this is due to the hardcoding of Au21huMZuDQrbzu2Ec5ohpW5CKRqhcGV6qLawfydStGs as program ID in the test.

Below is the error:

  Create a system account
    1) Create the account


  0 passing (103ms)
  1 failing

  1) Create a system account
       Create the account:
     Error: failed to send transaction: Transaction simulation failed: Attempt to load a program that does not exist
      at Connection.sendEncodedTransaction (node_modules/@solana/web3.js/src/connection.ts:4934:13)
      at processTicksAndRejections (node:internal/process/task_queues:96:5)
      at Connection.sendRawTransaction (node_modules/@solana/web3.js/src/connection.ts:4893:20)
      at Connection.sendTransaction (node_modules/@solana/web3.js/src/connection.ts:4881:12)
      at sendAndConfirmTransaction (node_modules/@solana/web3.js/src/utils/send-and-confirm-transaction.ts:31:21)

I can not run "favorites" example

When I run basics/favorites/anchor project, there is error like below.
Could you tell me how to fix this?
Thanks in advance

favorites
Balance: 500,000,000 SOL
1) Writes our favorites to the blockchain
Invalid arguments: favorites not provided.
2) Updates the favorites
3) Rejects transactions from unauthorized signers

0 passing (301ms)
3 failing

  1. favorites
    Writes our favorites to the blockchain:
    Error: Invalid arguments: favorites not provided.
    at /home/quan/workspace/favorites/node_modules/@coral-xyz/anchor/src/program/common.ts:50:15
    at Array.forEach ()
    at validateAccounts (node_modules/@coral-xyz/anchor/src/program/common.ts:45:14)
    at ix (node_modules/@coral-xyz/anchor/src/program/namespace/instruction.ts:44:23)
    at txFn (node_modules/@coral-xyz/anchor/src/program/namespace/transaction.ts:24:14)
    at MethodsBuilder.rpc [as _rpcFn] (node_modules/@coral-xyz/anchor/src/program/namespace/rpc.ts:21:18)
    at MethodsBuilder.rpc (node_modules/@coral-xyz/anchor/src/program/namespace/methods.ts:212:17)

  2. favorites
    Updates the favorites:
    Error: null
    at /home/quan/workspace/favorites/tests/favorites.ts:60:13
    at Generator.throw ()
    at rejected (tests/favorites.ts:29:65)

  3. favorites
    Rejects transactions from unauthorized signers:

    AssertionError: expected false to be true

    • expected - actual

    -false
    +true

    at /home/quan/workspace/favorites/tests/favorites.ts:75:14
    at Generator.throw ()
    at rejected (tests/favorites.ts:29:65)

Error: failed to send transaction: Transaction simulation failed: Error processing Instruction 0: Cross-program invocation with unauthorized signer or writable account

Hello there,
Please I have this bug i have been facing, i have tried everything but it’s not working
this is the raw error message
Error: Raw transaction 4n7GkQVEtedpvjMU27nnfhwxJhXh6xHxCG7VV8taVtdhvEyo7BfEdkctX84zx3CEvxxFCYCLEbPiFPKzB9AsEuXi failed ({"err":{"InstructionError":[0,"PrivilegeEscalation"]}})

Error: failed to send transaction: Transaction simulation failed: Error processing Instruction 0: Cross-program invocation with unauthorized signer or writable account

Please here is my code, i will really appreciate it of anyone can help

Screenshot 2023-09-07 at 14 54 10

And here is my test code below
Screenshot 2023-09-07 at 14 54 20
Screenshot 2023-09-07 at 14 54 31

Where can I ask questions about these examples?

Hi:

I am trying to understand the examples in this repo. While I have reasonable understanding of writing Solidity code for EVM targets, some of the code in the examples is hard for me to understand. For example, in this:

@program_id("F1ipperKF9EfD821ZbbYjS319LXYiBmjhzkkf5a26rC")
contract hello_solana {
    // The constructor is used to create a new account
    // Here we create a new account that stores no data and only prints messages to the program logs when the constructor is called.
    @payer(payer) // The "payer" pays for the account creation
    constructor() {
        // We get the program ID by calling 'this';
        address programId = address(this);

        // Print messages to the program logs
        print("Hello, Solana!");
        print("Our program's Program ID: {:}".format(programId));
    }
}

What is the meaning of @program_id and how is the value F1ipperKF9EfD821ZbbYjS319LXYiBmjhzkkf5a26rC generated or discovered?

Also, what is @payer(payer) about? I have not run across this before in typical Solidity programming for the EVM.

I know these are newbie questions, maybe not appropriate for this issue. If so, please might you be able to tell me where I can get some questions answered?

Thanks in advance!

Add CI/CD

It would be nice to have a setup where the example programs can be deployed and the client tests ran against them. I think it should be possible to set this up with github actions.

If this is considered worth having, then I will be happy to help setup.

Can't execute a Solana program compiled from Solidity code with Solang

Hi:

I am trying to exercise a Solana program I migrated from Solidity using Solang.

I keep getting this error:

Error: SendTransactionError: failed to send transaction: Transaction simulation failed: Error processing Instruction 0: invalid program argument
    at Connection.sendEncodedTransaction (/home/reselbob/Documents/solidity-to-solana/node_modules/@solana/web3.js/lib/index.cjs.js:9560:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Connection.sendRawTransaction (/home/reselbob/Documents/solidity-to-solana/node_modules/@solana/web3.js/lib/index.cjs.js:9526:20)
    at async Connection.sendTransaction (/home/reselbob/Documents/solidity-to-solana/node_modules/@solana/web3.js/lib/index.cjs.js:9517:12)
    at async sendAndConfirmTransaction (/home/reselbob/Documents/solidity-to-solana/node_modules/@solana/web3.js/lib/index.cjs.js:2145:21)
    at async callGetMessage (/home/reselbob/Documents/solidity-to-solana/scripts/SayHi.js:50:20) {
  logs: [
    'Program 5FWPj98F4TEfSvWxqYXQW4whdoLXTN2yeXfCJWfY7EjL invoke [1]',
    'Program 5FWPj98F4TEfSvWxqYXQW4whdoLXTN2yeXfCJWfY7EjL consumed 34 of 200000 compute units',
    'Program 5FWPj98F4TEfSvWxqYXQW4whdoLXTN2yeXfCJWfY7EjL failed: invalid program argument'
  ]
}

I demonstrate the issue in this 4 minute video.

For purposes of research, I am intentionally avoiding using Anchor.

Here is the Solidity code that I migrated.

Here is the client script I used to try to execute the program.

Here is the entire project on GitHub.

If the problem is due to some mistake on my part, in all sincerity I ask your forgiveness.

For what it's worth, this problem has been plaguing me for days.

Thanks in advance for any help and direction you can provide.

Error: program file does not exist: ./target/deploy/counter_solana_native.so

I'm trying to run the yarn test from counter/native directory.

$ pwd
~/program-examples/basics/counter/native

$ yarn test
Error: program file does not exist: ./target/deploy/counter_solana_native.so
Error: server closed unexpectedly
    at ChildProcess.onClose (program-examples/basics/counter/native/node_modules/start-server-and-test/src/index.js:80:14)
    at ChildProcess.emit (node:events:390:28)
    at maybeClose (node:internal/child_process:1064:16)
    at Process.ChildProcess._handle.onexit (node:internal/child_process:301:5)
error Command failed with exit code 1.

I think yarn should detect which directory the test is invoked from. There should be a way to know the project root and that should be prefixed to the target/deploy/counter_solana_native.so path.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.