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 all 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
32 changes: 31 additions & 1 deletion eth_client/lib/eth_client.ex
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,21 @@ 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 @@ -95,12 +110,27 @@ defmodule EthClient do
wei_to_ether(balance)
end

def invoke_by_selector(selector, arguments, amount \\ 0) 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 \\ 0) do
data =
ABI.encode(method, arguments)
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
48 changes: 47 additions & 1 deletion eth_client/lib/eth_client/abi.ex
Original file line number Diff line number Diff line change
@@ -1,10 +1,56 @@
defmodule EthClient.ABI do
@moduledoc false
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
function_def["name"]
|> ABI.FunctionSelector.decode()
|> 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} ->
funclist =
hashes
|> Jason.decode!()
|> 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
65 changes: 62 additions & 3 deletions eth_client/lib/eth_client/contract.ex
Original file line number Diff line number Diff line change
Expand Up @@ -57,26 +57,85 @@ 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()

{term, _bind} = Code.eval_quoted(function)
acc = Map.put(acc, selector_atom, term)

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()

{term, _bind} = Code.eval_quoted(function)
acc = Map.put(acc, selector_atom, term)

parse_abi(tail, acc)
end

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

defp build_function_by_hash(%{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 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))