-
Notifications
You must be signed in to change notification settings - Fork 0
/
RPCFunctions.fs
517 lines (443 loc) · 21.3 KB
/
RPCFunctions.fs
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
namespace Web3.fs
module RPCMethodFunctions =
///
/// Binds EthMethod to a string representation of the desired call. Only
/// making effort to support methods outlined at
/// https://playground.open-rpc.org/?schemaUrl=https://raw.githubusercontent.com/ethereum/eth1.0-apis/assembled-spec/
///
let internal bindEthMethod (m: EthMethod) =
match m with
| EthMethod.Accounts -> "eth_accounts" //
| EthMethod.BlockNumber -> "eth_blockNumber" //
| EthMethod.Call -> "eth_call" //
| EthMethod.Coinbase -> "eth_coinbase" //
| EthMethod.ChainId -> "eth_chainId" //
| EthMethod.EstimateGas -> "eth_estimateGas" //
//| EthMethod.FeeHistory -> "eth_feeHistory" //
| EthMethod.GasPrice -> "eth_gasPrice" //
| EthMethod.GetBalance -> "eth_getBalance" //
| EthMethod.GetBlockByHash -> "eth_getBlockByHash" //
| EthMethod.GetBlockByNumber -> "eth_getBlockByNumber" //
| EthMethod.GetBlockTransactionCountByHash -> "eth_getBlockTransactionCountByHash" //
| EthMethod.GetBlockTransactionCountByNumber -> "eth_getBlockTransactionCountByNumber" //
| EthMethod.GetCode -> "eth_getCode" //
//| EthMethod.GetFilterChanges -> "eth_getFilterChanges" //
//| EthMethod.GetFilterLogs -> "eth_getFilterLogs" //
//| EthMethod.GetLogs -> "eth_getLogs" //
| EthMethod.GetStorageAt -> "eth_getStorageAt" //
| EthMethod.GetTransactionCount -> "eth_getTransactionCount" //
| EthMethod.GetTransactionByHash -> "eth_getTransactionByHash" //
| EthMethod.GetTransactionByBlockHashAndIndex -> "eth_getTransactionByBlockHashAndIndex" //
| EthMethod.GetTransactionByBlockNumberAndIndex -> "eth_getTransactionByBlockNumberAndIndex" //
| EthMethod.GetTransactionReceipt -> "eth_getTransactionReceipt" //
| EthMethod.GetUncleCountByBlockHash -> "eth_getUncleCountByBlockHash" //
| EthMethod.GetUncleCountByBlockNumber -> "eth_getUncleCountByBlockNumber" //
//| EthMethod.NewFilter -> "eth_newFilter" //
//| EthMethod.NewBlockFilter -> "eth_newBlockFilter" //
//| EthMethod.NewPendingTransactionFilter -> "eth_newPendingTransactionFilter" //
| EthMethod.ProtocolVersion -> "eth_protocolVersion" //
| EthMethod.Syncing -> "eth_syncing" //
| EthMethod.SendTransaction -> "eth_sendTransaction" //
| EthMethod.SendRawTransaction -> "eth_sendRawTransaction" //
| EthMethod.Sign -> "eth_sign" //
| EthMethod.SignTransaction -> "eth_signTransaction" //
//| EthMethod.UninstallFilter -> "eth_uninstallFilter" //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// RPC Parameter module
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
module RPCParamFunctions =
open Common
//
// Convert call params into json string representation. RPC commands that
// consume filters will not work, as there is no websocket support.
//
let internal bindEthParam (p: EthParam) =
match p with
| EthGenericRPC p -> concatParamString p
| EthParam1559Call _e -> createJsonObj _e
| EthParam1559EstimateGas _e -> createJsonObj _e
| EthParam1559SendTransaction _e -> createJsonObj _e
| EthParam1559SignTransaction _e -> createJsonObj _e
[<AutoOpen>]
module RPCFunctions =
open Common
open Logging
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Builder functions for creating unvalidated transaction objects
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///
/// Detects if an ENS name was used and performs the lookup to resolve it
/// to an address.
///
let handleENSName env chainId (name: string) =
if name.Contains('.') then
let hash = convertENSName name
let bytes = [Byte32 hash] |> createInputByteString |> function Ok o -> o | Error _ -> ""
let evmData = "02571be3" + bytes |> prepend0x
{ utxnType = "0x2"
unonce = ""
utoAddr = "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"
ufrom = env.constants.walletAddress
ugas = ""
uvalue = ZEROHEX
udata = evmData
umaxPriorityFeePerGas = ""
umaxFeePerGas = ""
uaccessList = []
uchainId = chainId}
|> validateRPCParams
|> Result.bind
(fun _params ->
{ method = EthMethod.Call
paramList = _params
blockHeight = LATEST }
|> env.connection)
|> fun res ->
match res with
| Ok o -> o |> unpackRoot |> stringAndTrim |> fun s -> s.Remove(0, 26) |> prepend0x
| Error _ -> "failed to resolve address"
else name
///
/// Get constants values out of the ContractConstants
let private unpackConstants (constants: ContractConstants) =
constantsBind constants |> (fun a -> a |> Ok)
///
/// Convert the supplied value into hex form
let private convertValueToHex value (pipe: Result<string * string * string * EVMDatatype list, Web3Error>) =
pipe
|> Result.bind(fun (a, b, c, d) ->
(a, b, c, d, (value |> bigintToHex))
|> Ok)
///
/// Places the actual EVMFunction into the data for later use
let private pipeBindFunction evmFunction (pipe: Result<string * string * string * EVMDatatype list * string, Web3Error>) =
pipe
|> Result.bind(fun (a, b, c, d, e) -> (a, b, c, d, e, (bindFunctionIndicator evmFunction)) |> Ok)
///
/// Checks that we aren't trying to call the fallback or receive function(s)
/// on a contract that doesn't have them.
///
let checkForFallbackOrReceive contract (pipe: Result<string * string * string * EVMDatatype list * string * EVMFunction, Web3Error>) =
pipe
|> Result.bind(fun (_,_,_,_,_, requestedFunction) ->
if requestedFunction.name = "fallback" && contract.hasFallback = false then
ContractLacksFallbackError |> Error
else if requestedFunction.name = "receive" && contract.hasReceive = false then
ContractLacksReceiveError |> Error
else pipe)
///
/// Selects the supplied arguments defaults in the ContractConstants.
let private chooseDefaultOrSuppliedArguments suppliedArgs (pipe: Result<string * string * string * EVMDatatype list * string * EVMFunction, Web3Error>) =
pipe
|> Result.bind(fun (a, b, c, defaultArgs, e, f) ->
match suppliedArgs with
| [] -> (a, b, c, defaultArgs, e, f) |> Ok
| s -> (a, b, c, s, e, f) |> Ok)
///
/// Checks that arguments aren't supplied to functions with an empty
/// argument list, and that arguments aren't missing when required.
let private checkArgsToFunction (pipe: Result<string * string * string * EVMDatatype list * string * EVMFunction, Web3Error>) =
pipe
|> Result.bind(fun a ->
let _, _, _, args, _, evmFunction = a
match evmFunction.canonicalInputs with
|x when bindEVMFunctionInputs x = "()" ->
if args.Length = 0 then a |> Ok
else ArgumentsToEmptyFunctionSignatureError |> Error
| _ ->
if not(args.Length = 0) then a |> Ok
else FunctionArgumentsMissingError |> Error )
///
/// Check for sending value to a non-Payable.
let private checkValueAndStateMutability (pipe: Result<string * string * string * EVMDatatype list * string * EVMFunction, Web3Error>) =
pipe
|> Result.bind (fun a ->
let _, _, _, _, value, evmFunction = a
match evmFunction.config with
| Payable -> a |> Ok
| _ ->
if not(value = "0x0") then
ValueToNonPayableFunctionError |> Error
else a |> Ok )
///
/// Create the 'data' value string from arguments and function
let private createDataString (pipe: Result<string * string * string * EVMDatatype list * string * EVMFunction, Web3Error>) =
pipe
|> Result.bind (fun (a, b, c, args, e, evmFunction) ->
createInputByteString args
|> Result.bind (fun r -> (a, b, c, e, $"{evmFunction.hash}{r}") |> Ok))
///
/// Creates an unvalidated record
let private returnUnvalidatedRecord address contract (pipe: Result<string * string * string * string * string, Web3Error>) =
pipe
|> Result.bind (fun (txn, maxfee, priority, value, data) ->
{ utxnType = txn
unonce = ""
utoAddr = contract.address
ufrom = address
ugas = ""
uvalue = value
udata = data
umaxFeePerGas = maxfee
umaxPriorityFeePerGas = priority
uaccessList = []
uchainId = contract.chainId } |> Ok)
///
/// Returns an unvalidated transaction object.
let private createUnvalidatedTxn constants contract arguments value (pipe: Result<FunctionIndicator, Web3Error>) =
pipe
|> Result.bind (fun functionIndicator ->
constants
|> unpackConstants
|> convertValueToHex value
|> pipeBindFunction functionIndicator
|> checkForFallbackOrReceive contract
|> chooseDefaultOrSuppliedArguments arguments
|> checkArgsToFunction
|> checkValueAndStateMutability
|> createDataString
|> returnUnvalidatedRecord constants.walletAddress contract )
///
/// Factored out for reuse. Passes through a specified blockheight, or
/// supplies the LATEST default.
///
let private blockHeight (constants: ContractConstants) =
match constants.blockHeight with
| Some s -> s
| None -> LATEST
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//// Deployment Function Helpers
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///
/// Checks that the signer is on the chain we're about to transact with.
/// Emits WrongChainInSigner if not.
///
/// Check that the chain we're trying to work with is actually selected in
/// the signer.
let private checkForChain env chainId =
{ method = EthMethod.ChainId
paramList = [] |> EthGenericRPC
blockHeight = LATEST}
|> env.connection
|> decomposeRPCResult EthMethod.ChainId
|> env.log Emit
|> unwrapRPCCallResponse
|> fun chain ->
if chain = chainId then
() |> Ok
else WrongChainInSignerError |> Error
///
/// Checks that the value string isn't just empty "".
let private checkForEmptyValueString (value: string) (pipe: Result<'a, Web3Error>) =
let bool, _ = bigint.TryParse(value)
if bool then pipe else InvalidValueArgumentError |> Error
///
/// Checks that the function we're attempting to call exists.
let private checkFunctionExists contract functionSelector (pipe: Result<unit, Web3Error>) =
pipe
|> Result.bind (fun _ -> findFunction contract functionSelector)
///
/// Unpacks constants from the ContractConstants record
let private unpackDeployConstants constants (pipe: Result<'a, Web3Error>) =
pipe
|> Result.bind (fun _ ->
constantsBind constants |> (fun (a, b, c, _) -> (a, b, c) |> Ok))
///
/// Check that we aren't supplying value to a non-Payable constructor, which
/// will be accepted but the transaction will fail with a status 0x0.
///
let private checkValueAndStateMutabilityDeploy value contract (pipe: Result<string * string * string, Web3Error>) =
match contract.stateMutability with
| Payable -> pipe
| _ -> if value = "0" then pipe else ValueToNonPayableFunctionError |> Error
///
/// Returns the actual bytestring of the contract for the transaction.
let private createDeployData args (pipe: Result<string * string * string,Web3Error>) =
pipe
|> Result.bind (fun (a, b, c) ->
match createInputByteString args with
| Ok data -> (a, b, c, data) |> Ok
| Error e -> e |> Error)
///
/// Creates the unvalidated call record specifically for deployment.
let private buildDeploymentCall env value contract (pipe: Result<string * string * string * string, Web3Error>) =
let (RawContractBytecode _rawBytecode) = contract.bytecode
if contract.stateMutability = Payable && value = "0" then
env.log Log (PayableFunctionZeroValueWarning "Zero value sent to payable function" |> Error) |> ignore
pipe
|> Result.bind (fun (txn, maxfee, priority, data) ->
{ utxnType = txn
unonce = ""
utoAddr = ""
ufrom = env.constants.walletAddress
ugas = "0x4C4B40"
uvalue = value |> bigintToHex
udata =
$"{_rawBytecode}{data}" |> prepend0x
umaxFeePerGas = maxfee
umaxPriorityFeePerGas = priority
uaccessList = []
uchainId = contract.chainId } |> Ok )
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//// Call Functions
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///
/// Creates an Ethereum RPC request whose purpose is typically to query the
/// RPC node for chain-based or network-based data. Examples are retrieving
/// the contents of a block, checking a transaction receipt, or getting an
/// account balance.
/// * method: An EthMethod selector, like `EthMethod.GetBalance`
/// * paramList: A string list, such as
/// `["0x3872353821064f55df53ad1e2d7255e969f6eac0", "0x9dc3fe"]`
/// * chainId: The hexadecimal representation of the chain ID.
/// * env: A Web3Environment. See createWeb3Environment.
/// Some EthMethods have no arguments. Use an empty list in those cases.
///
let public rpcCall method (paramList: string list) chainId env =
checkForChain env chainId
|> Result.bind ( fun _ ->
{ method = method
paramList = paramList |> EthGenericRPC
blockHeight = LATEST }
|> env.connection
|> decomposeRPCResult method)
///
/// Creates a contract transaction (a call that changes the state of the
/// blockchain).
/// * contract: A DeployedContract that is being called
/// * evmFunction: FunctionSelector corresponding to the the function being
/// called. Typically (ByName "SomeFunction")
/// * arguments: a list of EVMDatatypes. Use an empty list to indicate no
/// arguments.
/// * value: the wei-denominated amount of ETH to send along with a
/// transaction to a payable function.
/// * env: An Web3Environment. See createWeb3Environment.
///
let public contractTransaction contract evmFunction arguments value env =
checkForChain env contract.chainId
|> checkForEmptyValueString value
|> checkFunctionExists contract evmFunction
|> createUnvalidatedTxn env.constants contract arguments value
|> Result.bind validateRPCParams
|> Result.bind
(fun _params ->
{ method = EthMethod.SendTransaction
paramList = _params
blockHeight = LATEST }
|> env.connection)
|> Result.bind (fun r ->
unpackRoot r
|> stringAndTrim
|> EthTransactionHash
|> fun ethHash ->
env.log Log (Library $"Monitoring transaction {ethHash}\n" |> Ok )
|> fun _ -> ethHash
|> Ok)
|> monitorTransaction env.monitor
///
/// Creates a contract call, a gasless transaction for querying the chain.
/// * contract: A DeployedContract that is being called
/// * evmFunction: FunctionSelector corresponding to the the function being
/// called. Typically '(ByName "SomeFunction")'
/// * arguments: a list of EVMDatatypes. Use an empty list to indicate no
/// arguments.
/// * env: An Web3Environment. See createWeb3Environment.
///
let public contractCall contract evmFunction arguments env =
let blockHeight' = blockHeight env.constants
checkForChain env contract.chainId
|> checkFunctionExists contract evmFunction
|> createUnvalidatedTxn env.constants contract arguments "0"
|> Result.bind validateRPCParams
|> Result.bind
(fun _params ->
{ method = EthMethod.Call
paramList = _params
blockHeight = blockHeight' }
|> env.connection)
|> Result.bind (fun r ->
returnOutputAsEVMDatatypes contract evmFunction (unpackRoot r |> stringAndTrim)
|> CallResult
|> Ok)
///
/// Creates a transaction specifically for deploying a contract's bytecode.
/// * contract: A UndeployedContract that is being deployed
/// * value: the wei-denominated amount of ETH to send along with a
/// transaction to a payable constructor.
/// * env: An Web3Environment. See createWeb3Environment.
///
let public deployContract (contract: UndeployedContract) value env =
checkForChain env contract.chainId
|> checkForEmptyValueString value
|> unpackDeployConstants env.constants
|> checkValueAndStateMutabilityDeploy value contract
|> createDeployData contract.constructorArguments
|> buildDeploymentCall env value contract
|> Result.bind validateRPCParams
|> Result.bind
(fun _params ->
{ method = EthMethod.SendTransaction
paramList = _params
blockHeight = LATEST }
|> env.connection)
|> Result.bind (fun r ->
unpackRoot r
|> stringAndTrim
|> EthTransactionHash
|> fun ethHash ->
env.log Log (Library $"Monitoring transaction {ethHash}" |> Ok )
|> fun _ -> ethHash
|> Ok)
|> monitorTransaction env.monitor
///
/// Estimate the amount of gas units required for the given transaction to
/// complete. Essentially the same as contractTransaction but with a
/// different underlying call. A static value argument of "0" is supplied.
///
/// * contract: A DeployedContract that is being called
/// * evmFunction: FunctionSelector corresponding to the the function being
/// called. Typically (ByName "SomeFunction")
/// * arguments: a list of EVMDatatypes. Use an empty list to indicate no
/// arguments.
/// * env: An Web3Environment. See createWeb3Environment.
let public estimateGas contract evmFunction arguments env =
let blockHeight' = blockHeight env.constants
checkForChain env contract.chainId
|> checkFunctionExists contract evmFunction
|> createUnvalidatedTxn env.constants contract arguments "0"
|> Result.bind validateRPCParams
|> Result.bind
(fun _params ->
{ method = EthMethod.EstimateGas
paramList = _params
blockHeight = blockHeight' }
|> env.connection)
|> decomposeRPCResult EthMethod.EstimateGas
///
/// This function is for the sending of Ether between Externally Owned
/// Accounts. Use 'contractTransaction' with the `Receive` indicator to send
/// to contracts. ENS names are supported for this function.
///
let public sendValue chainId destination value env =
let _dest = handleENSName env chainId destination
{ dummyTransaction with
utoAddr = _dest
ufrom = env.constants.walletAddress
uvalue = value |> bigintToHex
uchainId = chainId}
|> validateRPCParams
|> Result.bind
(fun _params ->
{method = EthMethod.SendTransaction
paramList = _params
blockHeight = LATEST}
|> env.connection)
|> Result.bind (fun r ->
unpackRoot r
|> stringAndTrim
|> EthTransactionHash
|> fun ethHash ->
env.log Log (Library $"Monitoring transaction {ethHash}" |> Ok )
|> fun _ -> ethHash
|> Ok)
|> monitorTransaction env.monitor