-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
76 lines (65 loc) · 2.46 KB
/
index.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
import { Connection, sendAndConfirmTransaction, Signer, SystemProgram, Transaction, TransactionSignature } from '@solana/web3.js';
import { createCloseAccountInstruction, createSyncNativeInstruction, getOrCreateAssociatedTokenAccount, NATIVE_MINT } from "@solana/spl-token";
export async function wrapSol(
connection: Connection,
signer: Signer,
amount: number
): Promise<TransactionSignature> {
// wSol ATA
const wSolAta = await getOrCreateAssociatedTokenAccount(connection, signer, NATIVE_MINT, signer.publicKey);
// wrap Sol
let transaction = new Transaction().add(
// trasnfer SOL
SystemProgram.transfer({
fromPubkey: signer.publicKey,
toPubkey: wSolAta.address,
lamports: amount,
}),
// sync wrapped SOL balance
createSyncNativeInstruction(wSolAta.address)
);
// submit transaction
const txSignature = await sendAndConfirmTransaction(connection, transaction, [signer]);
// validate transaction was successful
try {
const latestBlockhash = await connection.getLatestBlockhash();
await connection.confirmTransaction({
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
signature: txSignature,
}, 'confirmed');
} catch (error) {
console.log(`Error wrapping sol: ${error}`);
};
return txSignature;
}
export async function unwrapSol(
connection: Connection,
signer: Signer,
): Promise<TransactionSignature> {
// wSol ATA
const wSolAta = await getOrCreateAssociatedTokenAccount(connection, signer, NATIVE_MINT, signer.publicKey);
// close wSol account instruction
const transaction = new Transaction;
transaction.add(
createCloseAccountInstruction(
wSolAta.address,
signer.publicKey,
signer.publicKey
)
);
// submit transaction
const txSignature = await sendAndConfirmTransaction(connection, transaction, [signer]);
// validate transaction was successful
try {
const latestBlockhash = await connection.getLatestBlockhash();
await connection.confirmTransaction({
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
signature: txSignature,
}, 'confirmed');
} catch (error) {
console.log(`Error unwrapping sol: ${error}`);
};
return txSignature;
}