Skip to content

Commit

Permalink
Add jsonrpc call() method (#71)
Browse files Browse the repository at this point in the history
  • Loading branch information
ferranbt authored Mar 27, 2024
1 parent f82dfba commit 9d65cba
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/protocols/EthJsonRPC.sol
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ pragma solidity ^0.8.13;
import "../suavelib/Suave.sol";
import "solady/src/utils/JSONParserLib.sol";
import "solady/src/utils/LibString.sol";
import "forge-std/console.sol";
import "../utils/HexStrings.sol";

/// @notice EthJsonRPC is a library with utilities to interact with an Ethereum JSON-RPC endpoint.
contract EthJsonRPC {
Expand All @@ -30,6 +32,24 @@ contract EthJsonRPC {
return val;
}

/// @notice call a contract function.
/// @param to the address of the contract.
/// @param data the data of the function.
/// @return the result of the function call.
function call(address to, bytes memory data) public returns (bytes memory) {
bytes memory body = abi.encodePacked(
'{"jsonrpc":"2.0","method":"eth_call","params":[{"to":"',
LibString.toHexStringChecksummed(to),
'","data":"',
LibString.toHexString(data),
'"},"latest"],"id":1}'
);

JSONParserLib.Item memory item = doRequest(string(body));
bytes memory result = HexStrings.fromHexString(_stripQuotesAndPrefix(item.value()));
return result;
}

function doRequest(string memory body) public returns (JSONParserLib.Item memory) {
Suave.HttpRequest memory request;
request.method = "POST";
Expand All @@ -44,6 +64,15 @@ contract EthJsonRPC {
return item.at('"result"');
}

function _stripQuotesAndPrefix(string memory s) internal pure returns (string memory) {
bytes memory strBytes = bytes(s);
bytes memory result = new bytes(strBytes.length - 4);
for (uint256 i = 3; i < strBytes.length - 1; i++) {
result[i - 3] = strBytes[i];
}
return string(result);
}

function trimQuotes(string memory input) private pure returns (string memory) {
bytes memory inputBytes = bytes(input);
require(
Expand Down
9 changes: 9 additions & 0 deletions test/protocols/EthJsonRPC.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@ contract EthJsonRPCTest is Test, SuaveEnabled {
assertEq(nonce, 0);
}

function testEthJsonRPCCall() public {
EthJsonRPC ethjsonrpc = getEthJsonRPC();

bytes memory data = abi.encodeWithSignature("get_deposit_count()");
bytes memory result = ethjsonrpc.call(address(0x00000000219ab540356cBB839Cbe05303d7705Fa), data);

require(result.length > 0, "result is empty");
}

function getEthJsonRPC() public returns (EthJsonRPC ethjsonrpc) {
try vm.envString("JSONRPC_ENDPOINT") returns (string memory endpoint) {
ethjsonrpc = new EthJsonRPC(endpoint);
Expand Down

0 comments on commit 9d65cba

Please sign in to comment.