-
Notifications
You must be signed in to change notification settings - Fork 19
/
sdk.ts
329 lines (276 loc) · 12.1 KB
/
sdk.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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import { BehaviorSubject } from 'rxjs';
import { State, StateService } from './state';
import {
EthereumProvider,
isWalletConnectProvider,
isWalletProvider,
WalletConnect2WalletProvider,
WalletProviderLike
} from './wallet';
import { Factory, PaymasterApi, SdkOptions } from './interfaces';
import { Network } from "./network";
import { BatchUserOpsRequest, Exception, getGasFee, onRampApiKey, openUrl, UserOpsRequest } from "./common";
import { BigNumber, BigNumberish, ethers, providers, TypedDataField } from 'ethers';
import { Networks, onRamperAllNetworks } from './network/constants';
import { UserOperationStruct } from './contracts/account-abstraction/contracts/core/BaseAccount';
import { EtherspotWalletAPI, HttpRpcClient, VerifyingPaymasterAPI } from './base';
import { TransactionDetailsForUserOp, TransactionGasInfoForUserOp } from './base/TransactionDetailsForUserOp';
import { OnRamperDto, SignMessageDto, validateDto } from './dto';
import { ZeroDevWalletAPI } from './base/ZeroDevWalletAPI';
import { SimpleAccountAPI } from './base/SimpleAccountWalletAPI';
import { ErrorHandler } from './errorHandler/errorHandler.service';
import { EtherspotBundler } from './bundler';
/**
* Prime-Sdk
*
* @category Prime-Sdk
*/
export class PrimeSdk {
private etherspotWallet: EtherspotWalletAPI | ZeroDevWalletAPI | SimpleAccountAPI;
private bundler: HttpRpcClient;
private chainId: number;
private factoryUsed: Factory;
private index: number;
private userOpsBatch: BatchUserOpsRequest = { to: [], data: [], value: [] };
constructor(walletProvider: WalletProviderLike, optionsLike: SdkOptions) {
let walletConnectProvider;
if (isWalletConnectProvider(walletProvider)) {
walletConnectProvider = new WalletConnect2WalletProvider(walletProvider as EthereumProvider);
} else if (!isWalletProvider(walletProvider)) {
throw new Exception('Invalid wallet provider');
}
const {
index,
chainId,
rpcProviderUrl,
accountAddress,
} = optionsLike;
this.chainId = chainId;
this.index = index ?? 0;
if (!optionsLike.bundlerProvider) {
optionsLike.bundlerProvider = new EtherspotBundler(chainId);
}
this.factoryUsed = optionsLike.factoryWallet ?? Factory.ETHERSPOT;
let provider;
if (rpcProviderUrl) {
provider = new providers.JsonRpcProvider(rpcProviderUrl);
} else provider = new providers.JsonRpcProvider(optionsLike.bundlerProvider.url);
let entryPointAddress = '', walletFactoryAddress = '';
if (Networks[chainId]) {
entryPointAddress = Networks[chainId].contracts.entryPoint;
if (Networks[chainId].contracts.walletFactory[this.factoryUsed] == '') throw new Exception('The selected factory is not deployed in the selected chain_id')
walletFactoryAddress = Networks[chainId].contracts.walletFactory[this.factoryUsed];
}
if (optionsLike.entryPointAddress) entryPointAddress = optionsLike.entryPointAddress;
if (optionsLike.walletFactoryAddress) walletFactoryAddress = optionsLike.walletFactoryAddress;
if (entryPointAddress == '') throw new Exception('entryPointAddress not set on the given chain_id')
if (walletFactoryAddress == '') throw new Exception('walletFactoryAddress not set on the given chain_id')
if (this.factoryUsed === Factory.ZERO_DEV) {
this.etherspotWallet = new ZeroDevWalletAPI({
provider,
walletProvider: walletConnectProvider ?? walletProvider,
optionsLike,
entryPointAddress,
factoryAddress: walletFactoryAddress,
index: this.index,
})
} else if (this.factoryUsed === Factory.SIMPLE_ACCOUNT) {
this.etherspotWallet = new SimpleAccountAPI({
provider,
walletProvider: walletConnectProvider ?? walletProvider,
optionsLike,
entryPointAddress,
factoryAddress: walletFactoryAddress,
index: this.index,
})
}
else {
this.etherspotWallet = new EtherspotWalletAPI({
provider,
walletProvider: walletConnectProvider ?? walletProvider,
optionsLike,
entryPointAddress,
factoryAddress: walletFactoryAddress,
predefinedAccountAddress: accountAddress,
index: this.index,
})
}
this.bundler = new HttpRpcClient(optionsLike.bundlerProvider.url, entryPointAddress, chainId);
}
// exposes
get state(): StateService {
return this.etherspotWallet.services.stateService;
}
get state$(): BehaviorSubject<State> {
return this.etherspotWallet.services.stateService.state$;
}
get supportedNetworks(): Network[] {
return this.etherspotWallet.services.networkService.supportedNetworks;
}
/**
* destroys
*/
destroy(): void {
this.etherspotWallet.context.destroy();
}
// wallet
/**
* signs message
* @param dto
* @return Promise<string>
*/
async signMessage(dto: SignMessageDto): Promise<string> {
const { message } = await validateDto(dto, SignMessageDto);
await this.etherspotWallet.require({
network: false,
});
return this.etherspotWallet.services.walletService.signMessage(message);
}
async getCounterFactualAddress(): Promise<string> {
return this.etherspotWallet.getCounterFactualAddress();
}
async estimate(params: {
paymasterDetails?: PaymasterApi,
gasDetails?: TransactionGasInfoForUserOp,
callGasLimit?: BigNumberish,
key?: number
} = {}) {
const { paymasterDetails, gasDetails, callGasLimit, key } = params;
let dummySignature = "0xfffffffffffffffffffffffffffffff0000000000000000000000000000000007aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1c";
/**
* Dummy signature used only in the case of zeroDev factory contract
*/
if (this.factoryUsed === Factory.ZERO_DEV) {
dummySignature = "0x00000000870fe151d548a1c527c3804866fab30abf28ed17b79d5fc5149f19ca0819fefc3c57f3da4fdf9b10fab3f2f3dca536467ae44943b9dbb8433efe7760ddd72aaa1c"
}
if (this.userOpsBatch.to.length < 1) {
throw new ErrorHandler('cannot sign empty transaction batch', 1);
}
if (paymasterDetails?.url) {
const paymasterAPI = new VerifyingPaymasterAPI(paymasterDetails.url, this.etherspotWallet.entryPointAddress, paymasterDetails.context ?? {})
this.etherspotWallet.setPaymasterApi(paymasterAPI)
} else this.etherspotWallet.setPaymasterApi(null);
const tx: TransactionDetailsForUserOp = {
target: this.userOpsBatch.to,
values: this.userOpsBatch.value,
data: this.userOpsBatch.data,
dummySignature: dummySignature,
...gasDetails,
}
const gasInfo = await this.getGasFee()
const partialtx = await this.etherspotWallet.createUnsignedUserOp({
...tx,
maxFeePerGas: gasInfo.maxFeePerGas,
maxPriorityFeePerGas: gasInfo.maxPriorityFeePerGas,
}, key);
if (callGasLimit) {
partialtx.callGasLimit = BigNumber.from(callGasLimit).toHexString();
}
const bundlerGasEstimate = await this.bundler.getVerificationGasInfo(partialtx);
// if user has specified the gas prices then use them
if (gasDetails?.maxFeePerGas && gasDetails?.maxPriorityFeePerGas) {
partialtx.maxFeePerGas = gasDetails.maxFeePerGas;
partialtx.maxPriorityFeePerGas = gasDetails.maxPriorityFeePerGas;
}
// if estimation has gas prices use them, otherwise fetch them in a separate call
else if (bundlerGasEstimate.maxFeePerGas && bundlerGasEstimate.maxPriorityFeePerGas) {
partialtx.maxFeePerGas = bundlerGasEstimate.maxFeePerGas;
partialtx.maxPriorityFeePerGas = bundlerGasEstimate.maxPriorityFeePerGas;
} else {
const gas = await this.getGasFee();
partialtx.maxFeePerGas = gas.maxFeePerGas;
partialtx.maxPriorityFeePerGas = gas.maxPriorityFeePerGas;
}
if (bundlerGasEstimate.preVerificationGas) {
partialtx.preVerificationGas = BigNumber.from(bundlerGasEstimate.preVerificationGas);
partialtx.verificationGasLimit = BigNumber.from(bundlerGasEstimate.verificationGasLimit ?? bundlerGasEstimate.verificationGas);
const expectedCallGasLimit = BigNumber.from(bundlerGasEstimate.callGasLimit);
if (!callGasLimit)
partialtx.callGasLimit = expectedCallGasLimit;
else if (BigNumber.from(callGasLimit).lt(expectedCallGasLimit))
throw new ErrorHandler(`CallGasLimit is too low. Expected atleast ${expectedCallGasLimit.toString()}`);
}
return partialtx;
}
async getGasFee() {
const version = await this.bundler.getBundlerVersion();
if (version && version.includes('skandha'))
return this.bundler.getSkandhaGasPrice();
return getGasFee(this.etherspotWallet.provider as providers.JsonRpcProvider);
}
async send(userOp: UserOperationStruct) {
const signedUserOp = await this.etherspotWallet.signUserOp(userOp);
return this.bundler.sendUserOpToBundler(signedUserOp);
}
async signTypedData(
DataFields: TypedDataField[],
message: any
) {
return this.etherspotWallet.signTypedData(DataFields, message);
}
async getNativeBalance() {
if (!this.etherspotWallet.accountAddress) {
await this.getCounterFactualAddress();
}
const balance = await this.etherspotWallet.provider.getBalance(this.etherspotWallet.accountAddress);
return ethers.utils.formatEther(balance);
}
async getUserOpReceipt(userOpHash: string) {
return this.bundler.getUserOpsReceipt(userOpHash);
}
async getUserOpHash(userOp: UserOperationStruct) {
return this.etherspotWallet.getUserOpHash(userOp);
}
async addUserOpsToBatch(
tx: UserOpsRequest,
): Promise<BatchUserOpsRequest> {
if (!tx.data && !tx.value) throw new ErrorHandler('Data and Value both cannot be empty', 1);
if (tx.value && this.factoryUsed === Factory.SIMPLE_ACCOUNT && tx.value.toString() !== '0' && this.userOpsBatch.value.length > 0) throw new ErrorHandler('SimpleAccount: native transfers cant be part of batch', 1);
this.userOpsBatch.to.push(tx.to);
this.userOpsBatch.value.push(tx.value ?? BigNumber.from(0));
this.userOpsBatch.data.push(tx.data ?? '0x');
return this.userOpsBatch;
}
async clearUserOpsFromBatch(): Promise<void> {
this.userOpsBatch.to = [];
this.userOpsBatch.data = [];
this.userOpsBatch.value = [];
}
async getAccountContract() {
return this.etherspotWallet._getAccountContract();
}
async totalGasEstimated(userOp: UserOperationStruct): Promise<BigNumber> {
const callGasLimit = BigNumber.from(await userOp.callGasLimit);
const verificationGasLimit = BigNumber.from(await userOp.verificationGasLimit);
const preVerificationGas = BigNumber.from(await userOp.preVerificationGas);
return callGasLimit.add(verificationGasLimit).add(preVerificationGas);
}
async getFiatOnRamp(params: OnRamperDto = {}) {
if (!params.onlyCryptoNetworks) params.onlyCryptoNetworks = onRamperAllNetworks.join(',');
else {
const networks = params.onlyCryptoNetworks.split(',');
for (const network in networks) {
if (!onRamperAllNetworks.includes(network)) throw new ErrorHandler('Included Networks which are not supported. Please Check', 1);
}
}
const url = `https://buy.onramper.com/?networkWallets=ETHEREUM:${await this.getCounterFactualAddress()}` +
`&apiKey=${onRampApiKey}` +
`&onlyCryptoNetworks=${params.onlyCryptoNetworks}` +
`${params.defaultCrypto ? `&defaultCrypto=${params.defaultCrypto}` : ``}` +
`${params.excludeCryptos ? `&excludeCryptos=${params.excludeCryptos}` : ``}` +
`${params.onlyCryptos ? `&onlyCryptos=${params.onlyCryptos}` : ``}` +
`${params.excludeCryptoNetworks ? `&excludeCryptoNetworks=${params.excludeCryptoNetworks}` : ``}` +
`${params.defaultAmount ? `&defaultCrypto=${params.defaultAmount}` : ``}` +
`${params.defaultFiat ? `&defaultFiat=${params.defaultFiat}` : ``}` +
`${params.isAmountEditable ? `&isAmountEditable=${params.isAmountEditable}` : ``}` +
`${params.onlyFiats ? `&onlyFiats=${params.onlyFiats}` : ``}` +
`${params.excludeFiats ? `&excludeFiats=${params.excludeFiats}` : ``}` +
`&themeName=${params.themeName ?? 'dark'}`;
if (typeof window === 'undefined') {
openUrl(url);
} else {
window.open(url);
}
return url;
}
}