Skip to content

Commit

Permalink
make keccak module configurable (#169)
Browse files Browse the repository at this point in the history
  • Loading branch information
steffenix authored Jul 5, 2024
1 parent 3c04f5d commit 4c4b72f
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 4 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_do
and published on [HexDocs](https://hexdocs.pm). Once published, the docs can
be found at [https://hexdocs.pm/ex_abi](https://hexdocs.pm/ex_abi).

## Confiiguration

The default keccak library is set to `ex_keccak` but that can be ovveriden for a different libary:

```elixir
config :ex_abi, keccak_module: KeccakEx
```

## Usage

### Encoding
Expand Down
6 changes: 4 additions & 2 deletions lib/abi/function_selector.ex
Original file line number Diff line number Diff line change
Expand Up @@ -403,8 +403,9 @@ defmodule ABI.FunctionSelector do

defp add_method_id(selector) do
signature = encode(selector)
keccak_module = Application.get_env(:ex_abi, :keccak_module, ExKeccak)

case ExKeccak.hash_256(signature) do
case keccak_module.hash_256(signature) do
<<method_id::binary-size(4), _::binary>> ->
%{selector | method_id: method_id}

Expand All @@ -414,9 +415,10 @@ defmodule ABI.FunctionSelector do
end

defp add_event_id(selector) do
keccak_module = Application.get_env(:ex_abi, :keccak_module, ExKeccak)
signature = encode(selector)

%{selector | method_id: ExKeccak.hash_256(signature)}
%{selector | method_id: keccak_module.hash_256(signature)}
end

defp get_types(function_selector) do
Expand Down
3 changes: 2 additions & 1 deletion lib/abi/type_encoder.ex
Original file line number Diff line number Diff line change
Expand Up @@ -244,11 +244,12 @@ defmodule ABI.TypeEncoder do
defp encode_method_id(%FunctionSelector{function: nil}), do: ""

defp encode_method_id(function_selector) do
keccak_module = Application.get_env(:ex_abi, :keccak_module, ExKeccak)
# Encode selector e.g. "baz(uint32,bool)" and take keccak
kec =
function_selector
|> FunctionSelector.encode()
|> ExKeccak.hash_256()
|> keccak_module.hash_256()

# Take first four bytes
<<init::binary-size(4), _rest::binary>> = kec
Expand Down
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ defmodule ABI.Mixfile do
{:dialyxir, "~> 1.4", only: [:dev, :test], runtime: false},
{:ex_doc, "~> 0.24", only: :dev, runtime: false},
{:jason, "~> 1.4"},
{:ex_keccak, "~> 0.7.5"},
{:ex_keccak, "~> 0.7.5", optional: true},
{:propcheck, "~> 1.4", only: [:test, :dev]}
]
end
Expand Down

0 comments on commit 4c4b72f

Please sign in to comment.