-
-
Notifications
You must be signed in to change notification settings - Fork 946
/
Copy pathgetWithdrawalStatus.ts
279 lines (259 loc) · 8.96 KB
/
getWithdrawalStatus.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
import {
type ReadContractErrorType,
readContract,
} from '../../actions/public/readContract.js'
import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import { ContractFunctionRevertedError } from '../../errors/contract.js'
import type { ErrorType } from '../../errors/utils.js'
import type { Account } from '../../types/account.js'
import type {
Chain,
DeriveChain,
GetChainParameter,
} from '../../types/chain.js'
import type { TransactionReceipt } from '../../types/transaction.js'
import type { OneOf } from '../../types/utils.js'
import { portal2Abi, portalAbi } from '../abis.js'
import {
ReceiptContainsNoWithdrawalsError,
type ReceiptContainsNoWithdrawalsErrorType,
} from '../errors/withdrawal.js'
import type { TargetChain } from '../types/chain.js'
import type { GetContractAddressParameter } from '../types/contract.js'
import {
type GetWithdrawalsErrorType,
getWithdrawals,
} from '../utils/getWithdrawals.js'
import {
type GetGameErrorType,
type GetGameParameters,
getGame,
} from './getGame.js'
import {
type GetL2OutputErrorType,
type GetL2OutputParameters,
getL2Output,
} from './getL2Output.js'
import {
type GetPortalVersionParameters,
getPortalVersion,
} from './getPortalVersion.js'
import {
type GetTimeToFinalizeErrorType,
type GetTimeToFinalizeParameters,
getTimeToFinalize,
} from './getTimeToFinalize.js'
export type GetWithdrawalStatusParameters<
chain extends Chain | undefined = Chain | undefined,
chainOverride extends Chain | undefined = Chain | undefined,
_derivedChain extends Chain | undefined = DeriveChain<chain, chainOverride>,
> = GetChainParameter<chain, chainOverride> &
OneOf<
| GetContractAddressParameter<_derivedChain, 'l2OutputOracle' | 'portal'>
| GetContractAddressParameter<
_derivedChain,
'disputeGameFactory' | 'portal'
>
> & {
/**
* Limit of games to extract to check withdrawal status.
* @default 100
*/
gameLimit?: number
/**
* The relative index of the withdrawal in the transaction receipt logs.
* @default 0
*/
logIndex?: number
receipt: TransactionReceipt
}
export type GetWithdrawalStatusReturnType =
| 'waiting-to-prove'
| 'ready-to-prove'
| 'waiting-to-finalize'
| 'ready-to-finalize'
| 'finalized'
export type GetWithdrawalStatusErrorType =
| GetL2OutputErrorType
| GetTimeToFinalizeErrorType
| GetWithdrawalsErrorType
| ReadContractErrorType
| ReceiptContainsNoWithdrawalsErrorType
| ErrorType
/**
* Returns the current status of a withdrawal. Used for the [Withdrawal](/op-stack/guides/withdrawals) flow.
*
* - Docs: https://viem.sh/op-stack/actions/getWithdrawalStatus
*
* @param client - Client to use
* @param parameters - {@link GetWithdrawalStatusParameters}
* @returns Status of the withdrawal. {@link GetWithdrawalStatusReturnType}
*
* @example
* import { createPublicClient, http } from 'viem'
* import { getBlockNumber } from 'viem/actions'
* import { mainnet, optimism } from 'viem/chains'
* import { getWithdrawalStatus } from 'viem/op-stack'
*
* const publicClientL1 = createPublicClient({
* chain: mainnet,
* transport: http(),
* })
* const publicClientL2 = createPublicClient({
* chain: optimism,
* transport: http(),
* })
*
* const receipt = await publicClientL2.getTransactionReceipt({ hash: '0x...' })
* const status = await getWithdrawalStatus(publicClientL1, {
* receipt,
* targetChain: optimism
* })
*/
export async function getWithdrawalStatus<
chain extends Chain | undefined,
account extends Account | undefined,
chainOverride extends Chain | undefined = undefined,
>(
client: Client<Transport, chain, account>,
parameters: GetWithdrawalStatusParameters<chain, chainOverride>,
): Promise<GetWithdrawalStatusReturnType> {
const {
chain = client.chain,
gameLimit = 100,
receipt,
targetChain: targetChain_,
logIndex = 0,
} = parameters
const targetChain = targetChain_ as unknown as TargetChain
const portalAddress = (() => {
if (parameters.portalAddress) return parameters.portalAddress
if (chain) return targetChain.contracts.portal[chain.id].address
return Object.values(targetChain.contracts.portal)[0].address
})()
const withdrawal = getWithdrawals(receipt)[logIndex]
if (!withdrawal)
throw new ReceiptContainsNoWithdrawalsError({
hash: receipt.transactionHash,
})
const portalVersion = await getPortalVersion(
client,
parameters as GetPortalVersionParameters,
)
// Legacy (Portal < v3)
if (portalVersion.major < 3) {
const [outputResult, proveResult, finalizedResult, timeToFinalizeResult] =
await Promise.allSettled([
getL2Output(client, {
...parameters,
l2BlockNumber: receipt.blockNumber,
} as GetL2OutputParameters),
readContract(client, {
abi: portalAbi,
address: portalAddress,
functionName: 'provenWithdrawals',
args: [withdrawal.withdrawalHash],
}),
readContract(client, {
abi: portalAbi,
address: portalAddress,
functionName: 'finalizedWithdrawals',
args: [withdrawal.withdrawalHash],
}),
getTimeToFinalize(client, {
...parameters,
withdrawalHash: withdrawal.withdrawalHash,
} as GetTimeToFinalizeParameters),
])
// If the L2 Output is not processed yet (ie. the actions throws), this means
// that the withdrawal is not ready to prove.
if (outputResult.status === 'rejected') {
const error = outputResult.reason as GetL2OutputErrorType
if (
error.cause instanceof ContractFunctionRevertedError &&
error.cause.data?.args?.[0] ===
'L2OutputOracle: cannot get output for a block that has not been proposed'
)
return 'waiting-to-prove'
throw error
}
if (proveResult.status === 'rejected') throw proveResult.reason
if (finalizedResult.status === 'rejected') throw finalizedResult.reason
if (timeToFinalizeResult.status === 'rejected')
throw timeToFinalizeResult.reason
const [_, proveTimestamp] = proveResult.value
if (!proveTimestamp) return 'ready-to-prove'
const finalized = finalizedResult.value
if (finalized) return 'finalized'
const { seconds } = timeToFinalizeResult.value
return seconds > 0 ? 'waiting-to-finalize' : 'ready-to-finalize'
}
const numProofSubmitters = await readContract(client, {
abi: portal2Abi,
address: portalAddress,
functionName: 'numProofSubmitters',
args: [withdrawal.withdrawalHash],
}).catch(() => 1n)
const proofSubmitter = await readContract(client, {
abi: portal2Abi,
address: portalAddress,
functionName: 'proofSubmitters',
args: [withdrawal.withdrawalHash, numProofSubmitters - 1n],
}).catch(() => withdrawal.sender)
const [disputeGameResult, checkWithdrawalResult, finalizedResult] =
await Promise.allSettled([
getGame(client, {
...parameters,
l2BlockNumber: receipt.blockNumber,
limit: gameLimit,
} as GetGameParameters),
readContract(client, {
abi: portal2Abi,
address: portalAddress,
functionName: 'checkWithdrawal',
args: [withdrawal.withdrawalHash, proofSubmitter],
}),
readContract(client, {
abi: portal2Abi,
address: portalAddress,
functionName: 'finalizedWithdrawals',
args: [withdrawal.withdrawalHash],
}),
])
if (finalizedResult.status === 'fulfilled' && finalizedResult.value)
return 'finalized'
if (disputeGameResult.status === 'rejected') {
const error = disputeGameResult.reason as GetGameErrorType
if (error.name === 'GameNotFoundError') return 'waiting-to-prove'
throw disputeGameResult.reason
}
if (checkWithdrawalResult.status === 'rejected') {
const error = checkWithdrawalResult.reason as ReadContractErrorType
if (error.cause instanceof ContractFunctionRevertedError) {
const errorMessage = error.cause.data?.args?.[0]
if (
errorMessage === 'OptimismPortal: invalid game type' ||
errorMessage === 'OptimismPortal: withdrawal has not been proven yet' ||
errorMessage ===
'OptimismPortal: withdrawal has not been proven by proof submitter address yet' ||
errorMessage ===
'OptimismPortal: dispute game created before respected game type was updated'
)
return 'ready-to-prove'
if (
errorMessage ===
'OptimismPortal: proven withdrawal has not matured yet' ||
errorMessage ===
'OptimismPortal: output proposal has not been finalized yet' ||
errorMessage === 'OptimismPortal: output proposal in air-gap'
)
return 'waiting-to-finalize'
if (error.cause.data?.errorName === 'InvalidGameType')
return 'ready-to-prove'
}
throw checkWithdrawalResult.reason
}
if (finalizedResult.status === 'rejected') throw finalizedResult.reason
return 'ready-to-finalize'
}