@effect-blockchain/starknet 0.1.0 → 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 (49) hide show
  1. package/dist/StarknetIndexer.d.ts +40 -2
  2. package/dist/StarknetIndexer.d.ts.map +1 -1
  3. package/dist/StarknetIndexer.js +89 -14
  4. package/dist/StarknetIndexer.js.map +1 -1
  5. package/dist/StarknetNetwork.d.ts +9 -0
  6. package/dist/StarknetNetwork.d.ts.map +1 -1
  7. package/dist/StarknetNetwork.js +9 -0
  8. package/dist/StarknetNetwork.js.map +1 -1
  9. package/dist/StarknetRelayer.d.ts +273 -0
  10. package/dist/StarknetRelayer.d.ts.map +1 -0
  11. package/dist/StarknetRelayer.js +352 -0
  12. package/dist/StarknetRelayer.js.map +1 -0
  13. package/dist/StarknetRpc.d.ts +107 -5
  14. package/dist/StarknetRpc.d.ts.map +1 -1
  15. package/dist/StarknetRpc.js +83 -5
  16. package/dist/StarknetRpc.js.map +1 -1
  17. package/dist/StarknetSigner.d.ts +75 -0
  18. package/dist/StarknetSigner.d.ts.map +1 -0
  19. package/dist/StarknetSigner.js +84 -0
  20. package/dist/StarknetSigner.js.map +1 -0
  21. package/dist/StarknetTransaction.d.ts +74 -0
  22. package/dist/StarknetTransaction.d.ts.map +1 -0
  23. package/dist/StarknetTransaction.js +2 -0
  24. package/dist/StarknetTransaction.js.map +1 -0
  25. package/dist/index.d.ts +12 -0
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +12 -0
  28. package/dist/index.js.map +1 -1
  29. package/dist/internal/confirmations.d.ts +2 -0
  30. package/dist/internal/confirmations.d.ts.map +1 -0
  31. package/dist/internal/confirmations.js +13 -0
  32. package/dist/internal/confirmations.js.map +1 -0
  33. package/dist/internal/rpcMethods.js +135 -0
  34. package/dist/internal/rpcMethods.js.map +1 -1
  35. package/dist/internal/transactionHash.d.ts +2 -0
  36. package/dist/internal/transactionHash.d.ts.map +1 -0
  37. package/dist/internal/transactionHash.js +60 -0
  38. package/dist/internal/transactionHash.js.map +1 -0
  39. package/package.json +1 -1
  40. package/src/StarknetIndexer.ts +141 -26
  41. package/src/StarknetNetwork.ts +12 -0
  42. package/src/StarknetRelayer.ts +437 -0
  43. package/src/StarknetRpc.ts +198 -6
  44. package/src/StarknetSigner.ts +115 -0
  45. package/src/StarknetTransaction.ts +68 -0
  46. package/src/index.ts +15 -0
  47. package/src/internal/confirmations.ts +17 -0
  48. package/src/internal/rpcMethods.ts +136 -0
  49. package/src/internal/transactionHash.ts +64 -0
@@ -0,0 +1,352 @@
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.js";
72
+ import { deployAddress, transactionHash } from "./internal/transactionHash.js";
73
+ import { DEFAULT_POLL_INTERVAL } from "./StarknetIndexer.js";
74
+ import * as StarknetNetwork from "./StarknetNetwork.js";
75
+ import * as StarknetRpc from "./StarknetRpc.js";
76
+ import { StarknetSignerError } from "./StarknetSigner.js";
77
+ /**
78
+ * The nonce is not the account's next one: it is already used, or too far ahead of it (`INVALID_TRANSACTION_NONCE`).
79
+ *
80
+ * @since 0.2.0
81
+ * @category reasons
82
+ */
83
+ export class InvalidNonce extends /*#__PURE__*/Schema.TaggedError()("InvalidNonce", {}) {}
84
+ /**
85
+ * The account's STRK balance does not cover the resource bounds (`INSUFFICIENT_ACCOUNT_BALANCE`).
86
+ *
87
+ * @since 0.2.0
88
+ * @category reasons
89
+ */
90
+ export class InsufficientBalance extends /*#__PURE__*/Schema.TaggedError()("InsufficientBalance", {}) {}
91
+ /**
92
+ * The resource bounds are below what validating the transaction needs or below the current prices
93
+ * (`INSUFFICIENT_RESOURCES_FOR_VALIDATE`), or the fee is below the node's minimum (`FEE_BELOW_MINIMUM`).
94
+ *
95
+ * @since 0.2.0
96
+ * @category reasons
97
+ */
98
+ export class InsufficientResources extends /*#__PURE__*/Schema.TaggedError()("InsufficientResources", {}) {}
99
+ /**
100
+ * The account contract refused the transaction, usually for its signature (`VALIDATION_FAILURE`).
101
+ *
102
+ * @since 0.2.0
103
+ * @category reasons
104
+ */
105
+ export class ValidationFailure extends /*#__PURE__*/Schema.TaggedError()("ValidationFailure", {}) {}
106
+ /**
107
+ * The node's mempool holds another transaction at this nonce and the tip does not exceed its tip enough to replace it
108
+ * (`REPLACEMENT_TRANSACTION_UNDERPRICED`).
109
+ *
110
+ * @since 0.2.0
111
+ * @category reasons
112
+ */
113
+ export class ReplacementUnderpriced extends /*#__PURE__*/Schema.TaggedError()("ReplacementUnderpriced", {}) {}
114
+ /**
115
+ * Why a node refused a transaction, the `reason` of a {@link StarknetBroadcastError}, matched with
116
+ * `Effect.catchReason`.
117
+ *
118
+ * @since 0.2.0
119
+ * @category reasons
120
+ */
121
+ export const StarknetBroadcastReason = /*#__PURE__*/Schema.Union([InvalidNonce, InsufficientBalance, InsufficientResources, ValidationFailure, ReplacementUnderpriced]);
122
+ /**
123
+ * A node refused the transaction for a `reason` the sender can act on: `cause` is the
124
+ * {@link StarknetRpc.StarknetRpcError} holding the node's error code and message. Any other refusal stays a
125
+ * `StarknetRpcError`.
126
+ *
127
+ * @since 0.2.0
128
+ * @category errors
129
+ */
130
+ export class StarknetBroadcastError extends /*#__PURE__*/Schema.TaggedError()("StarknetBroadcastError", {
131
+ reason: StarknetBroadcastReason,
132
+ cause: /*#__PURE__*/Schema.Defect()
133
+ }) {}
134
+ /**
135
+ * @since 0.2.0
136
+ * @category services
137
+ */
138
+ export class StarknetRelayer extends /*#__PURE__*/Context.Service()("@effect-blockchain/starknet/StarknetRelayer") {}
139
+ // `__validate__` and `__validate_deploy__` of an OpenZeppelin account, one Stark curve signature check, use 130,240 L2
140
+ // gas: the estimate is made with `SKIP_VALIDATE` and leaves them out
141
+ const VALIDATION_L2_GAS = /*#__PURE__*/BigInt(300_000);
142
+ const margin = value => value * BigInt(3) / BigInt(2);
143
+ /**
144
+ * The library's fee strategy: each resource is bounded by 1.5 times its estimated amount at 1.5 times its estimated
145
+ * price, which keeps the transaction includable while prices rise. The L2 gas amount first gains 300,000 for the
146
+ * account's validation, which the estimate leaves out: over twice what a single signature check uses.
147
+ *
148
+ * @since 0.2.0
149
+ * @category fees
150
+ */
151
+ export const defaultFees = estimate => ({
152
+ l1Gas: {
153
+ maxAmount: margin(estimate.l1GasConsumed),
154
+ maxPricePerUnit: margin(estimate.l1GasPrice)
155
+ },
156
+ l1DataGas: {
157
+ maxAmount: margin(estimate.l1DataGasConsumed),
158
+ maxPricePerUnit: margin(estimate.l1DataGasPrice)
159
+ },
160
+ l2Gas: {
161
+ maxAmount: margin(estimate.l2GasConsumed + VALIDATION_L2_GAS),
162
+ maxPricePerUnit: margin(estimate.l2GasPrice)
163
+ }
164
+ });
165
+ const NO_BOUND = {
166
+ maxAmount: /*#__PURE__*/BigInt(0),
167
+ maxPricePerUnit: /*#__PURE__*/BigInt(0)
168
+ };
169
+ const toHex = value => `0x${value.toString(16)}`;
170
+ // the `__execute__` calldata of a Cairo 1 account, an `Array<Call>` (SNIP-6)
171
+ const executeCalldata = calls => [toHex(calls.length), ...calls.flatMap(call => [call.contractAddress, starknetHash.getSelectorFromName(call.entrypoint), toHex(call.calldata.length), ...call.calldata])];
172
+ // error codes of `starknet_addInvokeTransaction` and `starknet_addDeployAccountTransaction` in the Starknet JSON-RPC
173
+ // spec v0.9 (starknet_write_api.json)
174
+ const DUPLICATE_TX = 59;
175
+ const refusals = /*#__PURE__*/new Map([[52, () => new InvalidNonce()], [53, () => new InsufficientResources()], [54, () => new InsufficientBalance()], [55, () => new ValidationFailure()], [64, () => new ReplacementUnderpriced()], [65, () => new InsufficientResources()]]);
176
+ // after a fallback, the error holds each endpoint's error
177
+ const codesOf = error => error.cause instanceof AggregateError ? error.cause.errors.map(each => each instanceof StarknetRpc.StarknetRpcError ? each.code : undefined) : [error.code];
178
+ const toSignerError = cause => new StarknetSignerError({
179
+ cause
180
+ });
181
+ /**
182
+ * Builds a {@link StarknetRelayer} over the provided {@link StarknetRpc.StarknetRpc}. `confirmations` overrides the
183
+ * network's default, as in `StarknetIndexer.layer`: both agree on the last confirmed block. `fees` (default
184
+ * {@link defaultFees}) bounds the resources of the transactions signed without explicit bounds.
185
+ *
186
+ * @since 0.2.0
187
+ * @category layers
188
+ */
189
+ export const layer = (options = {}) => Layer.effect(StarknetRelayer, Effect.gen(function* () {
190
+ const rpc = yield* StarknetRpc.StarknetRpc;
191
+ const chainId = StarknetNetwork.toChainId(rpc.network);
192
+ const finish = Effect.fnUntraced(function* (signer, draft, given) {
193
+ const resourceBounds = given ?? (yield* Effect.map(rpc.estimateFee({
194
+ transactions: [{
195
+ ...draft,
196
+ signature: []
197
+ }],
198
+ skipValidate: true,
199
+ blockTag: "pre_confirmed"
200
+ }), ([estimate]) => (options.fees ?? defaultFees)(estimate)));
201
+ const unsigned = {
202
+ ...draft,
203
+ resourceBounds
204
+ };
205
+ const hash = yield* Effect.try({
206
+ try: () => transactionHash(unsigned),
207
+ catch: toSignerError
208
+ });
209
+ const signature = yield* signer.signTransaction(unsigned);
210
+ return {
211
+ hash,
212
+ signed: {
213
+ ...unsigned,
214
+ signature
215
+ },
216
+ nonce: unsigned.nonce
217
+ };
218
+ });
219
+ const unbounded = {
220
+ resourceBounds: {
221
+ l1Gas: NO_BOUND,
222
+ l1DataGas: NO_BOUND,
223
+ l2Gas: NO_BOUND
224
+ }
225
+ };
226
+ const sign = Effect.fn("StarknetRelayer.sign")(function* ({
227
+ calls,
228
+ nonce,
229
+ resourceBounds,
230
+ signer,
231
+ tip
232
+ }) {
233
+ return yield* finish(signer, {
234
+ ...unbounded,
235
+ type: "INVOKE",
236
+ chainId,
237
+ senderAddress: signer.address,
238
+ calldata: executeCalldata(calls),
239
+ nonce: nonce ?? (yield* rpc.getNonce({
240
+ address: signer.address,
241
+ blockTag: "pre_confirmed"
242
+ })),
243
+ tip: tip ?? BigInt(0)
244
+ }, resourceBounds);
245
+ });
246
+ const signDeployAccount = Effect.fn("StarknetRelayer.signDeployAccount")(function* ({
247
+ classHash,
248
+ constructorCalldata,
249
+ resourceBounds,
250
+ salt,
251
+ signer,
252
+ tip
253
+ }) {
254
+ const draft = {
255
+ ...unbounded,
256
+ type: "DEPLOY_ACCOUNT",
257
+ chainId,
258
+ classHash,
259
+ contractAddressSalt: salt,
260
+ constructorCalldata,
261
+ nonce: BigInt(0),
262
+ tip: tip ?? BigInt(0)
263
+ };
264
+ const address = yield* Effect.try({
265
+ try: () => deployAddress(draft),
266
+ catch: toSignerError
267
+ });
268
+ if (address !== signer.address) {
269
+ return yield* toSignerError(new Error(`the account deploys at ${address}, the signer is ${signer.address}`));
270
+ }
271
+ return yield* finish(signer, draft, resourceBounds);
272
+ });
273
+ const broadcast = Effect.fn("StarknetRelayer.broadcast")(function* ({
274
+ signed
275
+ }) {
276
+ const sent = yield* Effect.result(signed.type === "INVOKE" ? rpc.addInvokeTransaction({
277
+ transaction: signed
278
+ }) : Effect.map(rpc.addDeployAccountTransaction({
279
+ transaction: signed
280
+ }), added => added.transactionHash));
281
+ if (sent._tag === "Success") return sent.success;
282
+ const cause = sent.failure;
283
+ const codes = codesOf(cause);
284
+ if (codes.includes(DUPLICATE_TX)) return transactionHash(signed);
285
+ const reason = refusals.get(codes.find(code => refusals.has(code)))?.();
286
+ if (reason === undefined) return yield* cause;
287
+ if (reason._tag === "InvalidNonce") {
288
+ // a node that has this transaction in a block answers that its nonce is used
289
+ const hash = transactionHash(signed);
290
+ if ((yield* rpc.getTransactionStatus({
291
+ transactionHash: hash
292
+ })) !== null) return hash;
293
+ }
294
+ return yield* new StarknetBroadcastError({
295
+ reason,
296
+ cause
297
+ });
298
+ });
299
+ const fetchTransactionStatus = Effect.fn("StarknetRelayer.fetchTransactionStatus")(function* ({
300
+ hash
301
+ }) {
302
+ const status = yield* rpc.getTransactionStatus({
303
+ transactionHash: hash
304
+ });
305
+ if (status === null) return {
306
+ _tag: "NotFound"
307
+ };
308
+ if (status.finalityStatus !== "ACCEPTED_ON_L2" && status.finalityStatus !== "ACCEPTED_ON_L1") {
309
+ return {
310
+ _tag: "Pending"
311
+ };
312
+ }
313
+ // the status does not carry the block number
314
+ const {
315
+ blockNumber: block
316
+ } = yield* rpc.getTransactionReceipt({
317
+ transactionHash: hash
318
+ });
319
+ // read after the receipt: a head older than the receipt's block could only delay `Confirmed`
320
+ const confirmed = yield* Confirmations.lastConfirmedBlock(rpc, options.confirmations);
321
+ if (block > confirmed) return {
322
+ _tag: "Included",
323
+ block
324
+ };
325
+ return status.executionStatus === "REVERTED" ? {
326
+ _tag: "Failed",
327
+ block,
328
+ reason: status.failureReason
329
+ } : {
330
+ _tag: "Confirmed",
331
+ block
332
+ };
333
+ });
334
+ return StarknetRelayer.of({
335
+ sign,
336
+ signDeployAccount,
337
+ broadcast,
338
+ fetchTransactionStatus,
339
+ awaitConfirmation: ({
340
+ hash,
341
+ poll = Schedule.spaced(DEFAULT_POLL_INTERVAL)
342
+ }) => fetchTransactionStatus({
343
+ hash
344
+ }).pipe(Effect.repeat({
345
+ schedule: poll,
346
+ until: ({
347
+ _tag
348
+ }) => _tag === "Confirmed" || _tag === "Failed"
349
+ }), Effect.withSpan("StarknetRelayer.awaitConfirmation"))
350
+ });
351
+ }));
352
+ //# sourceMappingURL=StarknetRelayer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"StarknetRelayer.js","names":[],"sources":["../src/StarknetRelayer.ts"],"sourcesContent":[null],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,OAAO,KAAK,OAAO,MAAM,gBAAgB;AACzC,OAAO,KAAK,MAAM,MAAM,eAAe;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc;AACrC,OAAO,KAAK,QAAQ,MAAM,iBAAiB;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe;AACvC,SAAS,IAAI,IAAI,YAAY,QAAQ,UAAU;AAC/C,OAAO,KAAK,aAAa,MAAM,6BAA6B;AAC5D,SAAS,aAAa,EAAE,eAAe,QAAQ,+BAA+B;AAE9E,SAAS,qBAAqB,QAAQ,sBAAsB;AAC5D,OAAO,KAAK,eAAe,MAAM,sBAAsB;AACvD,OAAO,KAAK,WAAW,MAAM,kBAAkB;AAC/C,SAA8B,mBAAmB,QAA0C,qBAAqB;AA2ChH;;;;;;AAMA,OAAM,MAA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EAAE,WAAW;MAAE;IAAK,CAAW;EAC3C,CAAC,CACF;EACD,OAAO,eAAe,CAAC,EAAE,CAAC;IACxB,IAAI;IACJ,iBAAiB;IACjB,SAAS;IACT,sBAAsB;IACtB,iBAAiB,EAAE,CAAC;MAAE,IAAI;MAAE,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,qBAAqB;IAAC,CAAE,KACzE,sBAAsB,CAAC;MAAE;IAAI,CAAE,CAAC,CAAC,IAAI,CACnC,MAAM,CAAC,MAAM,CAAC;MAAE,QAAQ,EAAE,IAAI;MAAE,KAAK,EAAE,CAAC;QAAE;MAAI,CAAE,KAAK,IAAI,KAAK,WAAW,IAAI,IAAI,KAAK;IAAQ,CAAE,CAAC,EACjG,MAAM,CAAC,QAAQ,CAAC,mCAAmC,CAAC;GAEzD,CAAC;AACJ,CAAC,CAAC,CACH","ignoreList":[]}
@@ -1,10 +1,11 @@
1
1
  /**
2
- * Typed, read-only Starknet JSON-RPC methods over an ordered list of endpoints with fallback.
2
+ * Typed Starknet JSON-RPC methods over an ordered list of endpoints with fallback.
3
3
  *
4
4
  * A call starts at the first endpoint and moves to the next one on failure, except on `WrongNetwork`. Each endpoint
5
- * is checked once to serve the configured network (`starknet_chainId`). Every method is a read, so retries and
6
- * fallback are safe. Methods are named after the JSON-RPC method without its namespace (`starknet_getEvents` is
7
- * `getEvents`). A `getEvents` page cursor is only sent to the endpoint that issued it, with no fallback.
5
+ * is checked once to serve the configured network (`starknet_chainId`). Every method but `addInvokeTransaction`
6
+ * and `addDeployAccountTransaction` is a read, so retries and fallback are safe; these two document their own case.
7
+ * Methods are named after the JSON-RPC method without its namespace (`starknet_getEvents` is `getEvents`). A
8
+ * `getEvents` page cursor is only sent to the endpoint that issued it, with no fallback.
8
9
  *
9
10
  * @example
10
11
  * ```ts
@@ -32,7 +33,7 @@
32
33
  * @since 0.1.0
33
34
  */
34
35
  import * as JsonRpc from "@effect-blockchain/core/JsonRpc";
35
- import type * as Arr from "effect/Array";
36
+ import * as Arr from "effect/Array";
36
37
  import * as Config from "effect/Config";
37
38
  import * as Context from "effect/Context";
38
39
  import type * as Duration from "effect/Duration";
@@ -45,6 +46,7 @@ import type { StarknetAddress } from "./StarknetAddress.ts";
45
46
  import type { StarknetBlock } from "./StarknetBlock.ts";
46
47
  import type { StarknetEvent } from "./StarknetEvent.ts";
47
48
  import * as StarknetNetwork from "./StarknetNetwork.ts";
49
+ import type { StarknetDeployAccountTransaction, StarknetInvokeTransaction, StarknetTransaction } from "./StarknetTransaction.ts";
48
50
  import type { StarknetTransactionHash } from "./StarknetTransactionHash.ts";
49
51
  /**
50
52
  * A JSON-RPC endpoint. The `name` is shown in errors and spans, the `url` is never logged.
@@ -137,6 +139,42 @@ export interface StarknetTransactionReceipt {
137
139
  readonly blockHash: string;
138
140
  readonly events: ReadonlyArray<Pick<StarknetEvent, "fromAddress" | "keys" | "data">>;
139
141
  }
142
+ /**
143
+ * The `starknet_getTransactionStatus` result of the JSON-RPC spec v0.9. `executionStatus` is absent until the
144
+ * transaction is executed (`RECEIVED`, `CANDIDATE`), and `failureReason` is the node's revert message of a `REVERTED`
145
+ * transaction.
146
+ *
147
+ * @since 0.2.0
148
+ * @category models
149
+ */
150
+ export interface StarknetTransactionStatusResult {
151
+ readonly finalityStatus: "RECEIVED" | "CANDIDATE" | "PRE_CONFIRMED" | "ACCEPTED_ON_L2" | "ACCEPTED_ON_L1";
152
+ readonly executionStatus?: "SUCCEEDED" | "REVERTED" | undefined;
153
+ readonly failureReason?: string | undefined;
154
+ }
155
+ /**
156
+ * The block a state read is made at: the latest accepted block, or the pre-confirmed block being built on top of it.
157
+ *
158
+ * @since 0.2.0
159
+ * @category models
160
+ */
161
+ export type StarknetBlockTag = "latest" | "pre_confirmed";
162
+ /**
163
+ * One `starknet_estimateFee` result: the amount of each resource a transaction consumes and its price, in FRI (10^-18
164
+ * STRK) per unit. `overallFee` is their total.
165
+ *
166
+ * @since 0.2.0
167
+ * @category models
168
+ */
169
+ export interface StarknetFeeEstimate {
170
+ readonly l1GasConsumed: bigint;
171
+ readonly l1GasPrice: bigint;
172
+ readonly l1DataGasConsumed: bigint;
173
+ readonly l1DataGasPrice: bigint;
174
+ readonly l2GasConsumed: bigint;
175
+ readonly l2GasPrice: bigint;
176
+ readonly overallFee: bigint;
177
+ }
140
178
  declare const StarknetRpc_base: Context.ServiceClass<StarknetRpc, "@effect-blockchain/starknet/StarknetRpc", {
141
179
  readonly network: StarknetNetwork.StarknetNetwork;
142
180
  /** `starknet_chainId`, verified against `network` once per endpoint then served from that check. */
@@ -156,10 +194,74 @@ declare const StarknetRpc_base: Context.ServiceClass<StarknetRpc, "@effect-block
156
194
  * out-of-filter event fails with `InvalidResponse`, and an empty range returns no events.
157
195
  */
158
196
  readonly getEvents: (filter: StarknetEventsFilter) => Effect.Effect<StarknetEventsPage, StarknetRpcError>;
197
+ /**
198
+ * `starknet_call`, the raw felts a view function returns at the end of `blockNumber`, only answered by an endpoint
199
+ * whose head has reached `blockNumber`.
200
+ */
201
+ readonly call: (options: {
202
+ readonly contractAddress: StarknetAddress;
203
+ readonly entryPointSelector: string;
204
+ readonly calldata: ReadonlyArray<string>;
205
+ readonly blockNumber: bigint;
206
+ }) => Effect.Effect<ReadonlyArray<string>, StarknetRpcError>;
159
207
  /** `starknet_getTransactionReceipt`. A pre-confirmed receipt fails with `InvalidResponse`. */
160
208
  readonly getTransactionReceipt: (options: {
161
209
  readonly transactionHash: StarknetTransactionHash;
162
210
  }) => Effect.Effect<StarknetTransactionReceipt, StarknetRpcError>;
211
+ /**
212
+ * `starknet_getTransactionStatus`, `null` when the last endpoint tried answers `TXN_HASH_NOT_FOUND` (29): an endpoint
213
+ * that does not know the transaction falls back to the next one first.
214
+ */
215
+ readonly getTransactionStatus: (options: {
216
+ readonly transactionHash: StarknetTransactionHash;
217
+ }) => Effect.Effect<StarknetTransactionStatusResult | null, StarknetRpcError>;
218
+ /**
219
+ * `starknet_getNonce`: the nonce of the next transaction of the account at `address`. `pre_confirmed` counts the
220
+ * transactions of the block being built, not the ones still waiting in the mempool. An address without a contract
221
+ * is `Rejected` with the code 20 (`CONTRACT_NOT_FOUND`).
222
+ *
223
+ * @since 0.2.0
224
+ */
225
+ readonly getNonce: (options: {
226
+ readonly address: StarknetAddress;
227
+ readonly blockTag: StarknetBlockTag;
228
+ }) => Effect.Effect<bigint, StarknetRpcError>;
229
+ /**
230
+ * `starknet_estimateFee`: one estimate per transaction, each executed on top of the previous ones at `blockTag`
231
+ * (a reply without an estimate is an `InvalidResponse`).
232
+ * `skipValidate` sends the `SKIP_VALIDATE` flag, which accepts unsigned transactions. A transaction that fails is
233
+ * `Rejected` with the code 41 (`TRANSACTION_EXECUTION_ERROR`) and the node's message in `cause`.
234
+ *
235
+ * @since 0.2.0
236
+ */
237
+ readonly estimateFee: (options: {
238
+ readonly transactions: Arr.NonEmptyReadonlyArray<StarknetTransaction>;
239
+ readonly skipValidate?: boolean | undefined;
240
+ readonly blockTag: StarknetBlockTag;
241
+ }) => Effect.Effect<Arr.NonEmptyReadonlyArray<StarknetFeeEstimate>, StarknetRpcError>;
242
+ /**
243
+ * `starknet_addInvokeTransaction`: submits a signed `INVOKE` transaction and returns its hash. A retry or a fallback
244
+ * sends the same transaction, so it never creates a second one, but a node that already has it refuses the second
245
+ * copy. A refusal (`DUPLICATE_TX`, `INVALID_TRANSACTION_NONCE`, `INSUFFICIENT_ACCOUNT_BALANCE`...) is `Rejected`,
246
+ * with the spec's error code as `code`.
247
+ *
248
+ * @since 0.2.0
249
+ */
250
+ readonly addInvokeTransaction: (options: {
251
+ readonly transaction: StarknetInvokeTransaction;
252
+ }) => Effect.Effect<StarknetTransactionHash, StarknetRpcError>;
253
+ /**
254
+ * `starknet_addDeployAccountTransaction`: submits a signed `DEPLOY_ACCOUNT` transaction and returns its hash and
255
+ * the address of the account. Retries, fallback and refusals are those of `addInvokeTransaction`.
256
+ *
257
+ * @since 0.2.0
258
+ */
259
+ readonly addDeployAccountTransaction: (options: {
260
+ readonly transaction: StarknetDeployAccountTransaction;
261
+ }) => Effect.Effect<{
262
+ readonly transactionHash: StarknetTransactionHash;
263
+ readonly contractAddress: StarknetAddress;
264
+ }, StarknetRpcError>;
163
265
  }>;
164
266
  /**
165
267
  * @since 0.1.0
@@ -1 +1 @@
1
- {"version":3,"file":"StarknetRpc.d.ts","sourceRoot":"","sources":["../src/StarknetRpc.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,OAAO,KAAK,OAAO,MAAM,iCAAiC,CAAA;AAC1D,OAAO,KAAK,KAAK,GAAG,MAAM,cAAc,CAAA;AACxC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAA;AACzC,OAAO,KAAK,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAChD,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,UAAU,MAAM,wBAAwB,CAAA;AACzD,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAEhD,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AAEvC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAA;AAC3D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AACvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AACvD,OAAO,KAAK,eAAe,MAAM,sBAAsB,CAAA;AACvD,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAA;AAE3E;;;;;GAKG;AACH,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,GAAG,EAAE,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAA;CACxC;;;;;;;;AAED;;;;;;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QAAQ,CAAC,eAAe,EAAE,eAAe,CAAA;KAAE,EAChG,gBAAgB,CACjB;;AA1FH;;;GAGG;AACH,qBAAa,WAAY,SAAQ,gBAuFc;CAAG;AAoDlD;;;;;;;GAOG;AACH,eAAO,MAAM,KAAK,YAAa;IAC7B,QAAQ,CAAC,OAAO,EAAE,eAAe,CAAC,eAAe,CAAA;IACjD,QAAQ,CAAC,SAAS,EAAE,GAAG,CAAC,qBAAqB,CAAC,mBAAmB,CAAC,CAAA;IAClE,QAAQ,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,KAAK,GAAG,SAAS,CAAA;IAC7C,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IACrC,QAAQ,CAAC,UAAU,CAAC,EAAE,QAAQ,CAAC,KAAK,GAAG,SAAS,CAAA;CACjD,KAAG,KAAK,CAAC,KAAK,CAAC,WAAW,EAAE,KAAK,EAAE,UAAU,CAAC,UAAU,CAkJtD,CAAA;AAEH;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,WAAW,YACb,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,KAChD,KAAK,CAAC,KAAK,CAAC,WAAW,EAAE,MAAM,CAAC,WAAW,EAAE,UAAU,CAAC,UAAU,CACZ,CAAA"}
@@ -1,10 +1,11 @@
1
1
  /**
2
- * Typed, read-only Starknet JSON-RPC methods over an ordered list of endpoints with fallback.
2
+ * Typed Starknet JSON-RPC methods over an ordered list of endpoints with fallback.
3
3
  *
4
4
  * A call starts at the first endpoint and moves to the next one on failure, except on `WrongNetwork`. Each endpoint
5
- * is checked once to serve the configured network (`starknet_chainId`). Every method is a read, so retries and
6
- * fallback are safe. Methods are named after the JSON-RPC method without its namespace (`starknet_getEvents` is
7
- * `getEvents`). A `getEvents` page cursor is only sent to the endpoint that issued it, with no fallback.
5
+ * is checked once to serve the configured network (`starknet_chainId`). Every method but `addInvokeTransaction`
6
+ * and `addDeployAccountTransaction` is a read, so retries and fallback are safe; these two document their own case.
7
+ * Methods are named after the JSON-RPC method without its namespace (`starknet_getEvents` is `getEvents`). A
8
+ * `getEvents` page cursor is only sent to the endpoint that issued it, with no fallback.
8
9
  *
9
10
  * @example
10
11
  * ```ts
@@ -32,6 +33,7 @@
32
33
  * @since 0.1.0
33
34
  */
34
35
  import * as JsonRpc from "@effect-blockchain/core/JsonRpc";
36
+ import * as Arr from "effect/Array";
35
37
  import * as Config from "effect/Config";
36
38
  import * as Context from "effect/Context";
37
39
  import * as Effect from "effect/Effect";
@@ -82,12 +84,45 @@ export const StarknetEventsCursor = /*#__PURE__*/Schema.Struct({
82
84
  * @category services
83
85
  */
84
86
  export class StarknetRpc extends /*#__PURE__*/Context.Service()("@effect-blockchain/starknet/StarknetRpc") {}
87
+ const TXN_HASH_NOT_FOUND = 29;
85
88
  // error codes from the Starknet JSON-RPC spec v0.9 (starknet_api_openrpc.json), plus the common provider ones
86
89
  const codes = /*#__PURE__*/new Map([
87
90
  // UNEXPECTED_ERROR, JSON-RPC internal error and provider rate limits: the endpoint is struggling, retry then fall back
88
91
  [63, "Unavailable"], [-32603, "Unavailable"], [-32005, "Unavailable"], [429, "Unavailable"],
89
92
  // BLOCK_NOT_FOUND, TXN_HASH_NOT_FOUND: another endpoint may be further ahead
90
- [24, "Lagging"], [29, "Lagging"]]);
93
+ [24, "Lagging"], [TXN_HASH_NOT_FOUND, "Lagging"]]);
94
+ const bound = bound => ({
95
+ max_amount: bound.maxAmount,
96
+ max_price_per_unit: bound.maxPricePerUnit
97
+ });
98
+ const v3 = transaction => ({
99
+ version: "0x3",
100
+ signature: transaction.signature,
101
+ nonce: transaction.nonce,
102
+ resource_bounds: {
103
+ l1_gas: bound(transaction.resourceBounds.l1Gas),
104
+ l2_gas: bound(transaction.resourceBounds.l2Gas),
105
+ l1_data_gas: bound(transaction.resourceBounds.l1DataGas)
106
+ },
107
+ tip: transaction.tip,
108
+ paymaster_data: [],
109
+ nonce_data_availability_mode: "L1",
110
+ fee_data_availability_mode: "L1"
111
+ });
112
+ const invoke = transaction => ({
113
+ type: transaction.type,
114
+ sender_address: transaction.senderAddress,
115
+ calldata: transaction.calldata,
116
+ account_deployment_data: [],
117
+ ...v3(transaction)
118
+ });
119
+ const deployAccount = transaction => ({
120
+ type: transaction.type,
121
+ class_hash: transaction.classHash,
122
+ contract_address_salt: transaction.contractAddressSalt,
123
+ constructor_calldata: transaction.constructorCalldata,
124
+ ...v3(transaction)
125
+ });
91
126
  /**
92
127
  * Builds a {@link StarknetRpc} over `endpoints`, tried in order, sending requests with the provided `HttpClient`
93
128
  * (e.g. `FetchHttpClient.layer`). `timeout` (default 30 seconds) bounds each attempt, `retries` (default 3) and
@@ -175,10 +210,53 @@ export const layer = options => Layer.effect(StarknetRpc, Effect.gen(function* (
175
210
  }
176
211
  })))),
177
212
  getEvents,
213
+ call: options => rpc.withFallback(endpoint => rpc.requireHead(endpoint, RpcMethods.call.name, options.blockNumber, blockNumberOn(endpoint)).pipe(Effect.andThen(rpc.call(endpoint, RpcMethods.call, {
214
+ request: {
215
+ contract_address: options.contractAddress,
216
+ entry_point_selector: options.entryPointSelector,
217
+ calldata: options.calldata
218
+ },
219
+ block_id: {
220
+ block_number: options.blockNumber
221
+ }
222
+ })))),
178
223
  getTransactionReceipt: ({
179
224
  transactionHash
180
225
  }) => rpc.withFallback(endpoint => rpc.call(endpoint, RpcMethods.getTransactionReceipt, {
181
226
  transaction_hash: transactionHash
227
+ })),
228
+ getTransactionStatus: ({
229
+ transactionHash
230
+ }) => rpc.withFallback(endpoint => rpc.call(endpoint, RpcMethods.getTransactionStatus, {
231
+ transaction_hash: transactionHash
232
+ })).pipe(Effect.catchIf(error => error.code === TXN_HASH_NOT_FOUND, () => Effect.succeed(null))),
233
+ getNonce: ({
234
+ address,
235
+ blockTag
236
+ }) => rpc.withFallback(endpoint => rpc.call(endpoint, RpcMethods.getNonce, {
237
+ block_id: blockTag,
238
+ contract_address: address
239
+ })),
240
+ estimateFee: ({
241
+ blockTag,
242
+ skipValidate,
243
+ transactions
244
+ }) => rpc.withFallback(endpoint => rpc.call(endpoint, RpcMethods.estimateFee, {
245
+ request: Arr.map(transactions, transaction => transaction.type === "INVOKE" ? invoke(transaction) : deployAccount(transaction)),
246
+ simulation_flags: skipValidate === true ? ["SKIP_VALIDATE"] : [],
247
+ block_id: blockTag
248
+ })),
249
+ addInvokeTransaction: ({
250
+ transaction
251
+ }) => rpc.withFallback(endpoint => rpc.call(endpoint, RpcMethods.addInvokeTransaction, {
252
+ invoke_transaction: invoke(transaction)
253
+ })).pipe(Effect.map(({
254
+ transactionHash
255
+ }) => transactionHash)),
256
+ addDeployAccountTransaction: ({
257
+ transaction
258
+ }) => rpc.withFallback(endpoint => rpc.call(endpoint, RpcMethods.addDeployAccountTransaction, {
259
+ deploy_account_transaction: deployAccount(transaction)
182
260
  }))
183
261
  });
184
262
  }));