-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
200 lines (173 loc) · 5.25 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import express from 'express';
import {
Connection,
Keypair,
PublicKey,
SystemProgram,
Transaction,
} from '@solana/web3.js';
import { createPostResponse, actionCorsMiddleware } from '@solana/actions';
import { IDL } from './config/idl/lsd_program.js';
import { solanaPrograms, solanaRestEndpoint, PORT } from './config/index.js';
import { getSplTokenAccount } from './utils/solanaUtils.js';
import anchorPkg, { Wallet } from '@coral-xyz/anchor';
import {
createAssociatedTokenAccountInstruction,
getAssociatedTokenAddress,
TOKEN_PROGRAM_ID,
} from '@solana/spl-token';
import { StakeActions } from './config/actions.js';
const { BN, Program, AnchorProvider } = anchorPkg;
const DEFAULT_SOL_ADDRESS = Keypair.generate().publicKey;
const DEFAULT_SOL_AMOUNT = 1;
// Express app setup
const app = express();
app.use(express.json());
app.use(actionCorsMiddleware());
// Routes
app.get('/actions.json', getActionsJson);
app.get('/api/actions/stake', getStakeSol);
app.post('/api/actions/stake', postStakeSol);
// Route handlers
function getActionsJson(req, res) {
const payload = {
rules: [
{ pathPattern: '/*', apiPath: '/api/actions/*' },
{ pathPattern: '/api/actions/**', apiPath: '/api/actions/**' },
],
};
res.json(payload);
}
async function getStakeSol(req, res) {
try {
const baseHref = `http://${req.headers.host}/api/actions/stake`;
const actions = [];
for (let action of StakeActions) {
if (action.customAmount) {
actions.push({
label: action.label,
href: `${baseHref}?amount={amount}`,
parameters: [
{
name: 'amount',
label: action.placeholder || 'Enter the amount of SOL to stake',
required: true,
},
],
});
} else {
actions.push({
label: action.label,
href: `${baseHref}?amount=${action.amount}`,
});
}
}
const payload = {
title: 'Stake SOL to StaFi LSD',
icon: 'https://solana-actions.vercel.app/solana_devs.jpg',
description: 'Stake SOL to StaFi LSD',
label: 'Stake',
links: {
actions,
},
};
res.json(payload);
} catch (err) {
console.log(err);
res.status(500).json({ message: err?.message || err });
}
}
async function postStakeSol(req, res) {
try {
const { amount } = validatedQueryParams(req.query);
const { account } = req.body;
if (!account) {
throw new Error('Invalid "account" provided');
}
const fromPubkey = new PublicKey(account);
const connection = new Connection(solanaRestEndpoint);
const wallet = new Wallet(new Keypair());
const provider = new AnchorProvider(connection, wallet);
anchorPkg.setProvider(provider);
const lsdProgramPubKey = new PublicKey(solanaPrograms.lsdProgramId);
const stakeManagerPubKey = new PublicKey(
solanaPrograms.stakeManagerAccountAddress
);
const lsdTokenMintPubKey = new PublicKey(solanaPrograms.lsdTokenMint);
const [stakePoolPubKey] = PublicKey.findProgramAddressSync(
[stakeManagerPubKey.toBuffer(), Buffer.from('pool_seed')],
lsdProgramPubKey
);
const { blockhash, lastValidBlockHeight } =
await connection.getLatestBlockhash();
const transaction = new Transaction({
feePayer: fromPubkey,
blockhash,
lastValidBlockHeight,
});
let ata = await getAssociatedTokenAddress(lsdTokenMintPubKey, fromPubkey);
const userSplTokenAddress = await getSplTokenAccount(
connection,
account,
solanaPrograms.lsdTokenMint
);
if (!userSplTokenAddress) {
const ataInstruction = createAssociatedTokenAccountInstruction(
fromPubkey,
ata,
fromPubkey,
lsdTokenMintPubKey
);
transaction.add(ataInstruction);
}
const anchorProgram = new Program(IDL, lsdProgramPubKey);
const anchorInstruction = await anchorProgram.methods
.stake(new BN((Number(amount) * 1000000000).toFixed(0)))
.accounts({
stakeManager: stakeManagerPubKey,
stakePool: stakePoolPubKey,
from: fromPubkey,
lsdTokenMint: lsdTokenMintPubKey,
mintTo: ata,
systemProgram: SystemProgram.programId,
tokenProgram: TOKEN_PROGRAM_ID,
})
.instruction();
transaction.add(anchorInstruction);
transaction.rpc = solanaRestEndpoint;
const payload = await createPostResponse({
fields: {
transaction,
message: `Stake ${amount} SOL to StaFi`,
},
});
res.json(payload);
} catch (err) {
console.log(err);
res.status(400).json({ error: err.message || 'An unknown error occurred' });
}
}
function validatedQueryParams(query) {
let toPubkey = DEFAULT_SOL_ADDRESS;
let amount = DEFAULT_SOL_AMOUNT;
if (query.to) {
try {
toPubkey = new PublicKey(query.to);
} catch (err) {
throw new Error('Invalid input query parameter: to');
}
}
try {
if (query.amount) {
amount = parseFloat(query.amount);
}
if (amount <= 0) throw new Error('amount is too small');
} catch (err) {
throw new Error('Invalid input query parameter: amount');
}
return { amount, toPubkey };
}
// Start server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});