bg

How To Get Started With Solana Actions & Blinks

Updated at: September 20, 202411 Mins Read

Author: QuillAudits Team

What are Solana Actions?

Simply put, they're APIs that return transactions on the Solana blockchain. But there's more to it than that. These APIs are designed to be integrated into various contexts, from QR codes to widgets and websites. The magic of Actions is that they allow developers to bring the functionality of the Solana ecosystem directly to users, without the need to navigate away from their current environment.

Imagine you're browsing a website and you want to make a transaction. Normally, you'd have to open a separate wallet app, sign in, and complete the transaction there. With Solana Actions, you can preview, sign, and send transactions directly from the website. It's like having a personal assistant who handles all the nitty-gritty details while you enjoy the show.


Secure Your Solana Smart Contracts with QuillAudits

Ready to secure your Solana smart contracts? Take the first step towards a safer blockchain journey. Request an Audit with QuillAudits today & ensure your contracts are robust and secure!

Check Our Pricingarrow

Get Started with Creating Custom Solana Actions

To quickly get started with building custom Solana Actions, follow these steps:


1. Install the Solana Actions SDK

solana1

 

2. Set Up Your API Endpoints

  • Metadata Endpoint: Create an API endpoint for the GET request that provides metadata about your Action.
  • Transaction Endpoint: Set up an API endpoint that accepts POST requests and returns a signable transaction for the user.

 

3. Explore Example Actions

You can find the source code for an Action that performs a native SOL transfer here and other example Actions in this repository.

solana3

Source

 

Deploying Your Custom Solana Actions

When deploying your custom Solana Actions to production:

  1. actions.json File: Ensure your application includes a valid actions.json file at the root of your domain.
  2. Cross-Origin Headers: Make sure your application responds with the required Cross-Origin headers on all Action endpoints, including the actions.json file.
  3. Testing and Debugging: Use the Blinks Inspector to test and debug your blinks/actions.

For additional inspiration, explore the Awesome Blinks repository to see community-created Actions and find ideas for new ones.

 

The Lifecycle of a Solana Action: From URL to Transaction

Interacting with Solana Actions is like having a conversation with a well-mannered chatbot. Here’s how it works:


Lifecycle of a Solana Action

Source


  1. GET Request: The client (like a wallet or website) sends a GET request to the Action URL to fetch metadata, including the app's title, icon, and available actions.
  2. User Interaction: The client displays a UI for the user to choose an action (like clicking a button).
  3. POST Request: Once an action is selected, the client sends a POST request to get the transaction for the user to sign.
  4. Transaction Execution: The user's wallet facilitates signing the transaction, and it's sent to the blockchain for confirmation.

But wait, there's more! Actions can also support invalidation, meaning they can detect if an action is no longer valid. For example, if a voting window has closed, the GET request can return a message like "This proposal is no longer up for a vote," disabling the relevant buttons.

 

Demo Source code of a Solana Action


Demo Source code of a Solana Action

This code demonstrates how to use Solana Actions, a framework for creating interactive requests for signable transactions or messages on the Solana blockchain. The example showcases a web service that facilitates transferring SOL (Solana's native token) between wallets.

The code uses the @solana/actions package and Solana's web3.js library.

Imports and Constants

  1. Imports:
    • @solana/actions: Provides utilities for creating Action responses and handling CORS.
    • @solana/web3.js: Solana's client library for interacting with the blockchain, including creating transactions and querying the network.
    • Custom constants DEFAULT_SOL_ADDRESS and DEFAULT_SOL_AMOUNT for fallback values.
  2. Constants:

    • DEFAULT_SOL_ADDRESS: The default address to which SOL will be sent if none is specified.
    • DEFAULT_SOL_AMOUNT: The default amount of SOL to send if none is specified.

     

Handlers

GET Handler

Handles incoming GET requests to provide metadata and action links for the Solana Actions.

  • Function: GET
  • Input: req (Request object)
  • Output: Returns a JSON response with metadata and action links.

Process:

  1. Extracts the toPubkey (recipient's public key) from the URL's query parameters using validatedQueryParams.
  2. Constructs a base URL for the action endpoint, including the recipient's public key.
  3. Creates a payload (ActionGetResponse) containing:
    • title: The title of the action.
    • icon: The URL of an icon image.
    • description: A brief description of the action.
    • links.actions: An array of actions users can take, such as sending different amounts of SOL.
  4. Returns the payload as a JSON response with the appropriate CORS headers (ACTIONS_CORS_HEADERS).

 

OPTIONS Handler

Handles OPTIONS requests to support CORS preflight checks.

  • Function: OPTIONS
  • Behavior: Reuses the GET handler logic to ensure consistent CORS responses.

 

POST Handler

Handles POST requests to execute the SOL transfer action.

  • Function: POST
  • Input: req (Request object)
  • Output: Returns a JSON response with the transaction details or an error message.

Process:

  1. Extracts the amount and toPubkey from the URL's query parameters using validatedQueryParams.
  2. Parses the JSON body to get the user's account (public key).
  3. Validates the account and amount.
  4. Establishes a connection to the Solana network using Connection.
  5. Ensures the receiving account will be rent-exempt by checking the minimum balance required.
  6. Creates a transaction instruction to transfer the specified amount of SOL.
  7. Constructs a transaction object with the latest blockhash and block height.
  8. Generates a response (ActionPostResponse) containing the transaction details for the user to sign.
  9. Returns the response as a JSON object with CORS headers.

 

Utility Function: validatedQueryParams

  • Purpose: Validates and extracts query parameters from the URL.
  • Inputs:
    • requestUrl: The URL object containing query parameters.
  • Outputs: Returns an object with amount and toPubkey properties.

Process:

  1. Attempts to parse the to query parameter into a PublicKey object. Defaults to DEFAULT_SOL_ADDRESS if not provided.
  2. Parses the amount query parameter into a float. Defaults to DEFAULT_SOL_AMOUNT if not provided.
  3. Validates the amount to ensure it is greater than 0.

 

Error Handling

The code includes basic error handling, logging errors to the console and returning an appropriate response with a status code of 400 and a CORS header if an error occurs.

 

Beyond words we dedicate ourselves to pioneering the web3 industry towards a secure future

DSA MemberTS GovBWA LogoCoinweb Logo
Check Our Pricingarrow

Blinks: The Web3 Transformers

Now, let's talk about Blinks—short for blockchain links. These are special URLs that turn any Solana Action into a shareable, metadata-rich link. But Blinks are not just any links; they're like Swiss Army knives for Web3. They can be shared on websites, social media, or even in chat applications like Discord. When you click on a Blink, it can trigger a transaction preview in your wallet or expand into interactive buttons, depending on the platform.


blinks

Source

For instance, imagine you're on a Discord server, and someone shares a Blink. If the bot or client you're using supports Blinks, you could see an interactive set of buttons, allowing you to complete the transaction without leaving Discord. It’s like magic but with more zeros and ones.


Blink URL Specification

A Blink URL defines a client application that guides users through the entire process of executing an Action, including wallet signing.

https://example.domain/?action=<action_url>

For a client application to qualify as a blink, it must adhere to the following requirements:

  1. Action Query Parameter:
    • The blink URL must include an action query parameter.
    • The value of this parameter should be a URL-encoded Action URL. This ensures compatibility with other protocol parameters.
  2. URL Decoding and API Introspection:
    • The client application must URL-decode the action query parameter.
    • It should then introspect the Action API link provided in the decoded URL (see Action URL scheme).
  3. User Interface:
    • The client must render a comprehensive user interface that enables users to complete the full lifecycle of executing an Action, including signing with their wallet.

Note: Not all blink client applications (such as websites or dApps) are required to support every Action. Developers can choose which Actions to support within their blink interfaces.

 

Example

A valid blink URL with an Action value of solana-action:<https://actions.alice.com/donate> URL-encoded:

<https://example.domain/?action=solana-action%3Ahttps%3A%2F%2Factions.alice.com%2Fdonate>

 

Detecting Actions via Blinks

Blinks can be associated with Actions in three primary ways:

  1. Explicit Action URL Sharing:
    • Example: solana-action:<https://actions.alice.com/donate>
    • In this case, only clients that support the specified Action will render the blink. There won't be a fallback link preview or site for non-supporting clients.
       
  2. Website Link to Actions API:
    • A website can be linked to an Actions API via an actions.json file located at the domain root.
    • For instance, https://alice.com/actions.json might map the website URL https://alice.com/donate to the API URL https://actions.alice.com/donate, hosting Actions for donating to Alice.
       
  3. Embedding Action URL in an Interstitial Site:
    • Example: https://example.domain/?action=<action_url>
    • Interstitial sites understand how to parse the Action URL and render the appropriate interface.

Clients that support blinks should be able to recognize any of these formats and render an interface for users to execute the action directly within the client.

For clients that do not support blinks, there should be an underlying website as a fallback option, allowing the browser to serve as a universal fallback. If a user clicks anywhere within a client that is not an action button or text input field, they should be redirected to the underlying site.

 

Watch this video to get started on how to build Solana Actions

 

 

Action Identity & Verification on Solana

The concept of Action Identity is critical for attributing on-chain activities to specific services or Action Providers in a verifiable manner. This process involves creating a unique keypair known as the Action Identity, which is used to sign specially formatted messages included in transactions. These messages, known as Action Identifier Messages, are integral to the attribution process and help in identifying and verifying actions taken by a particular service on the Solana blockchain.

 

Action Identity Keypair

The Action Identity keypair consists of a public and private key. The public key serves as an identifier for the Action Provider, while the private key is used to sign messages. These messages, containing specific information, are included in transactions through the Memo instruction. The keypair itself does not sign the transaction, which enhances transaction deliverability when no other signatures are present in the transaction returned to the user.

 

Action Identifier Message Structure

The Action Identifier Message is a structured string included in a transaction via an SPL Memo instruction. The format is:

protocol:identity:reference:signature

  • protocol: The protocol being used, typically set to "solana-action" based on the URL scheme.

 

  • identity: The base58-encoded public key of the Action Identity keypair.

 

  • reference: A base58-encoded 32-byte array, potentially representing public keys or other identifiers.

 

  • signature: The base58-encoded signature created by the Action Identity keypair, signing the reference value.

This message helps in associating the transaction with an Action Provider. It's crucial to ensure that each reference value is unique and used only once across all transactions to maintain the integrity of the attribution process.

 

Verification Process

The verification of transactions associated with an Action Provider involves several steps:

  1. Transaction Retrieval: All transactions associated with the identity account are retrieved using the getSignaturesForAddress RPC method. This method returns all Memo data associated with the transactions, including multiple Memo instructions if present.
     
  2. Message Parsing and Verification: Each transaction's memo string is parsed to extract the Action Identifier Message. The signature within the message is verified against the reference value using the public key of the Action Identity keypair. If the signature is valid, the transaction can be attributed to the Action Provider.
     
  3. Reference Check: It is crucial to ensure that the transaction is the first on-chain occurrence of the reference value. If it is not, the transaction is considered invalid and cannot be attributed to the Action Provider.

This verification process is necessary because the identity is not required to sign the transaction, which means that any transaction could potentially include the identity as a non-signer, leading to inflated attribution and usage counts.

 

Key Considerations

  • The Action Identifier Message must be included in the Memo instruction with zero accounts provided to avoid requiring valid signers.
  • The identity and reference should be included as read-only, non-signer keys in a separate instruction from the Memo instruction.

 

Testing & Verification is a Must Because Safety First

Even in the world of permissionless protocols, safety is paramount. That’s where the Blinks Inspector tool comes into play. It allows developers to inspect, debug, and test their Blinks and Actions directly in their browser. Think of it as a stethoscope for your blockchain interactions, letting you listen to the heartbeat of your API requests and responses.

And if you're worried about security, Dialect's Actions Registry is here to help. This public registry lists verified Actions, adding an extra layer of trust. It’s like having a bouncer at a club, ensuring only the right people (or in this case, Actions) get in.

 

6+

Years of Expertise

$30B+

Secured in Digital Assets

1M+

Lines of Code

1K+

Projects

Ending Thoughts

Solana Actions and Blinks are not just about making transactions easier; they're about bringing Web3 to the masses. By simplifying the interaction process, these tools are paving the way for broader adoption of blockchain technology.

Before deploying any smart contract on Solana's mainnet, make sure to audit your code. Smart contract audits are essential for identifying potential vulnerabilities and ensuring the security of your application.

So whether you're a developer looking to integrate blockchain functionality into your app or a user wanting a smoother experience, Solana Actions and Blinks are here to save the day.

Just like Batman and Robin, they're making the world a better place, one transaction at a time.

 

Subscribe to our Newsletter

Your weekly dose of Web3 innovation and security, featuring blockchain updates, developer insights, curated knowledge, security resources, and hack alerts. Stay ahead in Web3!

Telegram