Skip to content

Commit

Permalink
Add blinks example (#69)
Browse files Browse the repository at this point in the history
* init blinker project

* add readme

* Update ActionUrlSearchForm.tsx

fix regex to support lulo

* Update useTransactionProcessor.ts

implement legacy/versioned tx handling
  • Loading branch information
amilz authored Jul 2, 2024
1 parent 86c514f commit d1195c5
Show file tree
Hide file tree
Showing 39 changed files with 19,054 additions and 0 deletions.
2 changes: 2 additions & 0 deletions sample-dapps/solana-action-blinker/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
QN_ENDPOINT=https://example.solana-mainnet.quiknode.pro/123456
NEXT_PUBLIC_CLUSTER=mainnet-beta # mainnet-beta | devnet | testnet | local
3 changes: 3 additions & 0 deletions sample-dapps/solana-action-blinker/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
36 changes: 36 additions & 0 deletions sample-dapps/solana-action-blinker/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
109 changes: 109 additions & 0 deletions sample-dapps/solana-action-blinker/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# QuickNode Solana Action Blinker

## Overview

This is a simple demo let's you create Solana Actions and will parse Solana action URLs to their respective actions.

![Preview](public/preview.png)

The demo uses [Next.js 14](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).

### Background

Solana Actions provide a standardized way to deliver signable transactions or messages from an application directly to a user.
Blinks are client apps that convert Solana Actions into shareable, metadata-rich UIs for interacting with and executing Actions.
For more information, check out our [Guide on Solana Actions](https://www.quicknode.com/guides/solana-development/solana-pay/actions-and-blinks/).

## Getting Started

### Install Dependencies

Open the project dictory:

```bash
cd sample-dapps/solana-action-blinker
```
Then, install the dependencies:

```bash
npm install
# or
yarn
# or
pnpm install
# or
bun install
```

### Set Environment Variables

- Rename `.env.example` to `.env.local` and update with your QuickNode Solana Node Endpoint.
- Make sure to update the cluster to ensure your transaction URLs point to the correct explorer (use only of the enum values provided in the `.env.example` file).

```env
QN_ENDPOINT=https://example.solana-mainnet.quiknode.pro/123456
NEXT_PUBLIC_CLUSTER=mainnet-beta # mainnet-beta | devnet | testnet | local
```

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

## Using the Dapp

1. Enter a [valid Solana Action URL](https://solana.com/docs/advanced/actions#detecting-actions-via-blinks) in the input field. You may copy and paste one of the example links on the homepage.
2. Click "Parse Action" to see the parsed action details.
3. You will see the parsed details of the action URL. To see and execute available actions, connect a wallet.

![Preview](public/parsed-jup.png)

4. Click any of the available actions to execute the action (you will need to sign the transaction when prompted by your wallet).
5. You may create additional actions by following the structure in `solana-action-blinker/app/api/actions`

### Architecture

```bash
src/
├── app/
│ ├── page.tsx # Main page for Blink
│ └── layout.tsx # layout for the page
│ └── api/
│ └── solana/
│ └── sendAndConfirm/route.ts # Send and Confirm Transaction
│ └── actions/
│ └── memo/route.ts # Creates a Memo Solana Action
│ └── donate/route.ts # Creates a Donate Solana Action
└── components/
│ ├── ActionComponents/ # includes components for parsing and executing Solana Actions
│ ├── Blink.tsx # Main component
│ ├── SolanaProviders.tsx # Wallet Adapter Context providers
│ └── [supporting components]
└── hooks/
│ ├── useActionFetch.ts # Fetches and parses Solana Actions from URLs
│ └── useTransactionProcessor.ts # Executes Solana Transactions
└── utils/ # includes various utility functions and constants

```

## Deploy on Vercel

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fquiknode-labs%2Fqn-guide-examples%2Fsample-dapps%2Fsolana-action-blinker&env=QN_ENDPOINT,NEXT_PUBLIC_CLUSTER&envDescription=Requires%20a%20Solana%20Endpoint&envLink=https%3A%2F%2Fdashboard.quicknode.com%2Fendpoints&project-name=solana-action-blinker&repository-name=solana-action-blinker&redirect-url=https%3A%2F%2Fdashboard.quicknode.com%2F&demo-title=Quick%20Actions%20Blinker&demo-description=A%20sample%20tool%20for%20creating%20%26%20parsing%20Solana%20Actions%20and%20Generating%20Blinks%20)

## Next.js Documentation

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
152 changes: 152 additions & 0 deletions sample-dapps/solana-action-blinker/app/api/actions/donate/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import {
ActionPostResponse,
ACTIONS_CORS_HEADERS,
createPostResponse,
ActionGetResponse,
ActionPostRequest,
} from "@solana/actions";
import {
LAMPORTS_PER_SOL,
PublicKey,
SystemProgram,
Transaction,
} from "@solana/web3.js";
import { initializeConnection, handleError } from "@/utils/solana";

const DEFAULT_SOL_AMOUNT = 1.0;
const DEFAULT_SOL_ADDRESS = new PublicKey("QN484oyeerMKQY2t9pEhT3XAjVpd1q4bF8y3Covobbn");

export const GET = async (req: Request) => {
try {
const requestUrl = new URL(req.url);
const { toPubkey } = validatedQueryParams(requestUrl);

const baseHref = new URL(
`/api/actions/donate?to=${toPubkey.toBase58()}`,
requestUrl.origin,
).toString();

const payload: ActionGetResponse = {
title: "Quick Actions Example - Donate SOL",
icon: new URL("/qn-pixel.png", new URL(req.url).origin).toString(),
description: "Donate SOL to another Solana wallet",
label: "Donate SOL", // this value will be ignored since `links.actions` exists
links: {
actions: [
{
label: "Send 1 SOL", // button text
href: `${baseHref}&amount=${"1"}`,
},
{
label: "Send 5 SOL", // button text
href: `${baseHref}&amount=${"5"}`,
},
{
label: "Send 10 SOL", // button text
href: `${baseHref}&amount=${"10"}`,
},
{
label: "Send SOL", // button text
href: `${baseHref}&amount={amount}`, // this href will have a text input
parameters: [
{
name: "amount", // parameter name in the `href` above
label: "Enter the amount of SOL to send", // placeholder of the text input
required: true,
},
],
},
],
},
};

return Response.json(payload, {
headers: ACTIONS_CORS_HEADERS,
});
} catch (err) {
return handleError(err);
}
};

// DO NOT FORGET TO INCLUDE THE `OPTIONS` HTTP METHOD
// THIS WILL ENSURE CORS WORKS FOR BLINKS
export const OPTIONS = GET;

export const POST = async (req: Request) => {
try {
const requestUrl = new URL(req.url);
const { amount, toPubkey } = validatedQueryParams(requestUrl);

const body: ActionPostRequest = await req.json();

// validate the client provided input
let account: PublicKey;
try {
account = new PublicKey(body.account);
} catch (err) {
return handleError('Invalid "account" provided');
}

const connection = initializeConnection();

const transaction = new Transaction();
transaction.feePayer = account;

transaction.add(
SystemProgram.transfer({
fromPubkey: account,
toPubkey: toPubkey,
lamports: amount * LAMPORTS_PER_SOL,
}),
);

transaction.feePayer = account;

transaction.recentBlockhash = (
await connection.getLatestBlockhash()
).blockhash;

const payload: ActionPostResponse = await createPostResponse({
fields: {
transaction,
message: `Send ${amount} SOL to ${toPubkey.toBase58()}`,
},
// note: no additional signers are needed
// signers: [],
});

return Response.json(payload, {
headers: ACTIONS_CORS_HEADERS,
});
} catch (err) {
handleError(err);
}
};

function validatedQueryParams(requestUrl: URL) {
let toPubkey: PublicKey = DEFAULT_SOL_ADDRESS;
let amount: number = DEFAULT_SOL_AMOUNT;

try {
if (requestUrl.searchParams.get("to")) {
toPubkey = new PublicKey(requestUrl.searchParams.get("to")!);
}
} catch (err) {
throw "Invalid input query parameter: to";
}

try {
if (requestUrl.searchParams.get("amount")) {
amount = parseFloat(requestUrl.searchParams.get("amount")!);
}

if (amount <= 0) throw "amount is too small";
} catch (err) {
throw "Invalid input query parameter: amount";
}

return {
amount,
toPubkey,
};
}
69 changes: 69 additions & 0 deletions sample-dapps/solana-action-blinker/app/api/actions/memo/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { initializeConnection, handleError } from "@/utils/solana";
import { ACTIONS_CORS_HEADERS, ActionGetResponse, ActionPostRequest, ActionPostResponse, MEMO_PROGRAM_ID, createPostResponse } from "@solana/actions";
import { ComputeBudgetProgram, PublicKey, Transaction, TransactionInstruction } from "@solana/web3.js";

export const GET = async (req: Request, res: Response) => {
const payload: ActionGetResponse = {
title: "Quick Actions Example - Simple On-chain Memo",
icon: new URL("/qn-pixel.png", new URL(req.url).origin).toString(),
description: "Send a message on-chain using a Memo",
label: "Send Memo",
};

return Response.json(payload, {
headers: ACTIONS_CORS_HEADERS,
});
}

// DO NOT FORGET TO INCLUDE THE `OPTIONS` HTTP METHOD
// THIS WILL ENSURE CORS WORKS FOR BLINKS
export const OPTIONS = GET;

export const POST = async (req: Request) => {
try {
const body: ActionPostRequest = await req.json();

let account: PublicKey;
try {
account = new PublicKey(body.account);
} catch (err) {
return handleError('Invalid "account" provided');
}

const connection = initializeConnection();

const transaction = new Transaction().add(
// note: `createPostResponse` requires at least 1 non-memo instruction
ComputeBudgetProgram.setComputeUnitPrice({
microLamports: 1000,
}),
new TransactionInstruction({
programId: new PublicKey(MEMO_PROGRAM_ID),
data: Buffer.from("Sup - this is a Quick Example of Solana Actions.", "utf8"),
keys: [],
}),
);

// set the end user as the fee payer
transaction.feePayer = account;

transaction.recentBlockhash = (
await connection.getLatestBlockhash()
).blockhash;

const payload: ActionPostResponse = await createPostResponse({
fields: {
transaction,
message: "A Quick Example memo transaction.",
},
// no additional signers are required for this transaction
// signers: [],
});

return Response.json(payload, {
headers: ACTIONS_CORS_HEADERS,
});
} catch (err) {
return handleError(err);
}
};
Loading

0 comments on commit d1195c5

Please sign in to comment.