Skip to content

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:

  1. x/ibc-rate-limit runs first via CombinedIBCHooks to enforce channel and denom flow caps.
  2. CustomHooks.OnRecvPacketOverride checks whether the packet is an ICS-20 FungibleTokenPacketData and parses data.Memo with ParseHookDataFromMemo.
    • Memos larger than 64 KB (65,536 bytes) are rejected before JSON unmarshaling.
    • A memo containing both swap_and_action and transfer_tokens is rejected (mutually exclusive).
    • Non-ICS-20 packets or memos without either key pass straight through to im.App.OnRecvPacket.
  3. When a hook is present, the module opens cacheCtx, writeCache := ctx.CacheContext() and runs the underlying ICS-20 transfer inside cacheCtx.
    • Asynchronous (nil) acknowledgements and failed IBC transfers abort immediately and discard cacheCtx.
  4. The local denom is resolved from the packet trace (extractDenomFromPacketOnRecv) and the intermediate sender is derived deterministically from (packet.DestChannel, data.Sender, "bb") via ibchooks/types.DeriveIntermediateSender.
  5. Keeper.ExecuteHook dispatches to ExecuteTransferTokens or ExecuteSwapAndAction in the same cacheCtx.
  6. If the hook returns a success acknowledgement, writeCache() commits both the ICS-20 receive and the hook's state changes atomically. Otherwise, cacheCtx is discarded and a deterministic error acknowledgement prefixed with swap-and-action-hooks: is returned so the source chain refunds the sender.

Supported Memo Hooks

go
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.

FieldTypeRequiredDescription
collection_idstringyesTarget collection ID (unsigned integer as string)
transfersarrayyesNon-empty array of transfers in snake_case JSON (converted to protobuf MsgTransferTokens.Transfers)
fail_on_errorboolyestrue: roll back the entire IBC transfer on error. false: keep the IBC transfer and send received coins to recover_address
recover_addressstringwhen fail_on_error is falseValid 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 tokenIn remains at the intermediate sender address unless your approval criteria transfer it via coinTransfers. For pure trigger calls with no payment required, send a minimal amount (for example 1ubadge or 1uatom).
  • On failure with fail_on_error: false, ExecuteFallbackToRecoverAddress sends tokenIn to recover_address inside 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).

FieldTypeRequiredDescription
user_swap.swap_exact_asset_in.operationsOperation[]yesOne 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 }yesMinimum output denom and amount; denom must match the final operation's denom_out
post_swap_actionobjectyesMust contain exactly one of transfer ({ to_address }) or ibc_transfer ({ ibc_info: { source_channel, receiver, memo?, recover_address } })
affiliatesAffiliate[]noOptional fee recipients ({ basis_points_fee, address }). Individual and combined affiliate fees are capped at 5000 bps (50%)
timeout_timestampuint64noOutbound IBC timeout in Unix nanoseconds. Defaults to blockTime + 5m; must be in the future and at most blockTime + 7d
destination_recover_addressstringnoValid 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; native x/tokenization alias denoms cannot be forwarded over IBC. The swapped output is first transferred to ibc_info.recover_address and then sent via transferKeeper.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

EventEmitted whenKey attributes
transfer_tokens_successtransfer_tokens succeedsmodule, sender, original_sender, collection_id, num_transfers, token_in, token_in_denom, token_in_amount
transfer_tokens_fallbacktransfer_tokens fails with fail_on_error: false and fallback succeedsmodule, sender, original_sender, recover_address, token_in, error, collection_id
swap_and_action_successswap_and_action swap succeedsmodule, sender, original_sender, token_in, token_out, denom_in, denom_out, num_operations, operation_<i>_*
swap_and_action_fallbackswap_and_action swap fails and destination_recover_address fallback succeedsmodule, 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:

bash
# 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"}}}}'

Edit this page on GitHub