-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
256 lines (242 loc) · 10.8 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
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
import * as anchor from "@project-serum/anchor";
import { Connection, Keypair, PublicKey, ConnectionConfig, Commitment } from "@solana/web3.js";
import Context from "./types/context";
import { OPTIFI_EXCHANGE_ID, SolanaEndpoint } from "./constants";
import { isWalletProvider, readJsonFile } from './utils/generic';
import { OptifiExchangeIDL } from './types/optifi-exchange-types';
import optifiExchange from './idl/optifi_exchange.json';
import { MathWallet, SlopeWallet, SolongWallet, SolWindow, WalletProvider } from './types/solanaTypes';
import WalletType from "./types/walletType";
//instructions
import deposit from './instructions/deposit';
import withdraw from './instructions/withdraw';
import initialize from './instructions/initialize';
import initializeUserAccount from './instructions/initializeUserAccount';
import initializeSerumMarket from './instructions/initializeSerumMarket';
import NodeWallet from "@project-serum/anchor/dist/cjs/nodewallet";
require('dotenv').config();
interface WalletContext {
walletType: WalletType,
anchorWallet: anchor.Wallet
}
/**
* On the frontend, resolve an injected wallet from the window.solana object
*
* @param wallet The wallet provider already resolved
*/
function getWalletWrapper(wallet: WalletProvider): Promise<WalletContext> {
return new Promise((resolve, reject) => {
let walletType: WalletType;
// Cast solana injected window type
const solWindow = window as unknown as SolWindow;
let walletWrapper: anchor.Wallet | SolongWallet | MathWallet | SlopeWallet = solWindow.solana as unknown as anchor.Wallet;
// Wallet adapter or injected wallet setup
if (wallet.name === 'Slope' && !!solWindow.Slope) {
walletType = WalletType.Slope;
walletWrapper = new solWindow.Slope() as unknown as SlopeWallet;
walletWrapper.connect().then(({ data }) => {
if (data.publicKey) {
// @ts-ignore
(walletWrapper as SlopeWallet).publicKey = new anchor.web3.PublicKey(data.publicKey);
}
// @ts-ignore
walletWrapper.on = (action: string, callback: any) => {
if (callback) callback()
};
resolve({
walletType: walletType,
anchorWallet: walletWrapper as unknown as anchor.Wallet
})
}).catch((err) => reject(err))
} else if (wallet.name === 'Solong' && solWindow.solong) {
walletType = WalletType.Solong;
walletWrapper = solWindow.solong as unknown as SolongWallet;
solWindow.solong.selectAccount().then((key) => {
(walletWrapper as SolongWallet).publicKey = new anchor.web3.PublicKey(key);
// @ts-ignore
walletWrapper.on = (action: string, callback: Function) => { if (callback) callback() };
// @ts-ignore
walletWrapper.connect = (action: string, callback: Function) => { if (callback) callback() };
resolve({
walletType: walletType,
anchorWallet: walletWrapper as unknown as anchor.Wallet
})
}).catch((err) => reject(err))
} else if (wallet.name === 'Math Wallet' && solWindow.solana?.isMathWallet) {
walletType = WalletType.Math;
walletWrapper = solWindow.solana as unknown as MathWallet;
solWindow.solana.getAccount().then((key) => {
(walletWrapper as MathWallet).publicKey = new anchor.web3.PublicKey(key);
// @ts-ignore
walletWrapper.on = (action: string, callback: any) => { if (callback) callback() };
// @ts-ignore
walletWrapper.connect = (action: string, callback: any) => { if (callback) callback() };
resolve({
walletType: walletType,
anchorWallet: walletWrapper as unknown as anchor.Wallet
})
})
}
else {
if (wallet.name === 'Phantom' && solWindow.solana?.isPhantom) {
walletType = WalletType.Phantom;
walletWrapper = solWindow.solana as unknown as anchor.Wallet;
} else if (wallet.name === 'Solflare' && solWindow.solflare?.isSolflare) {
walletType = WalletType.Solflare;
walletWrapper = solWindow.solflare as unknown as anchor.Wallet;
} else {
walletType = WalletType.Unknown;
console.error("Unsupported wallet provider ", wallet);
reject("Unsupported wallet provider");
}
resolve({
walletType: walletType,
anchorWallet: walletWrapper as unknown as anchor.Wallet
})
}
});
}
/**
* Initialize a context to use the SDK with, given a wallet and a program ID
*
* @param wallet The user's wallet, to transact with the system. Can either be a string, specifying a path to a wallet,
* or an already initialized Wallet Provider. If a wallet is not provided, will try to read one in from the path in
* the environment variable process.env.OPTIFI_WALLET
*
* @param optifiProgramId The ID of the on chain Optifi program. If not provided, will try to read in from
* process.env.OPTIFI_PROGRAM_ID
*
* @param customExchangeUUID Optionally supply a custom UUID for the exchange, instead of using the Optifi
* constant
*
* @param cluster The Solana cluster to connect to. If not provided, will try to read in from
* process.env.CLUSTER. Mainnet by default
*/
function initializeContext(wallet?: string | WalletProvider,
optifiProgramId?: string,
customExchangeUUID?: string,
endpoint?: SolanaEndpoint,
connectionConfig: ConnectionConfig = {
commitment: "recent",
disableRetryOnRateLimit: true,
confirmTransactionInitialTimeout: 50 * 1000,
}
): Promise<Context> {
if (endpoint == undefined) {
let cluster = process.env.CLUSTER!;
switch (cluster) {
case "mainnet":
endpoint = SolanaEndpoint.Mainnet;
break;
case "devnet":
endpoint = SolanaEndpoint.Devnet;
break;
default:
endpoint = SolanaEndpoint.Devnet;
break;
}
}
let uuid = customExchangeUUID || OPTIFI_EXCHANGE_ID[endpoint];
return new Promise((resolve, reject) => {
// If the wallet was a provider object, figure out it's type for later specifics of transaction signing,
// and build the anchor wallet object
if (wallet !== undefined && isWalletProvider(wallet)) {
getWalletWrapper(wallet).then((walletRes) => {
const connection = new Connection(endpoint!, connectionConfig);
const provider = new anchor.AnchorProvider(connection,
walletRes.anchorWallet,
anchor.AnchorProvider.defaultOptions());
const idl = optifiExchange as unknown as OptifiExchangeIDL;
const program = new anchor.Program(idl,
(optifiProgramId || (process.env.OPTIFI_PROGRAM_ID as string)),
provider,
new anchor.BorshCoder(idl)
)
resolve({
program: program,
walletType: walletRes.walletType,
provider: provider,
endpoint: endpoint!,
connection: connection,
exchangeUUID: uuid
})
}).catch((err) => reject(err))
// Otherwise, try to read in a keypair from an environment variable, or a specified string
} else {
let keypair: Keypair;
if (wallet === undefined) {
keypair = Keypair.fromSecretKey(new Uint8Array(readJsonFile<any>(process.env.OPTIFI_WALLET as string)))
} else {
// Initialize the wallet
// The wallet was provided as a path
keypair = Keypair.fromSecretKey(new Uint8Array(readJsonFile<any>(wallet)));
}
const idl = optifiExchange as unknown as OptifiExchangeIDL;
const connection = new Connection(endpoint!, connectionConfig);
const walletWrapper = new NodeWallet(keypair);
const provider = new anchor.AnchorProvider(connection, walletWrapper, anchor.AnchorProvider.defaultOptions());
const program = new anchor.Program(idl,
(optifiProgramId || (process.env.OPTIFI_PROGRAM_ID as string)),
provider,
new anchor.BorshCoder(idl)
)
resolve({
program: program,
provider: provider,
endpoint: endpoint!,
connection: connection,
walletType: WalletType.Keypair,
walletKeypair: keypair,
exchangeUUID: uuid
})
}
})
}
function initializeContextWithoutWallet(
optifiProgramId?: string,
customExchangeUUID?: string,
endpoint?: SolanaEndpoint,
connectionConfig: ConnectionConfig = {
commitment: "recent",
disableRetryOnRateLimit: true,
confirmTransactionInitialTimeout: 50 * 1000,
}
): Promise<Context> {
if (endpoint == undefined) {
let cluster = process.env.CLUSTER!;
switch (cluster) {
case "mainnet":
endpoint = SolanaEndpoint.Mainnet;
break;
case "devnet":
endpoint = SolanaEndpoint.Devnet;
break;
default:
endpoint = SolanaEndpoint.Devnet;
break;
}
}
let uuid = customExchangeUUID || OPTIFI_EXCHANGE_ID[endpoint];
return new Promise((resolve, reject) => {
const idl = optifiExchange as unknown as OptifiExchangeIDL;
const connection = new Connection(endpoint!, connectionConfig);
const keypair = Keypair.generate(); // use a temp key
const walletWrapper = new NodeWallet(keypair);
const provider = new anchor.AnchorProvider(connection, walletWrapper, anchor.AnchorProvider.defaultOptions());
const program = new anchor.Program(idl,
(optifiProgramId || (process.env.OPTIFI_PROGRAM_ID as string)),
provider,
new anchor.BorshCoder(idl)
)
resolve({
program: program,
provider: provider,
endpoint: endpoint!,
connection: connection,
walletType: WalletType.Keypair,
walletKeypair: keypair,
exchangeUUID: uuid
})
})
}
export { initializeContext, deposit, withdraw, initialize, initializeSerumMarket, initializeUserAccount, initializeContextWithoutWallet }