How to quote and execute spot swaps against Injective's native orderbook from Solidity and fund the calling contract.

Injective's precompiles allow EVM contracts to interact directly with the native execution layer within a single transaction. Introduced in the Meridian upgrade, the swap precompile extends this to spot swaps: a contract can execute a swap against the native orderbook, transfer the resulting tokens, or use them in another operation before the transaction completes. These operations are atomic, so they either succeed together or are rolled back together if the transaction reverts. This post covers how the precompile works and what a Solidity contract needs to quote and execute a swap.

Quick Reference

Item Details
Precompile 0x0000000000000000000000000000000000000068
Availability The original methods shipped in v1.20.4 (Meridian). v1.21 adds the V2 exact input methods, exact output execution, and resolution of EVM native erc20: denoms. Try these changes on Injective Testnet v1.21.0-beta.2 before v1.21.0 lands on mainnet November 24th.
Quote methods quoteExactInputV1
quoteExactInputV2
quoteExactOutputV1
Execution methods swapExactInputV1
swapExactInputV2
swapExactOutputV1
Supported markets Active spot markets on the swap allowlist. Each call uses one market.
Funding The precompile debits the immediate caller’s default subaccount bank balance. It requires no ERC20 approval.
Token addresses Use the ERC20 address of a token represented in the native bank module. Use the zero address for native INJ.
References Swap precompile documentation
Swap precompile demo

Synchronous swaps on the native orderbook

Injective's exchange normally matches orders in a batch auction at the end of each block. A contract submitting an ordinary order must therefore wait for the block to finish before using the resulting tokens. The swap precompile executes immediately, allowing the contract to swap and use those tokens within the same transaction.

Bridge resolvers swap incoming assets into the token required by the bridge, while aggregators execute swaps as part of a trading route. The swap precompile lets both use the resulting tokens immediately within the same Injective transaction.

A contract can combine a swap with subsequent transfers or contract calls in one Injective transaction. If the calling contract reverts, Injective rolls back the swaps and transfers within that call. For bridge operations, delivery on the destination chain remains a separate asynchronous step.

How the swap precompile works

The swap precompile at 0x68 offers exact-input and exact-output quotes and execution. Each execution call submits one atomic spot market order using the caller’s default subaccount. If the swap reverts, Injective discards its changes to native balances and the orderbook.

The swap precompile uses a separate interface from the exchange precompile. It enables swaps per market, accounts for atomic swap fees, charges gas for matching, and keeps existing order placement permissions unchanged:

  • Market availability: SwapParams enables swaps for individual markets. Extending the existing execution path would have applied the capability across all spot markets.
  • Balance holds: Swaps use a 2.0x atomic fee multiplier by default on Mainnet. The buy hold covers the atomic taker fee as well as the purchase.
  • Gas usage: Matching may consume multiple price levels depending on the swap size. Gas is charged according to the work performed.
  • Authorization: Existing authz grants for ordinary order placement do not automatically authorize synchronous swap execution.

Check the mainnet swap params for latest values.

Routing is implemented in the calling contract. For a route with multiple hops, call the

An exact input buy holds the full quote token budget before execution. An exact input sell holds the base token quantity rounded down to the market’s quantity tick. Any unused portion of either hold is released to the caller.

The Mainnet exchange parameter spot_atomic_market_order_fee_multiplier is currently 2.0. A market can override this default. The precompile uses the applicable multiplier when pricing the trade and meters gas separately. Query the Mainnet default with:

curl -fsS https://sentry.lcd.injective.network/injective/exchange/v2/exchangeParams \
  | jq -r '.params.spot_atomic_market_order_fee_multiplier'

For exact input, request a quote, choose a minimum output and set a deadline. For exact output, request the input estimate with quoteExactOutputV1, then use swapExactOutputV1 to enforce an input cap. Quantity ticks can cause the delivered amount to exceed the requested output slightly. The Solidity interface lists all six methods.

Quotes are also available through gRPC and the LCD: SpotSwapOutput at /injective/exchange/v2/spot/swapOutput and SpotSwapInput at /injective/exchange/v2/spot/swapInput. These endpoints can be used to price a route off-chain before building the transaction. They also expose spent_amount, which is covered in the section on partial fills below.

Funding the calling account

Under MTS, an ERC20 balance and its native bank balance represent the same funds. The precompile spends directly from the calling account's default subaccount.

If a wallet calls a router and the router calls 0x68, the router pays from its own balance. Fund it with the full input budget before executing. For a Circle USDC to INJ buy, transfer Circle USDC to the router using the token’s ERC20 transfer and check balanceOf(router). To sell native INJ, fund the router’s native balance. You can send INJ to its Injective bech32 address using the native bank module, or use an EVM transfer if the router accepts it.

The account that submits the transaction also needs INJ for gas. Call the precompile with zero msg.value. It debits the router’s default subaccount bank balance directly, so the precompile needs no ERC20 approval. If your router pulls funds from the user instead, authorize that separate transfer to the router. Restrict who can spend funds held by your contract.

The output is credited to the address supplied as recipient. Passing the zero address defaults to the caller. There is no equivalent input account parameter; the input always comes from the calling account's default subaccount.

For token parameters, use the ERC20 address corresponding to the native bank denom, or the zero address for native INJ. marketId is the spot market ID with its 0x prefix. Active markets can be queried at /injective/exchange/v1beta1/spot/markets?status=Active.

Token addresses and bank denoms

Under MTS, tokens in the native bank module are represented on Injective's EVM. Tokens originating through TokenFactory, Peggy or IBC receive an ERC20 address when their token pair is created. EVM-native MTS tokens such as Circle USDC have a bank denom derived from their ERC20 contract address. Ordinary ERC20s whose balances are held in contract storage have no corresponding bank denom and the precompile rejects them. Pass the ERC20 address as tokenIn or tokenOut, and use the zero address for native INJ.

The precompile resolves the supplied address to its bank denom. Query the token pairs to find the ERC20 address associated with a denom, or retrieve the pair for a known ERC20 address:

ERC20_API="https://sentry.lcd.injective.network/injective/erc20/v1beta1"

# List up to 2,000 token pairs.
curl -fsSG "$ERC20_API/all_token_pairs" \
  --data-urlencode 'pagination.limit=2000' | jq

# Look up Circle USDC by its Mainnet ERC20 address on v1.21.
TOKEN_ADDRESS="0xa00C59fF5a080D2b954d0c75e46E22a0c371235a"
curl -fsSG "$ERC20_API/token_pair_by_erc20_address" \
  --data-urlencode "erc20_address=$TOKEN_ADDRESS" | jq

On v1.21, the precompile also resolves EVM native MTS tokens such as Circle USDC through their erc20: bank denoms. Check the network’s release and confirm that the token has a pair or an EVM native bank denom if resolution fails.

Quote and execute a swap

For an input budget, call quoteExactInputV2 to estimate input spent and output received. Choose minOut from your own price reference (an oracle or the market mid) and tolerance. The quote already includes this trade’s impact on the order book, so a minOut derived from it won’t protect against a thin book. Pass the bound in output base units and a deadline in Unix seconds to swapExactInputV2. Execution reverts if the delivered output falls below your minimum or the deadline has passed.

This excerpt belongs inside an authorized function in a funded contract. The recipient is the contract itself so it can use the output in the same transaction.

// Import ISwapModule from the demo's Solidity interface.
ISwapModule swap = ISwapModule(address(0x68));
(, uint256 quotedOut) = swap.quoteExactInputV2(tokenIn, marketId, amountIn);

// Choose minOut from your own price reference (an oracle or the market mid)
// and tolerance. The quote already includes this trade’s impact on the order
// book, so a minOut derived from it won’t protect against a thin book.
require(minOut > 0 && quotedOut >= minOut, "quote below minimum");
(uint256 spent, uint256 received) = swap.swapExactInputV2(
    tokenIn, marketId, amountIn, minOut, address(this), deadline
);

For a target output, call quoteExactOutputV1(tokenOut, marketId, amountOut) to estimate the required input. Choose maxAmountIn in input base units and call swapExactOutputV1 with that cap and the deadline. Fund the full cap before execution. The call delivers at least the requested output within the cap or reverts.

Quotes estimate fills against current depth. Orders and account fees can change before execution, so verify the bound in a simulation from the funded caller. You can query the quote with cast call to check token resolution, market eligibility and executable output before submitting a transaction. See the Solidity interface and swap precompile reference.

Partial fills and unspent input

For a buy order, the swap holds the full quote token budget. For a sell order, it holds the base token quantity rounded down to the market’s quantity tick. Both exact input buys and sells can fill partially when the book lacks depth. The caller keeps any unspent input, and the swap succeeds if the output meets minOut. An exact output swap reverts if it cannot deliver the requested output within the input cap.

Both quoteExactInputV2 and swapExactInputV2 return (amountInSpent, amountOut). The difference between the requested input and the spent amount is the unspent input. Quantity ticks can leave a small remainder even in a deep book. A caller that limits partial fills can check the remainder against a tolerance expressed in input units and revert if it exceeds that tolerance.

The V1 exact-input methods only return amountOut. Off-chain integrations can use spent_amount from the gRPC or LCD quote for an estimate and from EventSwapExecuted for reconciliation. Balance deltas can differ from reported amounts by a smallest unit due to rounding.

Composing swaps

For a route with multiple hops, the calling contract executes a separate precompile call for each market. A revert rolls back preceding swaps within the same reverting call frame.

A bridge resolver funds the calling contract, executes the swap with a price bound and uses the delivered amount to dispatch the bridge. For exact-input swaps, the resolver can enforce its unspent-input tolerance before dispatch. For exact-output swaps, it can request the amount the bridge needs and cap its input. A revert in the resolver also rolls back the swap. The bridge handles delivery on the destination chain asynchronously.

Supported markets

SwapParams in the exchange module contains an enabled flag and a market allowlist. Calling a market outside the allowlist returns:

> market is not allowlisted for swaps: invalid swap route

On your target network, check that enabled is true and that allowed_markets includes the spot market ID you intend to use. See the Mainnet and Testnet allowlist queries.

Governance or an address listed in exchange_admins can update the parameters using MsgUpdateSwapParams. Updates take effect immediately and replace the entire parameter group, so include every market that should remain allowlisted.

If your integration needs a market enabled, ask in the #developers channel of the Injective Discord or go through your Injective partner contact.

Known limitations

Account for the following limitations when planning an integration:

  • Exact output execution is available on v1.21 and requires a market with enough liquidity to deliver the requested amount within the input cap.
  • Consumed input is returned by the V2 exact-input methods and the exact-output execution method.
  • Routing: Each call uses one market. Routes with multiple hops must be implemented in the calling contract.
  • Market type: Only spot markets are supported. Derivatives remain a separate development track.
  • Market availability: A market must be active and included in the swap allowlist.
  • Post-Only Mode. When the exchange is in Post-Only Mode, both swap quotes and execution return exchange is in post-only mode. Check post_only_mode_height_threshold in the exchange parameters. The mode is active while the current block height is below that threshold. Retry once the exchange exits this mode.
  • Test environment: Use an Injective node or live RPC endpoint. Foundry's simulated EVM does not provide the precompile.

Further development and integration support

See the Swap Precompile reference for the interface, amount units, and execution rules. For a hands-on walkthrough, see the swap precompile demo. Use the Testnet Index for network connections and faucets.