Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add function to get ABI from non-etherscan addresses #50

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 28 additions & 2 deletions eth_client/lib/eth_client.ex
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,20 @@ defmodule EthClient do
|> Rpc.call()
end

def call_by_selector(selector, arguments) do
encoded_arguments = ABI.TypeEncoder.encode_raw(arguments, selector.types)
|> Base.encode16(case: :lower)

data = selector.method_id <> encoded_arguments

%{
from: Context.user_account().address,
to: Context.contract().address,
data: data
}
|> Rpc.call()
end

def get_balance(address) do
{balance, _lead} =
Rpc.get_balance(address)
Expand All @@ -90,12 +104,24 @@ defmodule EthClient do
wei_to_ether(balance)
end

def invoke_by_selector(selector, arguments, amount) do
encoded_arguments = ABI.TypeEncoder.encode_raw(arguments, selector.types)
|> Base.encode16(case: :lower)
data = selector.method_id <> encoded_arguments

invoke_with_data(data, amount)
end

def invoke(method, arguments, amount) do
data =
ABI.encode(method, arguments)
data = method
|> ABI.encode(arguments)
|> Base.encode16(case: :lower)
|> add_0x()

invoke_with_data(data, amount)
end

defp invoke_with_data(data, amount) do
caller = Context.user_account()
caller_address = String.downcase(caller.address)
contract_address = Context.contract().address
Expand Down
49 changes: 48 additions & 1 deletion eth_client/lib/eth_client/abi.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,57 @@ defmodule EthClient.ABI do
@moduledoc """
"""
alias EthClient.Context
alias EthClient.Rpc

# get whether it's an etherscan-linked bc: get_etherscan_api_key...
def get("0x" <> _ = address) do
if Context.etherscan_api_key() do
get_etherscan(address)
else
get_non_etherscan(address)
end
end

def get("0x" <> _ = address), do: get_etherscan(address)
def get(abi_path), do: get_local(abi_path)

def to_selector(function_def) do
selector = ABI.FunctionSelector.decode(function_def["name"])
mfachal marked this conversation as resolved.
Show resolved Hide resolved
selector
|> Map.put(:method_id, function_def["selector"])
|> Map.put(:state_mutability, function_def["stateMutability"])

end

defp filter_unnamed(function_def) do
"0x" <> function_hash = function_def.method_id
unknown_name = "unknown" <> function_hash
case Map.get(function_def, :function) do
^unknown_name -> Map.delete(function_def, :function)
_ -> function_def
end
end

def get_non_etherscan(address) do
decode_path = Application.app_dir(:eth_client, "priv/decompile.py")
{:ok, bytecode} = Rpc.get_code(address)

case System.cmd("python3", [decode_path, bytecode]) do
{hashes, 0} ->
{:ok, funclist} = hashes
|> Jason.decode()

funclist = funclist
|> Enum.filter(fn %{"selector" => hash} -> hash != "_fallback()" end)
|> Enum.map(&to_selector/1)
|> Enum.map(&filter_unnamed/1)

{:ok, funclist}
{_, _} ->
{:error, :abi_unavailable}
end

end

defp get_etherscan(address) do
api_key = Context.etherscan_api_key()

Expand Down
60 changes: 57 additions & 3 deletions eth_client/lib/eth_client/contract.ex
Original file line number Diff line number Diff line change
Expand Up @@ -18,26 +18,79 @@ defmodule EthClient.Contract do

defp parse_abi([], acc), do: {:ok, acc}

defp parse_abi([%{"type" => "function"} = method_map | tail], acc) do
defp parse_abi([%{"type" => "function", "name" => name} = method_map | tail], acc) do
method = %{
name: String.to_atom(method_map["name"]),
name: name,
state_mutability: method_map["stateMutability"],
inputs: Enum.map(method_map["inputs"], fn input -> input["name"] end),
# What's the difference between type and internal type?
input_types: Enum.map(method_map["inputs"], fn input -> input["internalType"] end)
}

name_snake_case = String.to_atom(Macro.underscore(method_map["name"]))
name_snake_case = String.to_atom(Macro.underscore(name))
function = build_function(method)
acc = Map.put(acc, name_snake_case, Code.eval_quoted(function) |> elem(0))

parse_abi(tail, acc)
end

defp parse_abi([%{function: name} = method_map | tail], acc) do
function = build_function_by_hash(method_map)

selector_atom = name
|> Macro.underscore()
|> String.to_atom()

acc = Map.put(acc, selector_atom, Code.eval_quoted(function) |> elem(0))
mfachal marked this conversation as resolved.
Show resolved Hide resolved

parse_abi(tail, acc)
end

defp parse_abi([%{type: function, method_id: selector} = method_map | tail], acc) do
function = build_function_by_hash(method_map)

selector_atom = selector
|> String.to_atom()

acc = Map.put(acc, selector_atom, Code.eval_quoted(function) |> elem(0))

parse_abi(tail, acc)
end

defp parse_abi([_head | tail], acc) do
parse_abi(tail, acc)
end

defp build_function_by_hash(%{method_id: selector, state_mutability: mutability} = method)
when mutability in ["pure", "view"] do
args = method.types
|> length()
|> Macro.generate_arguments(__MODULE__)

bound_method = Macro.escape(method)

quote do
fn unquote_splicing(args) ->
EthClient.call_by_selector(unquote(bound_method), unquote(args))
end
end
end

defp build_function_by_hash(%{method_id: selector} = method) do
args = method
|> Map.get(:types)
|> length()
|> Macro.generate_arguments(__MODULE__)

bound_method = Macro.escape(method)

quote do
fn unquote_splicing(args), amount ->
EthClient.invoke_by_selector(unquote(bound_method), unquote(args), amount)
end
end
end

defp build_function(%{state_mutability: mutability} = method)
when mutability in ["pure", "view"] do
args = Macro.generate_arguments(length(method.inputs), __MODULE__)
Expand All @@ -60,4 +113,5 @@ defmodule EthClient.Contract do
end
end
end

end
1 change: 1 addition & 0 deletions eth_client/lib/eth_client/rpc.ex
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ defmodule EthClient.Rpc do
def gas_price, do: send_request("eth_gasPrice", [])
def get_transaction_by_hash(tx_hash), do: send_request("eth_getTransactionByHash", [tx_hash])
def get_transaction_receipt(tx_hash), do: send_request("eth_getTransactionReceipt", [tx_hash])
def get_code(contract), do: send_request("eth_getCode", [contract, "latest"])
def call(call_map), do: send_request("eth_call", [call_map, "latest"])

def get_logs(log_map), do: send_request("eth_getLogs", [log_map])
Expand Down
28 changes: 28 additions & 0 deletions eth_client/priv/decompile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import sys
import json
from panoramix.decompiler import decompile_bytecode

def get_hash(function_def):
func = {}
func['selector'] = function_def['hash']
func['name'] = function_def['abi_name']

if function_def['payable']:
# This needs some work
func['stateMutability'] = "payable"
else:
func['stateMutability'] = "nonpayable"
if function_def['const']:
func['stateMutability'] = "view"

func['type'] = "function"

return func

if len(sys.argv) != 2:
print("usage: python3 decode_address.py <address>", sys.argv)
else:
decompilation = decompile_bytecode(sys.argv[1])
# Despite its name, it's not a json
hashes = list(map(get_hash, decompilation.json["functions"]))
print(json.dumps(hashes))