x/custom-hooks
The x/custom-hooks IBC middleware: atomic inbound ICS-20 memo hooks for transfer_tokens and swap_and_action, intermediate sender derivation, limits, events, and fallback rules.
x/custom-hooks is BitBadges' IBC memo-hook module. It plugs into x/ibc-hooks as an OnRecvPacketOverrideHooks implementation and inspects the JSON memo field of inbound ICS-20 token transfers. When a memo contains a supported hook (transfer_tokens or swap_and_action), the module executes the ICS-20 receive and the hook action inside a single cached context so both commit together or roll back atomically.
For full field-by-field payload walkthroughs and JSON recipes, see IBC Hooks: Transfer Tokens and Swap and Action.
Execution Flow
On every inbound IBC packet routed through the transfer stack:
- x/ibc-rate-limit runs first via
CombinedIBCHooksto enforce channel and denom flow caps. CustomHooks.OnRecvPacketOverridechecks whether the packet is an ICS-20FungibleTokenPacketDataand parsesdata.MemowithParseHookDataFromMemo.- Memos larger than 64 KB (
65,536bytes) are rejected before JSON unmarshaling. - A memo containing both
swap_and_actionandtransfer_tokensis rejected (mutually exclusive). - Non-ICS-20 packets or memos without either key pass straight through to
im.App.OnRecvPacket.
- Memos larger than 64 KB (
- When a hook is present, the module opens
cacheCtx, writeCache := ctx.CacheContext()and runs the underlying ICS-20 transfer insidecacheCtx.- Asynchronous (
nil) acknowledgements and failed IBC transfers abort immediately and discardcacheCtx.
- Asynchronous (
- The local denom is resolved from the packet trace (
extractDenomFromPacketOnRecv) and the intermediate sender is derived deterministically from(packet.DestChannel, data.Sender, "bb")viaibchooks/types.DeriveIntermediateSender. Keeper.ExecuteHookdispatches toExecuteTransferTokensorExecuteSwapAndActionin the samecacheCtx.- If the hook returns a success acknowledgement,
writeCache()commits both the ICS-20 receive and the hook's state changes atomically. Otherwise,cacheCtxis discarded and a deterministic error acknowledgement prefixed withswap-and-action-hooks:is returned so the source chain refunds the sender.
Supported Memo Hooks
type HookData struct {
SwapAndAction *SwapAndAction `json:"swap_and_action,omitempty"`
TransferTokens *TransferTokensAction `json:"transfer_tokens,omitempty"`
}transfer_tokens
Executes an x/tokenization MsgTransferTokens with creator set to the derived intermediate sender address.
| Field | Type | Required | Description |
|---|---|---|---|
collection_id | string | yes | Target collection ID (unsigned integer as string) |
transfers | array | yes | Non-empty array of transfers in snake_case JSON (converted to protobuf MsgTransferTokens.Transfers) |
fail_on_error | bool | yes | true: roll back the entire IBC transfer on error. false: keep the IBC transfer and send received coins to recover_address |
recover_address | string | when fail_on_error is false | Valid bb1... Bech32 fallback recipient |
Key behaviors verified in x/custom-hooks/keeper/transfer_tokens.go:
- Before executing
MsgTransferTokens, the keeper sets all auto-approval flags (AutoApproveAllIncomingTransfers,AutoApproveSelfInitiatedOutgoingTransfers,AutoApproveSelfInitiatedIncomingTransfers) for the intermediate sender on the target collection. Your collection approvals must still authorize the intermediate sender (or allow any initiator). - On success, the received ICS-20
tokenInremains at the intermediate sender address unless your approval criteria transfer it viacoinTransfers. For pure trigger calls with no payment required, send a minimal amount (for example1ubadgeor1uatom). - On failure with
fail_on_error: false,ExecuteFallbackToRecoverAddresssendstokenIntorecover_addressinside a fallback cached context and returns a success acknowledgement. If the fallback transfer also fails, the whole packet returns an error acknowledgement.
swap_and_action
Swaps the received ICS-20 coins through x/gamm using RouteExactAmountIn and then executes a post-swap action (either a local transfer via x/sendmanager or an outbound ICS-20 transfer).
| Field | Type | Required | Description |
|---|---|---|---|
user_swap.swap_exact_asset_in.operations | Operation[] | yes | One or more chained { pool, denom_in, denom_out } steps (operations[0].denom_in must equal the received local denom; each denom_out must match the next denom_in) |
min_asset.native | { denom, amount } | yes | Minimum output denom and amount; denom must match the final operation's denom_out |
post_swap_action | object | yes | Must contain exactly one of transfer ({ to_address }) or ibc_transfer ({ ibc_info: { source_channel, receiver, memo?, recover_address } }) |
affiliates | Affiliate[] | no | Optional fee recipients ({ basis_points_fee, address }). Individual and combined affiliate fees are capped at 5000 bps (50%) |
timeout_timestamp | uint64 | no | Outbound IBC timeout in Unix nanoseconds. Defaults to blockTime + 5m; must be in the future and at most blockTime + 7d |
destination_recover_address | string | no | Valid bb1... address that receives the original tokenIn if the swap fails instead of returning an error acknowledgement |
Key behaviors verified in x/custom-hooks/keeper/keeper.go:
- Supports both single-hop and multi-hop routes through
gammKeeper.RouteExactAmountIn. - If any denom in the route is a
badgeslp:alias denom, auto-approval flags are set for the intermediate sender inside the swap's cached context (and rolled back if the swap fails). - For
post_swap_action.ibc_transfer, the output denom must be ICS-20 compatible (sendManagerKeeper.IsICS20Compatible) and expandable to its full IBC path; nativex/tokenizationalias denoms cannot be forwarded over IBC. The swapped output is first transferred toibc_info.recover_addressand then sent viatransferKeeper.Transfer.
Deterministic Error Handling
IBC acknowledgements are part of consensus state, so non-deterministic error strings (stack traces, file paths, goroutine IDs) would halt the chain. x/custom-hooks maintains a dedicated transient store (customhooks_transient) via SetDeterministicError / GetDeterministicError / ClearDeterministicError that sanitizes .go, goroutine, runtime., panic, and package paths before embedding error details into swap-and-action-hooks: ... acknowledgements.
Events
| Event | Emitted when | Key attributes |
|---|---|---|
transfer_tokens_success | transfer_tokens succeeds | module, sender, original_sender, collection_id, num_transfers, token_in, token_in_denom, token_in_amount |
transfer_tokens_fallback | transfer_tokens fails with fail_on_error: false and fallback succeeds | module, sender, original_sender, recover_address, token_in, error, collection_id |
swap_and_action_success | swap_and_action swap succeeds | module, sender, original_sender, token_in, token_out, denom_in, denom_out, num_operations, operation_<i>_* |
swap_and_action_fallback | swap_and_action swap fails and destination_recover_address fallback succeeds | module, sender, original_sender, recover_address, token_in, error, num_operations, operation_<i>_* |
Messages, Queries, Params, and CLI
x/custom-hooks exposes no transaction messages, no gRPC/LCD query service, and no module parameters. It is triggered strictly by sending a standard ICS-20 transfer from a counterparty chain with a JSON memo:
# Example from a counterparty Cosmos chain CLI (e.g. osmosisd / gaiad)
osmosisd tx ibc-transfer transfer transfer channel-0 bb1p0rrel3365scadq5k9pv0x0zp9j22js6dnw70d 1000000uosmo \
--from my-key \
--memo '{"swap_and_action":{"user_swap":{"swap_exact_asset_in":{"swap_venue_name":"bitbadges-poolmanager","operations":[{"pool":"1","denom_in":"ibc/...","denom_out":"ubadge"}]}},"min_asset":{"native":{"denom":"ubadge","amount":"100000"}},"post_swap_action":{"transfer":{"to_address":"bb1py4mfpg6uf59qkyzg0nmau322c5873eeysp5ue"}}}}'