-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathestimation.ts
More file actions
342 lines (292 loc) · 11.6 KB
/
Copy pathestimation.ts
File metadata and controls
342 lines (292 loc) · 11.6 KB
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
330
331
332
333
334
335
336
337
338
339
340
341
342
import ErrorHumanizerError from '../../classes/ErrorHumanizerError'
import { Account, IAccountsController } from '../../interfaces/account'
import { IActivityController } from '../../interfaces/activity'
import { ErrorRef } from '../../interfaces/eventEmitter'
import { IFeatureFlagsController } from '../../interfaces/featureFlags'
import { IKeystoreController } from '../../interfaces/keystore'
import { INetworksController } from '../../interfaces/network'
import { IPortfolioController } from '../../interfaces/portfolio'
import { RPCProvider } from '../../interfaces/provider'
import { SignAccountOpError, Warning } from '../../interfaces/signAccountOp'
import { isSmartAccount } from '../../libs/account/account'
import { BaseAccount } from '../../libs/account/BaseAccount'
import { getBaseAccount } from '../../libs/account/getBaseAccount'
import { AccountOp } from '../../libs/accountOp/accountOp'
import { getEstimation, getEstimationSummary } from '../../libs/estimate/estimate'
import { FeePaymentOption, FullEstimationSummary } from '../../libs/estimate/interfaces'
import { isPortfolioGasTankResult } from '../../libs/portfolio/helpers'
import { BundlerSwitcher } from '../../services/bundlers/bundlerSwitcher'
import { getIsViewOnly } from '../../utils/accounts'
import EventEmitter from '../eventEmitter/eventEmitter'
import { EstimationStatus } from './types'
export class EstimationController extends EventEmitter {
#keystore: IKeystoreController
#accounts: IAccountsController
#networks: INetworksController
#provider: RPCProvider
#portfolio: IPortfolioController
#featureFlags: IFeatureFlagsController
status: EstimationStatus = EstimationStatus.Initial
estimation: FullEstimationSummary | null = null
error: Error | null = null
/**
* a boolean to understand if the estimation has been performed
* at least one indicating clearly that all other are re-estimates
*/
hasEstimated: boolean = false
estimationRetryError: ErrorRef | null = null
availableFeeOptions: FeePaymentOption[] = []
#bundlerSwitcher: BundlerSwitcher
#notFatalBundlerError?: Error
#activity: IActivityController
/**
* Used to prevent slow estimations for a past accountOp overwriting
* the latest estimation results
*/
private lastAccountOpId: string | null = null
constructor(
keystore: IKeystoreController,
accounts: IAccountsController,
networks: INetworksController,
provider: RPCProvider,
portfolio: IPortfolioController,
bundlerSwitcher: BundlerSwitcher,
activity: IActivityController,
featureFlags: IFeatureFlagsController
) {
super()
this.#keystore = keystore
this.#accounts = accounts
this.#networks = networks
this.#provider = provider
this.#portfolio = portfolio
this.#featureFlags = featureFlags
this.#bundlerSwitcher = bundlerSwitcher
this.#activity = activity
}
#getAvailableFeeOptions(baseAcc: BaseAccount, op: AccountOp): FeePaymentOption[] {
const estimation = this.estimation as FullEstimationSummary
return baseAcc.getAvailableFeeOptions(
estimation,
estimation.ambireEstimation
? estimation.ambireEstimation.feePaymentOptions
: estimation.providerEstimation
? estimation.providerEstimation.feePaymentOptions
: [],
op
)
}
async estimate(op: AccountOp) {
this.status = EstimationStatus.Loading
this.emitUpdate()
const account = this.#accounts.accounts.find((acc) => acc.addr === op.accountAddr)!
const network = this.#networks.networks.find((net) => net.chainId === op.chainId)!
const accountState = await this.#accounts.getOrFetchAccountOnChainState(
op.accountAddr,
op.chainId
)
if (!accountState) {
this.error = new Error(
'During the preparation step, required transaction information was found missing (account state). Please try again later or contact support.'
)
this.status = EstimationStatus.Error
this.hasEstimated = true
this.emitUpdate()
return
}
const baseAcc = getBaseAccount(
account,
accountState,
network,
this.#featureFlags.isFeatureEnabled('erc4337')
)
// Take the fee tokens from two places: the user's tokens and his gasTank
// The gasTank tokens participate on each network as they belong everywhere
// NOTE: at some point we should check all the "?" signs below and if
// an error pops out, we should notify the user about it
let networkFeeTokens =
this.#portfolio.getAccountPortfolioState(op.accountAddr)?.[op.chainId.toString()]?.result
?.feeTokens ?? []
// This could happen only in a race when a NOT currently selected account is
// requested, switched to and immediately fired a txn request for. In that situation,
// the portfolio would not be fetched and the estimation would be fired without tokens,
// resulting in a "nothing to pay the fee with" error which is absolutely wrong
if (networkFeeTokens.length === 0) {
await this.#portfolio.updateSelectedAccount(op.accountAddr, [network])
networkFeeTokens =
this.#portfolio.getAccountPortfolioState(op.accountAddr)?.[op.chainId.toString()]?.result
?.feeTokens ?? []
}
const gasTankResult = this.#portfolio.getAccountPortfolioState(op.accountAddr)?.gasTank?.result
const gasTankFeeTokens = isPortfolioGasTankResult(gasTankResult)
? gasTankResult.gasTankTokens
: []
const feeTokens =
[...networkFeeTokens, ...gasTankFeeTokens].filter((t) => t.flags.isFeeToken) || []
// Here, we list EOA accounts for which you can also obtain an estimation of the AccountOp payment.
// In the case of operating with a smart account (an account with creation code), all other EOAs can pay the fee.
//
// If the current account is an EOA, only this account can pay the fee,
// and there's no need for checking other EOA accounts native balances.
// This is already handled and estimated as a fee option in the estimate library, which is why we pass an empty array here.
//
// we're excluding the view only accounts from the natives to check
// in all cases EXCEPT the case where we're making an estimation for
// the view only account itself. In all other, view only accounts options
// should not be present as the user cannot pay the fee with them (no key)
const nativeToCheck = baseAcc.canBroadcastByOtherEOA()
? this.#accounts.accounts
.filter(
(acc) =>
!isSmartAccount(acc) &&
(acc.addr === op.accountAddr ||
!getIsViewOnly(this.#keystore.keys, acc.associatedKeys))
)
// internal keys first
.sort((a, b) => {
const aKeyInternal = this.#keystore.keys.find(
(k) => k.type === 'internal' && k.addr === a.addr
)
const bKeyInternal = this.#keystore.keys.find(
(k) => k.type === 'internal' && k.addr === b.addr
)
if (aKeyInternal && !bKeyInternal) return -1
if (!aKeyInternal && bKeyInternal) return 1
return 0
})
.map((acc) => acc.addr)
: []
this.lastAccountOpId = op.id
const estimation = await getEstimation(
baseAcc,
accountState,
op,
network,
this.#provider,
feeTokens,
nativeToCheck,
this.#bundlerSwitcher,
(this.#activity.broadcastedButNotConfirmed[account.addr] || []).find(
(accOp) => accOp.chainId === network.chainId && !!accOp.asUserOperation
)
).catch((e) => {
console.error(e)
return e
})
// Done to prevent race conditions
if (op.id !== this.lastAccountOpId) {
const error = new Error(
`Estimation race condition prevented. Op id: ${op.id}. Expected: ${this.lastAccountOpId}`
)
this.emitError({
message: 'Estimation race condition prevented',
error,
level: 'silent'
})
return
}
const isSuccess = !(estimation instanceof Error) && !estimation.criticalError
if (isSuccess) {
this.estimation = getEstimationSummary(estimation)
this.error = null
this.status = EstimationStatus.Success
this.estimationRetryError = null
this.availableFeeOptions = this.#getAvailableFeeOptions(baseAcc, op)
this.#notFatalBundlerError =
estimation.bundler instanceof Error
? new Error(estimation.bundler.message, { cause: '4337_ESTIMATION' })
: undefined
} else {
this.estimation = null
this.error = estimation instanceof Error ? estimation : estimation.criticalError
this.status = EstimationStatus.Error
this.availableFeeOptions = []
}
// estimation.flags.hasNonceDiscrepancy is a signal from the estimation
// that the account state is not the latest and needs to be updated
if (
this.estimation &&
(this.estimation.flags.hasNonceDiscrepancy || this.estimation.flags.has4337NonceDiscrepancy)
) {
// continue on error here as the flags are more like app helpers
this.#accounts
.updateAccountState(op.accountAddr, 'pending', [op.chainId])
.catch((e) => console.error(e))
}
this.hasEstimated = true
this.emitUpdate()
}
/**
* it's initialized if it has estimated at least once
*/
isInitialized() {
return this.hasEstimated
}
/**
* has it estimated at least once without a failure
*/
isLoadingOrFailed(): boolean {
return this.status === EstimationStatus.Loading || this.error instanceof Error
}
calculateWarnings(acc: Account) {
const warnings: Warning[] = []
if (this.estimationRetryError && this.status === EstimationStatus.Success) {
warnings.push({
id: 'estimation-retry',
title: this.estimationRetryError.message,
text: 'You can proceed, but fee estimation is outdated - consider waiting for an updated estimation for a more optimal fee.'
})
}
if (
this.#notFatalBundlerError?.cause === '4337_ESTIMATION' &&
// do not show the warning for safe accounts that don't have a gas tank
(!acc.safeCreation ||
(this.availableFeeOptions.find((opt) => opt.token.flags.onGasTank)?.availableAmount || 0) >
0)
) {
warnings.push({
id: 'bundler-failure',
title: 'Fee options are temporarily limited',
text: 'Use the "Retry" button to try again, or pay the fee with the native token"'
})
}
if (this.#notFatalBundlerError?.cause === '4337_INVALID_NONCE') {
warnings.push({
id: 'bundler-nonce-discrepancy',
title:
'You can proceed safely, but fee payment options are limited due to a pending transaction'
})
}
return warnings
}
get errors(): SignAccountOpError[] {
const errors: SignAccountOpError[] = []
if (this.isLoadingOrFailed() && this.estimationRetryError) {
// If there is a successful estimation we should show this as a warning
// as the user can use the old estimation to broadcast
errors.push({
title: `${this.estimationRetryError.message} ${
this.error
? 'We will continue retrying, but please check your internet connection.'
: 'Automatically retrying in a few seconds. Please wait...'
}`
})
return errors
}
if (!this.isInitialized()) return []
if (this.error) {
let code = ''
if (this.error instanceof ErrorHumanizerError && this.error.isFallbackMessage) {
code =
typeof this.error.cause === 'string' && !!this.error.cause
? this.error.cause
: 'ESTIMATION_ERROR'
}
errors.push({
title: this.error.message,
code
})
}
return errors
}
}