Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: update examples #16

Merged
merged 1 commit into from
Jul 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
180 changes: 12 additions & 168 deletions examples/express/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion examples/express/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"@solana/actions": "^1.1.1",
"@solana/actions": "^1.4.0",
"@solana/web3.js": "^1.94",
"cors": "^2.8.5",
"express": "^4.19.2"
Expand Down
83 changes: 50 additions & 33 deletions examples/express/server.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import express from 'express';
import cors from 'cors';
import {
Connection,
Keypair,
PublicKey,
SystemProgram,
Transaction,
clusterApiUrl,
LAMPORTS_PER_SOL
import express from "express";
import cors from "cors";
import {
Connection,
Keypair,
PublicKey,
SystemProgram,
Transaction,
clusterApiUrl,
LAMPORTS_PER_SOL,
} from "@solana/web3.js";
import {
ACTIONS_CORS_HEADERS_MIDDLEWARE,
createPostResponse,
} from "@solana/actions";


const DEFAULT_SOL_ADDRESS = Keypair.generate().publicKey;
const DEFAULT_SOL_AMOUNT = 1;
const connection = new Connection(clusterApiUrl("devnet"));
Expand All @@ -24,16 +24,12 @@ const BASE_URL = `http://localhost:${PORT}`;
// Express app setup
const app = express();
app.use(express.json());
app.use(cors({
origin: '*',
methods: ['GET', 'POST', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'Content-Encoding', 'Accept-Encoding'],
}));
app.use(cors(ACTIONS_CORS_HEADERS_MIDDLEWARE));

// Routes
app.get('/actions.json', getActionsJson);
app.get('/api/actions/transfer-sol', getTransferSol);
app.post('/api/actions/transfer-sol', postTransferSol);
app.get("/actions.json", getActionsJson);
app.get("/api/actions/transfer-sol", getTransferSol);
app.post("/api/actions/transfer-sol", postTransferSol);

// Route handlers
function getActionsJson(req, res) {
Expand Down Expand Up @@ -64,7 +60,11 @@ async function getTransferSol(req, res) {
label: "Send SOL",
href: `${baseHref}&amount={amount}`,
parameters: [
{ name: "amount", label: "Enter the amount of SOL to send", required: true },
{
name: "amount",
label: "Enter the amount of SOL to send",
required: true,
},
],
},
],
Expand All @@ -73,7 +73,9 @@ async function getTransferSol(req, res) {

res.json(payload);
} catch (err) {
handleError(res, err);
console.error(err);
// handleError(res, err);
res.status(500).json({ message: err?.message || err });
}
}

Expand All @@ -87,25 +89,40 @@ async function postTransferSol(req, res) {
}

const fromPubkey = new PublicKey(account);
const minimumBalance = await connection.getMinimumBalanceForRentExemption(0);

const minimumBalance = await connection.getMinimumBalanceForRentExemption(
0,
);

if (amount * LAMPORTS_PER_SOL < minimumBalance) {
throw new Error(`Account may not be rent exempt: ${toPubkey.toBase58()}`);
}

const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
// create an instruction to transfer native SOL from one wallet to another
const transferSolInstruction = SystemProgram.transfer({
fromPubkey: fromPubkey,
toPubkey: toPubkey,
lamports: amount * LAMPORTS_PER_SOL,
});

const { blockhash, lastValidBlockHeight } =
await connection.getLatestBlockhash();

// create a legacy transaction
const transaction = new Transaction({
feePayer: fromPubkey,
blockhash,
lastValidBlockHeight
}).add(
SystemProgram.transfer({
fromPubkey,
toPubkey,
lamports: amount * LAMPORTS_PER_SOL,
})
);
lastValidBlockHeight,
}).add(transferSolInstruction);

// versioned transactions are also supported
// const transaction = new VersionedTransaction(
// new TransactionMessage({
// payerKey: fromPubkey,
// recentBlockhash: blockhash,
// instructions: [transferSolInstruction],
// }).compileToV0Message(),
// // note: you can also use `compileToLegacyMessage`
// );

const payload = await createPostResponse({
fields: {
Expand Down Expand Up @@ -149,4 +166,4 @@ function validatedQueryParams(query) {
// Start server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
});
Loading