# `ExWapp.AppState.Engine.Codec`
[🔗](https://github.com/elchemista/ex_wapp/blob/v0.1.5/lib/ex_wapp/appstate/engine/codec.ex#L1)

Encoding and decoding helpers for app-state patches.

This module owns the cryptographic transformation layer: it turns high-level
patch descriptions into protobuf payloads for WhatsApp and validates incoming
patch payloads back into decoded mutations that the local store can apply.

# `action_value`

```elixir
@type action_value() :: WAWebProtobufSyncAction.SyncActionValue.t() | nil
```

# `decoded_mutation`

```elixir
@type decoded_mutation() :: %{
  operation: non_neg_integer(),
  action: action_value(),
  version: integer() | nil,
  index: [String.t()],
  index_mac: binary(),
  value_mac: binary()
}
```

# `hash_state`

```elixir
@type hash_state() :: %{version: non_neg_integer(), hash: binary()}
```

# `mutation_info`

```elixir
@type mutation_info() :: %{
  :index =&gt; [String.t()],
  :version =&gt; integer(),
  :value =&gt; WAWebProtobufSyncAction.SyncActionValue.t(),
  optional(:operation) =&gt; :remove
}
```

# `patch_info`

```elixir
@type patch_info() :: %{
  type: String.t(),
  mutations: [mutation_info()],
  timestamp: integer() | nil
}
```

# `syncd_mutation`

```elixir
@type syncd_mutation() :: WAWebProtobufsServerSync.SyncdMutation.t()
```

# `syncd_patch`

```elixir
@type syncd_patch() :: WAWebProtobufsServerSync.SyncdPatch.t()
```

# `decode_mutations`

```elixir
@spec decode_mutations([syncd_mutation()], map(), boolean()) ::
  {:ok, [decoded_mutation()]} | {:error, term()}
```

Decodes a list of `SyncdMutation` records and optionally validates their MACs.

# `decode_patch`

```elixir
@spec decode_patch(syncd_patch(), String.t(), hash_state(), map(), map(), boolean()) ::
  {:ok, [decoded_mutation()], hash_state(), map()} | {:error, term()}
```

Decodes a complete incoming patch and validates its hash-chain transition.

Besides decoding each mutation, this verifies snapshot and patch MACs and
returns the updated hash state plus the refreshed mutation-MAC map.

# `encode_patch`

```elixir
@spec encode_patch(patch_info(), binary(), binary(), hash_state(), map()) ::
  {:ok, binary(), hash_state(), map()} | {:error, term()}
```

Encodes a high-level patch description into a `SyncdPatch` protobuf payload.

The returned binary is ready to be embedded in the app-state IQ request, and
the hash state / mutation MAC map are advanced to reflect the encoded patch.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
