-
Notifications
You must be signed in to change notification settings - Fork 370
/
Copy pathSolanaLib.ts
271 lines (219 loc) · 7.38 KB
/
SolanaLib.ts
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import {
Keypair,
Connection,
SendOptions,
VersionedTransaction,
PublicKey,
Transaction,
SystemProgram
} from '@solana/web3.js'
import bs58 from 'bs58'
import nacl from 'tweetnacl'
import {
getAssociatedTokenAddress,
createTransferInstruction,
TOKEN_PROGRAM_ID,
getOrCreateAssociatedTokenAccount
} from '@solana/spl-token'
import { SOLANA_MAINNET_CHAINS, SOLANA_TEST_CHAINS } from '@/data/SolanaData'
/**
* Types
*/
interface IInitArguments {
secretKey?: Uint8Array
}
/**
* Library
*/
export default class SolanaLib {
keypair: Keypair
constructor(keypair: Keypair) {
this.keypair = keypair
}
static init({ secretKey }: IInitArguments) {
const keypair = secretKey ? Keypair.fromSecretKey(secretKey) : Keypair.generate()
return new SolanaLib(keypair)
}
public async getAddress() {
return await this.keypair.publicKey.toBase58()
}
public getSecretKey() {
return this.keypair.secretKey.toString()
}
public async signMessage(
params: SolanaLib.SignMessage['params']
): Promise<SolanaLib.SignMessage['result']> {
const signature = nacl.sign.detached(bs58.decode(params.message), this.keypair.secretKey)
const bs58Signature = bs58.encode(signature)
return { signature: bs58Signature }
}
public async signTransaction(
params: SolanaLib.SignTransaction['params']
): Promise<SolanaLib.SignTransaction['result']> {
const transaction = this.deserialize(params.transaction)
this.sign(transaction)
return {
transaction: this.serialize(transaction),
signature: bs58.encode(transaction.signatures[0])
}
}
public async signAndSendTransaction(
params: SolanaLib.SignAndSendTransaction['params'],
chainId: string
): Promise<SolanaLib.SignAndSendTransaction['result']> {
const rpc = { ...SOLANA_TEST_CHAINS, ...SOLANA_MAINNET_CHAINS }[chainId]?.rpc
if (!rpc) {
throw new Error('There is no RPC URL for the provided chain')
}
const connection = new Connection(rpc)
const transaction = this.deserialize(params.transaction)
this.sign(transaction)
const signature = await connection.sendTransaction(transaction, {
maxRetries: 3,
preflightCommitment: 'recent',
...params.options
})
return { signature }
}
public async signAllTransactions(
params: SolanaLib.SignAllTransactions['params']
): Promise<SolanaLib.SignAllTransactions['result']> {
const signedTransactions = params.transactions.map(transaction => {
const transactionObj = this.deserialize(transaction)
this.sign(transactionObj)
return this.serialize(transactionObj)
})
return { transactions: signedTransactions }
}
private serialize(transaction: VersionedTransaction): string {
return Buffer.from(transaction.serialize()).toString('base64')
}
private deserialize(transaction: string): VersionedTransaction {
let bytes: Uint8Array
try {
bytes = bs58.decode(transaction)
} catch {
// Convert base64 to Uint8Array to avoid type issues
const buffer = Buffer.from(transaction, 'base64')
bytes = new Uint8Array(buffer)
}
return VersionedTransaction.deserialize(bytes)
}
private sign(transaction: VersionedTransaction) {
transaction.sign([this.keypair])
}
/**
* Send SOL to a recipient
* @param recipientAddress The recipient's address
* @param amount The amount to send in lamports (as a bigint)
* @returns The transaction signature/hash
*/
public async sendSol(recipientAddress: string, chainId: string, amount: bigint): Promise<string> {
console.log({ chainId })
const rpc = { ...SOLANA_TEST_CHAINS, ...SOLANA_MAINNET_CHAINS }[chainId]?.rpc
if (!rpc) {
throw new Error('There is no RPC URL for the provided chain')
}
const connection = new Connection(rpc, 'confirmed')
const fromPubkey = this.keypair.publicKey
const toPubkey = new PublicKey(recipientAddress)
// Create a simple SOL transfer transaction
const transaction = new Transaction().add(
SystemProgram.transfer({
fromPubkey,
toPubkey,
lamports: amount
})
)
// Get recent blockhash
const { blockhash } = await connection.getLatestBlockhash('confirmed')
transaction.recentBlockhash = blockhash
transaction.feePayer = fromPubkey
// Sign the transaction
transaction.sign(this.keypair)
// Send and confirm the transaction
const signature = await connection.sendRawTransaction(transaction.serialize())
// Wait for confirmation
await connection.confirmTransaction(signature, 'confirmed')
return signature
}
/**
* Send an SPL token to a recipient
* @param tokenAddress The token's mint address
* @param recipientAddress The recipient's address
* @param amount The amount to send (as a bigint)
* @returns The transaction signature/hash
*/
public async sendSplToken(
tokenAddress: string,
recipientAddress: string,
chainId: string,
amount: bigint
): Promise<string> {
const rpc = { ...SOLANA_TEST_CHAINS, ...SOLANA_MAINNET_CHAINS }[chainId]?.rpc
if (!rpc) {
throw new Error('There is no RPC URL for the provided chain')
}
const connection = new Connection(rpc, 'confirmed')
const fromWallet = this.keypair
const fromPubkey = fromWallet.publicKey
const toPubkey = new PublicKey(recipientAddress)
const mint = new PublicKey(tokenAddress)
// Get sender's token account (create if it doesn't exist)
const fromTokenAccount = await getOrCreateAssociatedTokenAccount(
connection,
fromWallet,
mint,
fromPubkey
)
// Check if recipient has a token account WITHOUT creating one
const associatedTokenAddress = await getAssociatedTokenAddress(mint, toPubkey)
const recipientTokenAccount = await connection.getAccountInfo(associatedTokenAddress)
if (!recipientTokenAccount) {
throw new Error(
`Recipient ${recipientAddress} doesn't have a token account for this SPL token. Transaction cannot proceed.`
)
}
// Create transfer instruction to existing account
const transferInstruction = createTransferInstruction(
fromTokenAccount.address,
associatedTokenAddress,
fromPubkey,
amount,
[],
TOKEN_PROGRAM_ID
)
// Create transaction and add the transfer instruction
const transaction = new Transaction().add(transferInstruction)
// Get recent blockhash
const { blockhash } = await connection.getLatestBlockhash('confirmed')
transaction.recentBlockhash = blockhash
transaction.feePayer = fromPubkey
// Sign the transaction
transaction.sign(fromWallet)
// Send and confirm the transaction
const signature = await connection.sendRawTransaction(transaction.serialize())
// Wait for confirmation
await connection.confirmTransaction(signature, 'confirmed')
return signature
}
}
export namespace SolanaLib {
type RPCRequest<Params, Result> = {
params: Params
result: Result
}
export type SignMessage = RPCRequest<{ message: string }, { signature: string }>
export type SignTransaction = RPCRequest<
{ transaction: string },
{ transaction: string; signature: string }
>
export type SignAndSendTransaction = RPCRequest<
{ transaction: string; options?: SendOptions },
{ signature: string }
>
export type SignAllTransactions = RPCRequest<
{ transactions: string[] },
{ transactions: string[] }
>
}