Skip to content

Commit

Permalink
Add SPV request body json protocol. (#137)
Browse files Browse the repository at this point in the history
Co-authored-by: Edwin Guayacan <80716239+EdwinGuayacan@users.noreply.github.com>
  • Loading branch information
SergioGueruiz and EdwinGuayacan committed Nov 9, 2022
1 parent f280159 commit da17e9d
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
26 changes: 26 additions & 0 deletions lib/types/spv_request_body.ex
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ defmodule Kadena.Types.SPVRequestBody do
`SPVRequestBody` struct definition.
"""

alias Kadena.Chainweb.Pact.JSONPayload
alias Kadena.Types.{Base64Url, ChainID}

@behaviour Kadena.Types.Spec
Expand Down Expand Up @@ -48,4 +49,29 @@ defmodule Kadena.Types.SPVRequestBody do
{:error, reasons} -> {:error, [target_chain_id: :invalid] ++ reasons}
end
end

defimpl JSONPayload do
alias Kadena.Types.SPVRequestBody
alias Kadena.Utils.MapCase

@type request_key :: Base64Url.t()
@type target_chain_id :: ChainID.t()
@type value :: String.t()

@impl true
def parse(%SPVRequestBody{request_key: request_key, target_chain_id: chain_id}) do
request_key = extract_key(request_key)
chain_id = extract_chain_id(chain_id)

%{request_key: request_key, target_chain_id: chain_id}
|> MapCase.to_camel!()
|> Jason.encode!()
end

@spec extract_key(request_key()) :: value()
defp extract_key(%Base64Url{url: url}), do: url

@spec extract_chain_id(target_chain_id()) :: value()
defp extract_chain_id(%ChainID{id: id}), do: id
end
end
22 changes: 22 additions & 0 deletions test/types/spv_request_body_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ defmodule Kadena.Types.SPVRequestBodyTest do

use ExUnit.Case

alias Kadena.Chainweb.Pact.JSONPayload
alias Kadena.Types.{Base64Url, ChainID, SPVRequestBody}

describe "new/1" do
Expand Down Expand Up @@ -42,4 +43,25 @@ defmodule Kadena.Types.SPVRequestBodyTest do
{:error, [spv_request_body: :not_a_list]} = SPVRequestBody.new("invalid_param")
end
end

describe "JSONPayload.parse/1" do
setup do
%{
json_result:
"{\"requestKey\":\"7af34f24d55d2fcf5de6fccfeeb837698ebff4598303237c64348a47806c8646\",\"targetChainId\":\"1\"}"
}
end

test "with a valid SPVRequestBody", %{
json_result: json_result
} do
spv_request_body =
SPVRequestBody.new(
request_key: "7af34f24d55d2fcf5de6fccfeeb837698ebff4598303237c64348a47806c8646",
target_chain_id: "1"
)

^json_result = JSONPayload.parse(spv_request_body)
end
end
end

0 comments on commit da17e9d

Please sign in to comment.