@effect-blockchain/starknet 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/dist/StarknetAddress.d.ts +29 -0
  4. package/dist/StarknetAddress.d.ts.map +1 -0
  5. package/dist/StarknetAddress.js +29 -0
  6. package/dist/StarknetAddress.js.map +1 -0
  7. package/dist/StarknetBlock.d.ts +49 -0
  8. package/dist/StarknetBlock.d.ts.map +1 -0
  9. package/dist/StarknetBlock.js +52 -0
  10. package/dist/StarknetBlock.js.map +1 -0
  11. package/dist/StarknetEvent.d.ts +34 -0
  12. package/dist/StarknetEvent.d.ts.map +1 -0
  13. package/dist/StarknetEvent.js +39 -0
  14. package/dist/StarknetEvent.js.map +1 -0
  15. package/dist/StarknetIndexer.d.ts +157 -0
  16. package/dist/StarknetIndexer.d.ts.map +1 -0
  17. package/dist/StarknetIndexer.js +245 -0
  18. package/dist/StarknetIndexer.js.map +1 -0
  19. package/dist/StarknetNetwork.d.ts +72 -0
  20. package/dist/StarknetNetwork.d.ts.map +1 -0
  21. package/dist/StarknetNetwork.js +83 -0
  22. package/dist/StarknetNetwork.js.map +1 -0
  23. package/dist/StarknetRelayer.d.ts +273 -0
  24. package/dist/StarknetRelayer.d.ts.map +1 -0
  25. package/dist/StarknetRelayer.js +352 -0
  26. package/dist/StarknetRelayer.js.map +1 -0
  27. package/dist/StarknetRpc.d.ts +306 -0
  28. package/dist/StarknetRpc.d.ts.map +1 -0
  29. package/dist/StarknetRpc.js +281 -0
  30. package/dist/StarknetRpc.js.map +1 -0
  31. package/dist/StarknetSigner.d.ts +75 -0
  32. package/dist/StarknetSigner.d.ts.map +1 -0
  33. package/dist/StarknetSigner.js +84 -0
  34. package/dist/StarknetSigner.js.map +1 -0
  35. package/dist/StarknetTransaction.d.ts +74 -0
  36. package/dist/StarknetTransaction.d.ts.map +1 -0
  37. package/dist/StarknetTransaction.js +2 -0
  38. package/dist/StarknetTransaction.js.map +1 -0
  39. package/dist/StarknetTransactionHash.d.ts +22 -0
  40. package/dist/StarknetTransactionHash.d.ts.map +1 -0
  41. package/dist/StarknetTransactionHash.js +22 -0
  42. package/dist/StarknetTransactionHash.js.map +1 -0
  43. package/dist/index.d.ts +44 -0
  44. package/dist/index.d.ts.map +1 -0
  45. package/dist/index.js +45 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/internal/PaddedFelt.d.ts +2 -0
  48. package/dist/internal/PaddedFelt.d.ts.map +1 -0
  49. package/dist/internal/PaddedFelt.js +15 -0
  50. package/dist/internal/PaddedFelt.js.map +1 -0
  51. package/dist/internal/confirmations.d.ts +2 -0
  52. package/dist/internal/confirmations.d.ts.map +1 -0
  53. package/dist/internal/confirmations.js +13 -0
  54. package/dist/internal/confirmations.js.map +1 -0
  55. package/dist/internal/rpcMethods.d.ts +2 -0
  56. package/dist/internal/rpcMethods.d.ts.map +1 -0
  57. package/dist/internal/rpcMethods.js +225 -0
  58. package/dist/internal/rpcMethods.js.map +1 -0
  59. package/dist/internal/transactionHash.d.ts +2 -0
  60. package/dist/internal/transactionHash.d.ts.map +1 -0
  61. package/dist/internal/transactionHash.js +60 -0
  62. package/dist/internal/transactionHash.js.map +1 -0
  63. package/package.json +66 -3
  64. package/src/StarknetAddress.ts +42 -0
  65. package/src/StarknetBlock.ts +54 -0
  66. package/src/StarknetEvent.ts +45 -0
  67. package/src/StarknetIndexer.ts +363 -0
  68. package/src/StarknetNetwork.ts +107 -0
  69. package/src/StarknetRelayer.ts +437 -0
  70. package/src/StarknetRpc.ts +524 -0
  71. package/src/StarknetSigner.ts +115 -0
  72. package/src/StarknetTransaction.ts +68 -0
  73. package/src/StarknetTransactionHash.ts +31 -0
  74. package/src/index.ts +55 -0
  75. package/src/internal/PaddedFelt.ts +18 -0
  76. package/src/internal/confirmations.ts +17 -0
  77. package/src/internal/rpcMethods.ts +224 -0
  78. package/src/internal/transactionHash.ts +64 -0
@@ -0,0 +1,437 @@
1
+ /**
2
+ * Starknet transaction relaying on top of {@link StarknetRpc.StarknetRpc}: signing a transaction, broadcasting it and
3
+ * following it until it is final.
4
+ *
5
+ * A relayer here sends an account's own transactions and manages their nonces and fees, as OpenZeppelin Relayer does.
6
+ * It is not a meta-transaction relayer (a paymaster, SNIP-9 outside execution) paying for someone else's transaction.
7
+ * It keeps no state: storing hashes and nonces, deciding when to resend and holding keys belong to the application.
8
+ * Senders sharing an account must each pass their own nonce, as the node's nonce does not count a transaction that is
9
+ * signed and not yet in a pre-confirmed block, and two concurrent `sign` calls read the same one.
10
+ *
11
+ * Only V3 transactions are sent: an `INVOKE` running calls through the `__execute__` entrypoint of a Cairo 1 account
12
+ * (SNIP-6), and the `DEPLOY_ACCOUNT` of the signer's own account. `sign` and `signDeployAccount` return the
13
+ * transaction hash before anything is broadcast, so it can be stored first, and `broadcast` can be repeated with the
14
+ * same transaction.
15
+ *
16
+ * Resource bounds come from `starknet_estimateFee` (see {@link defaultFees}) unless `sign` receives them. The
17
+ * transaction is estimated unsigned, with `SKIP_VALIDATE`, so that a custody signer signs once: the estimate leaves
18
+ * out the account's validation, which the default strategy adds back. The account must hold the bounds in STRK, each
19
+ * `maxAmount` times its `maxPricePerUnit`, though it only pays what the transaction uses. The tip is 0 unless given.
20
+ *
21
+ * A transaction is in one {@link StarknetTransactionStatus}:
22
+ *
23
+ * | status | meaning | final |
24
+ * |---|---|---|
25
+ * | `Pending` | known to the node, not in an accepted block: received, candidate or pre-confirmed | no |
26
+ * | `Included` | in the accepted block `block`, above the last confirmed block | no |
27
+ * | `Confirmed` | succeeded in `block`, at or below the last confirmed block | yes |
28
+ * | `Failed` | reverted in `block`, at or below the last confirmed block | yes |
29
+ * | `NotFound` | unknown to the node: dropped, not propagated yet, or never sent | no |
30
+ *
31
+ * The last confirmed block is the one of `StarknetIndexer`: with the default of 0 confirmations, a transaction is
32
+ * final as soon as its block is accepted on L2, and `Included` only shows while the head read is behind that block.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * import type { StarknetAddress } from "@effect-blockchain/starknet/StarknetAddress"
37
+ * import { StarknetRelayer } from "@effect-blockchain/starknet/StarknetRelayer"
38
+ * import type { StarknetSigner } from "@effect-blockchain/starknet/StarknetSigner"
39
+ * import type { StarknetTransactionHash } from "@effect-blockchain/starknet/StarknetTransactionHash"
40
+ * import * as Effect from "effect/Effect"
41
+ *
42
+ * declare const signer: StarknetSigner
43
+ * declare const token: StarknetAddress
44
+ * declare const to: StarknetAddress
45
+ * declare const store: (hash: StarknetTransactionHash, nonce: bigint) => Effect.Effect<void>
46
+ *
47
+ * const program = Effect.gen(function*() {
48
+ * const relayer = yield* StarknetRelayer
49
+ * // an ERC-20 `transfer(recipient, amount)`, the amount being a u256 as two felts
50
+ * const calls = [{ contractAddress: token, entrypoint: "transfer", calldata: [to, "0x1", "0x0"] }]
51
+ * const { hash, nonce, signed } = yield* relayer.sign({ signer, calls })
52
+ * // stored before the broadcast: a crash in between leaves a hash to look up, never an unknown transaction
53
+ * yield* store(hash, nonce)
54
+ * yield* relayer.broadcast({ signed })
55
+ * // a transaction the node never sees stays `NotFound`: the timeout bounds the wait
56
+ * const status = yield* relayer.awaitConfirmation({ hash }).pipe(Effect.timeout("10 minutes"))
57
+ * if (status._tag === "Failed") {
58
+ * yield* Effect.logError(`reverted in block ${status.block}: ${status.reason}`)
59
+ * }
60
+ * })
61
+ * ```
62
+ *
63
+ * @since 0.2.0
64
+ */
65
+ import * as Context from "effect/Context"
66
+ import * as Effect from "effect/Effect"
67
+ import * as Layer from "effect/Layer"
68
+ import * as Schedule from "effect/Schedule"
69
+ import * as Schema from "effect/Schema"
70
+ import { hash as starknetHash } from "starknet"
71
+ import * as Confirmations from "./internal/confirmations.ts"
72
+ import { deployAddress, transactionHash } from "./internal/transactionHash.ts"
73
+ import type { StarknetAddress } from "./StarknetAddress.ts"
74
+ import { DEFAULT_POLL_INTERVAL } from "./StarknetIndexer.ts"
75
+ import * as StarknetNetwork from "./StarknetNetwork.ts"
76
+ import * as StarknetRpc from "./StarknetRpc.ts"
77
+ import { type StarknetSigner, StarknetSignerError, type StarknetUnsignedTransaction } from "./StarknetSigner.ts"
78
+ import type { StarknetResourceBounds, StarknetTransaction } from "./StarknetTransaction.ts"
79
+ import type { StarknetTransactionHash } from "./StarknetTransactionHash.ts"
80
+
81
+ /**
82
+ * Where a transaction stands, by `_tag`: see the module's table. `block` is the number of the accepted block holding
83
+ * it, and `reason` the node's revert message, `undefined` when the node gives none.
84
+ *
85
+ * @since 0.2.0
86
+ * @category models
87
+ */
88
+ export type StarknetTransactionStatus =
89
+ | { readonly _tag: "Pending" }
90
+ | { readonly _tag: "Included"; readonly block: bigint }
91
+ | { readonly _tag: "Confirmed"; readonly block: bigint }
92
+ | { readonly _tag: "Failed"; readonly block: bigint; readonly reason: string | undefined }
93
+ | { readonly _tag: "NotFound" }
94
+
95
+ /**
96
+ * One call of an `INVOKE` transaction: the `entrypoint` name of `contractAddress` and its calldata felts.
97
+ *
98
+ * @since 0.2.0
99
+ * @category models
100
+ */
101
+ export interface StarknetCall {
102
+ readonly contractAddress: StarknetAddress
103
+ readonly entrypoint: string
104
+ readonly calldata: ReadonlyArray<string>
105
+ }
106
+
107
+ /**
108
+ * A transaction signed by {@link StarknetRelayer}: `signed` is what `broadcast` takes, `hash` its transaction hash
109
+ * and `nonce` the nonce it uses.
110
+ *
111
+ * @since 0.2.0
112
+ * @category models
113
+ */
114
+ export interface StarknetSignedTransaction {
115
+ readonly hash: StarknetTransactionHash
116
+ readonly signed: StarknetTransaction
117
+ readonly nonce: bigint
118
+ }
119
+
120
+ /**
121
+ * The nonce is not the account's next one: it is already used, or too far ahead of it (`INVALID_TRANSACTION_NONCE`).
122
+ *
123
+ * @since 0.2.0
124
+ * @category reasons
125
+ */
126
+ export class InvalidNonce extends Schema.TaggedError<InvalidNonce>()("InvalidNonce", {}) {}
127
+
128
+ /**
129
+ * The account's STRK balance does not cover the resource bounds (`INSUFFICIENT_ACCOUNT_BALANCE`).
130
+ *
131
+ * @since 0.2.0
132
+ * @category reasons
133
+ */
134
+ export class InsufficientBalance extends Schema.TaggedError<InsufficientBalance>()("InsufficientBalance", {}) {}
135
+
136
+ /**
137
+ * The resource bounds are below what validating the transaction needs or below the current prices
138
+ * (`INSUFFICIENT_RESOURCES_FOR_VALIDATE`), or the fee is below the node's minimum (`FEE_BELOW_MINIMUM`).
139
+ *
140
+ * @since 0.2.0
141
+ * @category reasons
142
+ */
143
+ export class InsufficientResources extends Schema.TaggedError<InsufficientResources>()("InsufficientResources", {}) {}
144
+
145
+ /**
146
+ * The account contract refused the transaction, usually for its signature (`VALIDATION_FAILURE`).
147
+ *
148
+ * @since 0.2.0
149
+ * @category reasons
150
+ */
151
+ export class ValidationFailure extends Schema.TaggedError<ValidationFailure>()("ValidationFailure", {}) {}
152
+
153
+ /**
154
+ * The node's mempool holds another transaction at this nonce and the tip does not exceed its tip enough to replace it
155
+ * (`REPLACEMENT_TRANSACTION_UNDERPRICED`).
156
+ *
157
+ * @since 0.2.0
158
+ * @category reasons
159
+ */
160
+ export class ReplacementUnderpriced
161
+ extends Schema.TaggedError<ReplacementUnderpriced>()("ReplacementUnderpriced", {})
162
+ {}
163
+
164
+ /**
165
+ * Why a node refused a transaction, the `reason` of a {@link StarknetBroadcastError}, matched with
166
+ * `Effect.catchReason`.
167
+ *
168
+ * @since 0.2.0
169
+ * @category reasons
170
+ */
171
+ export const StarknetBroadcastReason = Schema.Union([
172
+ InvalidNonce,
173
+ InsufficientBalance,
174
+ InsufficientResources,
175
+ ValidationFailure,
176
+ ReplacementUnderpriced
177
+ ])
178
+
179
+ /**
180
+ * @since 0.2.0
181
+ * @category reasons
182
+ */
183
+ export type StarknetBroadcastReason = typeof StarknetBroadcastReason.Type
184
+
185
+ /**
186
+ * A node refused the transaction for a `reason` the sender can act on: `cause` is the
187
+ * {@link StarknetRpc.StarknetRpcError} holding the node's error code and message. Any other refusal stays a
188
+ * `StarknetRpcError`.
189
+ *
190
+ * @since 0.2.0
191
+ * @category errors
192
+ */
193
+ export class StarknetBroadcastError extends Schema.TaggedError<StarknetBroadcastError>()("StarknetBroadcastError", {
194
+ reason: StarknetBroadcastReason,
195
+ cause: Schema.Defect()
196
+ }) {}
197
+
198
+ /**
199
+ * @since 0.2.0
200
+ * @category services
201
+ */
202
+ export class StarknetRelayer extends Context.Service<StarknetRelayer, {
203
+ /**
204
+ * Signs an `INVOKE` running `calls` in order from the account at `signer.address`, without sending it. A missing
205
+ * `nonce` is the account's nonce at the pre-confirmed block, missing `resourceBounds` come from the layer's fee
206
+ * strategy over `starknet_estimateFee` (calls that revert fail with `Rejected`), and a missing `tip` is 0.
207
+ */
208
+ readonly sign: (options: {
209
+ readonly signer: StarknetSigner
210
+ readonly calls: ReadonlyArray<StarknetCall>
211
+ readonly nonce?: bigint | undefined
212
+ readonly resourceBounds?: StarknetResourceBounds | undefined
213
+ readonly tip?: bigint | undefined
214
+ }) => Effect.Effect<StarknetSignedTransaction, StarknetRpc.StarknetRpcError | StarknetSignerError>
215
+ /**
216
+ * Signs the `DEPLOY_ACCOUNT` of the signer's own account contract, without sending it: its nonce is 0. The address
217
+ * that `classHash`, `salt` and `constructorCalldata` deploy to must be `signer.address`, or it fails with a
218
+ * `StarknetSignerError`, and must hold STRK for the fee before the broadcast.
219
+ */
220
+ readonly signDeployAccount: (options: {
221
+ readonly signer: StarknetSigner
222
+ readonly classHash: string
223
+ readonly salt: string
224
+ readonly constructorCalldata: ReadonlyArray<string>
225
+ readonly resourceBounds?: StarknetResourceBounds | undefined
226
+ readonly tip?: bigint | undefined
227
+ }) => Effect.Effect<StarknetSignedTransaction, StarknetRpc.StarknetRpcError | StarknetSignerError>
228
+ /**
229
+ * Sends a signed transaction and returns its hash. Sending the same transaction again is safe: a node answering
230
+ * `DUPLICATE_TX`, or that the nonce is invalid while it knows this hash, is a success.
231
+ */
232
+ readonly broadcast: (options: {
233
+ readonly signed: StarknetTransaction
234
+ }) => Effect.Effect<StarknetTransactionHash, StarknetBroadcastError | StarknetRpc.StarknetRpcError>
235
+ /**
236
+ * The status of the transaction as the answering endpoint sees it. An endpoint behind the head answers `Pending` or
237
+ * `Included` for a transaction another one has in a confirmed block, and `NotFound` means that the last endpoint
238
+ * tried does not know it.
239
+ */
240
+ readonly fetchTransactionStatus: (options: {
241
+ readonly hash: StarknetTransactionHash
242
+ }) => Effect.Effect<StarknetTransactionStatus, StarknetRpc.StarknetRpcError>
243
+ /**
244
+ * Reads {@link fetchTransactionStatus} on `poll` (`Schedule.spaced(StarknetIndexer.DEFAULT_POLL_INTERVAL)` by
245
+ * default) until it is `Confirmed` or `Failed`, and returns it. `NotFound` keeps polling, so bound the wait with a
246
+ * timeout. A `poll` that ends first returns the last status read.
247
+ */
248
+ readonly awaitConfirmation: (options: {
249
+ readonly hash: StarknetTransactionHash
250
+ readonly poll?: Schedule.Schedule<unknown> | undefined
251
+ }) => Effect.Effect<StarknetTransactionStatus, StarknetRpc.StarknetRpcError>
252
+ }>()("@effect-blockchain/starknet/StarknetRelayer") {}
253
+
254
+ // `__validate__` and `__validate_deploy__` of an OpenZeppelin account, one Stark curve signature check, use 130,240 L2
255
+ // gas: the estimate is made with `SKIP_VALIDATE` and leaves them out
256
+ const VALIDATION_L2_GAS = BigInt(300_000)
257
+
258
+ const margin = (value: bigint) => value * BigInt(3) / BigInt(2)
259
+
260
+ /**
261
+ * The library's fee strategy: each resource is bounded by 1.5 times its estimated amount at 1.5 times its estimated
262
+ * price, which keeps the transaction includable while prices rise. The L2 gas amount first gains 300,000 for the
263
+ * account's validation, which the estimate leaves out: over twice what a single signature check uses.
264
+ *
265
+ * @since 0.2.0
266
+ * @category fees
267
+ */
268
+ export const defaultFees = (estimate: StarknetRpc.StarknetFeeEstimate): StarknetResourceBounds => ({
269
+ l1Gas: { maxAmount: margin(estimate.l1GasConsumed), maxPricePerUnit: margin(estimate.l1GasPrice) },
270
+ l1DataGas: { maxAmount: margin(estimate.l1DataGasConsumed), maxPricePerUnit: margin(estimate.l1DataGasPrice) },
271
+ l2Gas: {
272
+ maxAmount: margin(estimate.l2GasConsumed + VALIDATION_L2_GAS),
273
+ maxPricePerUnit: margin(estimate.l2GasPrice)
274
+ }
275
+ })
276
+
277
+ const NO_BOUND = { maxAmount: BigInt(0), maxPricePerUnit: BigInt(0) }
278
+
279
+ const toHex = (value: number) => `0x${value.toString(16)}`
280
+
281
+ // the `__execute__` calldata of a Cairo 1 account, an `Array<Call>` (SNIP-6)
282
+ const executeCalldata = (calls: ReadonlyArray<StarknetCall>): ReadonlyArray<string> => [
283
+ toHex(calls.length),
284
+ ...calls.flatMap((call) => [
285
+ call.contractAddress,
286
+ starknetHash.getSelectorFromName(call.entrypoint),
287
+ toHex(call.calldata.length),
288
+ ...call.calldata
289
+ ])
290
+ ]
291
+
292
+ // error codes of `starknet_addInvokeTransaction` and `starknet_addDeployAccountTransaction` in the Starknet JSON-RPC
293
+ // spec v0.9 (starknet_write_api.json)
294
+ const DUPLICATE_TX = 59
295
+ const refusals: ReadonlyMap<number | undefined, () => StarknetBroadcastReason> = new Map<
296
+ number,
297
+ () => StarknetBroadcastReason
298
+ >([
299
+ [52, () => new InvalidNonce()],
300
+ [53, () => new InsufficientResources()],
301
+ [54, () => new InsufficientBalance()],
302
+ [55, () => new ValidationFailure()],
303
+ [64, () => new ReplacementUnderpriced()],
304
+ [65, () => new InsufficientResources()]
305
+ ])
306
+
307
+ // after a fallback, the error holds each endpoint's error
308
+ const codesOf = (error: StarknetRpc.StarknetRpcError): ReadonlyArray<number | undefined> =>
309
+ error.cause instanceof AggregateError
310
+ ? error.cause.errors.map((each) => each instanceof StarknetRpc.StarknetRpcError ? each.code : undefined)
311
+ : [error.code]
312
+
313
+ const toSignerError = (cause: unknown) => new StarknetSignerError({ cause })
314
+
315
+ /**
316
+ * Builds a {@link StarknetRelayer} over the provided {@link StarknetRpc.StarknetRpc}. `confirmations` overrides the
317
+ * network's default, as in `StarknetIndexer.layer`: both agree on the last confirmed block. `fees` (default
318
+ * {@link defaultFees}) bounds the resources of the transactions signed without explicit bounds.
319
+ *
320
+ * @since 0.2.0
321
+ * @category layers
322
+ */
323
+ export const layer = (options: {
324
+ readonly confirmations?: number | undefined
325
+ readonly fees?: ((estimate: StarknetRpc.StarknetFeeEstimate) => StarknetResourceBounds) | undefined
326
+ } = {}): Layer.Layer<StarknetRelayer, never, StarknetRpc.StarknetRpc> =>
327
+ Layer.effect(
328
+ StarknetRelayer,
329
+ Effect.gen(function*() {
330
+ const rpc = yield* StarknetRpc.StarknetRpc
331
+ const chainId = StarknetNetwork.toChainId(rpc.network)
332
+ const finish = Effect.fnUntraced(function*(
333
+ signer: StarknetSigner,
334
+ draft: StarknetUnsignedTransaction,
335
+ given: StarknetResourceBounds | undefined
336
+ ) {
337
+ const resourceBounds = given ?? (yield* Effect.map(
338
+ rpc.estimateFee({
339
+ transactions: [{ ...draft, signature: [] }],
340
+ skipValidate: true,
341
+ blockTag: "pre_confirmed"
342
+ }),
343
+ ([estimate]) => (options.fees ?? defaultFees)(estimate)
344
+ ))
345
+ const unsigned = { ...draft, resourceBounds }
346
+ const hash = yield* Effect.try({ try: () => transactionHash(unsigned), catch: toSignerError })
347
+ const signature = yield* signer.signTransaction(unsigned)
348
+ return { hash, signed: { ...unsigned, signature }, nonce: unsigned.nonce }
349
+ })
350
+ const unbounded = { resourceBounds: { l1Gas: NO_BOUND, l1DataGas: NO_BOUND, l2Gas: NO_BOUND } }
351
+ const sign = Effect.fn("StarknetRelayer.sign")(
352
+ function*({ calls, nonce, resourceBounds, signer, tip }: Parameters<StarknetRelayer["Service"]["sign"]>[0]) {
353
+ return yield* finish(signer, {
354
+ ...unbounded,
355
+ type: "INVOKE",
356
+ chainId,
357
+ senderAddress: signer.address,
358
+ calldata: executeCalldata(calls),
359
+ nonce: nonce ?? (yield* rpc.getNonce({ address: signer.address, blockTag: "pre_confirmed" })),
360
+ tip: tip ?? BigInt(0)
361
+ }, resourceBounds)
362
+ }
363
+ )
364
+ const signDeployAccount = Effect.fn("StarknetRelayer.signDeployAccount")(
365
+ function*(
366
+ { classHash, constructorCalldata, resourceBounds, salt, signer, tip }: Parameters<
367
+ StarknetRelayer["Service"]["signDeployAccount"]
368
+ >[0]
369
+ ) {
370
+ const draft = {
371
+ ...unbounded,
372
+ type: "DEPLOY_ACCOUNT" as const,
373
+ chainId,
374
+ classHash,
375
+ contractAddressSalt: salt,
376
+ constructorCalldata,
377
+ nonce: BigInt(0),
378
+ tip: tip ?? BigInt(0)
379
+ }
380
+ const address = yield* Effect.try({ try: () => deployAddress(draft), catch: toSignerError })
381
+ if (address !== signer.address) {
382
+ return yield* toSignerError(new Error(`the account deploys at ${address}, the signer is ${signer.address}`))
383
+ }
384
+ return yield* finish(signer, draft, resourceBounds)
385
+ }
386
+ )
387
+ const broadcast = Effect.fn("StarknetRelayer.broadcast")(
388
+ function*({ signed }: { readonly signed: StarknetTransaction }) {
389
+ const sent = yield* Effect.result(
390
+ signed.type === "INVOKE"
391
+ ? rpc.addInvokeTransaction({ transaction: signed })
392
+ : Effect.map(rpc.addDeployAccountTransaction({ transaction: signed }), (added) => added.transactionHash)
393
+ )
394
+ if (sent._tag === "Success") return sent.success
395
+ const cause = sent.failure
396
+ const codes = codesOf(cause)
397
+ if (codes.includes(DUPLICATE_TX)) return transactionHash(signed)
398
+ const reason = refusals.get(codes.find((code) => refusals.has(code)))?.()
399
+ if (reason === undefined) return yield* cause
400
+ if (reason._tag === "InvalidNonce") {
401
+ // a node that has this transaction in a block answers that its nonce is used
402
+ const hash = transactionHash(signed)
403
+ if ((yield* rpc.getTransactionStatus({ transactionHash: hash })) !== null) return hash
404
+ }
405
+ return yield* new StarknetBroadcastError({ reason, cause })
406
+ }
407
+ )
408
+ const fetchTransactionStatus = Effect.fn("StarknetRelayer.fetchTransactionStatus")(
409
+ function*({ hash }: { readonly hash: StarknetTransactionHash }) {
410
+ const status = yield* rpc.getTransactionStatus({ transactionHash: hash })
411
+ if (status === null) return { _tag: "NotFound" } as const
412
+ if (status.finalityStatus !== "ACCEPTED_ON_L2" && status.finalityStatus !== "ACCEPTED_ON_L1") {
413
+ return { _tag: "Pending" } as const
414
+ }
415
+ // the status does not carry the block number
416
+ const { blockNumber: block } = yield* rpc.getTransactionReceipt({ transactionHash: hash })
417
+ // read after the receipt: a head older than the receipt's block could only delay `Confirmed`
418
+ const confirmed = yield* Confirmations.lastConfirmedBlock(rpc, options.confirmations)
419
+ if (block > confirmed) return { _tag: "Included", block } as const
420
+ return status.executionStatus === "REVERTED"
421
+ ? { _tag: "Failed", block, reason: status.failureReason } as const
422
+ : { _tag: "Confirmed", block } as const
423
+ }
424
+ )
425
+ return StarknetRelayer.of({
426
+ sign,
427
+ signDeployAccount,
428
+ broadcast,
429
+ fetchTransactionStatus,
430
+ awaitConfirmation: ({ hash, poll = Schedule.spaced(DEFAULT_POLL_INTERVAL) }) =>
431
+ fetchTransactionStatus({ hash }).pipe(
432
+ Effect.repeat({ schedule: poll, until: ({ _tag }) => _tag === "Confirmed" || _tag === "Failed" }),
433
+ Effect.withSpan("StarknetRelayer.awaitConfirmation")
434
+ )
435
+ })
436
+ })
437
+ )