A TypeScript SDK for encoding, decoding, and interacting with the 1inch Swap VM Protocol smart contract. This SDK provides utilities for building transactions, parsing events, and managing virtual machine instructions for the Swap VM Protocol's core operations.
The Swap VM Protocol is a lightweight virtual machine designed for efficient and flexible token swapping on-chain. This SDK simplifies integration by providing:
- Transaction Building: Build typed call data for
quote,swap,hash, andeip712Domainoperations - Instruction System: Comprehensive instruction set including swaps, liquidity concentration, fees, and controls
- Trait management: Taker and maker traits builders with sensible defaults for standard swaps, plus fine-grained control whenever you need advanced order customization.
For detailed protocol documentation, see the Swap VM Protocol Documentation.
pnpm add @1inch/swap-vm-sdkaqua.ship() only records virtual balances for the strategy: the tokens stay in the maker's wallet and Aqua pulls them with transferFrom when swaps execute. The maker must keep the tokens in the wallet and approve the Aqua contract to spend each of them.
import {
AQUA_SWAP_VM_CONTRACT_ADDRESSES,
Address,
NetworkEnum,
Order,
MakerTraits,
AquaXYCAmmStrategy,
instructions
} from '@1inch/swap-vm-sdk'
import { AquaProtocolContract, AQUA_CONTRACT_ADDRESSES } from '@1inch/aqua-sdk'
import { encodeFunctionData, erc20Abi, maxUint256 } from 'viem'
const chainId = NetworkEnum.ETHEREUM
const aqua = new AquaProtocolContract(AQUA_CONTRACT_ADDRESSES[chainId])
const swapVMAddress = AQUA_SWAP_VM_CONTRACT_ADDRESSES[chainId]
const maker = '0xmaker_address'
const USDC = new Address('0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48')
const WETH = new Address('0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2')
// Price range: 1500–3000 USDC per WETH. `Price.fromHuman` applies the token decimals and `toSqrt()`
// returns the on-chain bound sqrt(P * 1e18), with P = tokenGt/tokenLt in token base units (1e18 fixed-point).
// USDC < WETH by address, so P is WETH per USDC and the higher USDC price (3000) is the lower bound
const { Price } = instructions.concentrate
const usdcPerWeth = {
quoteToken: { address: USDC, decimals: 6n },
baseToken: { address: WETH, decimals: 18n }
}
const program = AquaXYCAmmStrategy.newConcentrate({
sqrtPriceMin: Price.fromHuman('3000', usdcPerWeth).toSqrt(),
sqrtPriceMax: Price.fromHuman('1500', usdcPerWeth).toSqrt()
}).build()
const order = Order.new({
maker: new Address(maker),
program,
traits: MakerTraits.default()
})
// Aqua pulls the tokens from the maker's wallet when swaps execute, so it needs an allowance
for (const token of [USDC, WETH]) {
await makerWallet.send({
to: token.toString(),
data: encodeFunctionData({
abi: erc20Abi,
functionName: 'approve',
args: [aqua.address.toString(), maxUint256]
}),
value: 0n
})
}
const tx = aqua.ship({
app: swapVMAddress,
strategy: order.encode(),
amountsAndTokens: [
{
amount: 10000n * 10n ** 6n,
token: USDC
},
{
amount: 5n * 10n ** 18n,
token: WETH
}
]
})
await makerWallet.send(tx)import {
Order,
HexString,
TakerTraits,
Address,
AQUA_SWAP_VM_CONTRACT_ADDRESSES,
NetworkEnum,
SwapVMContract,
ABI
} from '@1inch/swap-vm-sdk'
import { decodeFunctionResult } from 'viem'
const chainId = NetworkEnum.ETHEREUM
const swapVM = new SwapVMContract(AQUA_SWAP_VM_CONTRACT_ADDRESSES[chainId])
const USDC = new Address('0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48')
const WETH = new Address('0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2')
const encodedOrder = '0x...' // fetched from ship event or from api
const order = Order.decode(new HexString(encodedOrder))
const srcAmount = 100n * 10n ** 6n
const swapParams = {
order,
amount: srcAmount,
takerTraits: TakerTraits.default(),
tokenIn: USDC,
tokenOut: WETH
}
// Simulate the call to get the dstAmount
const simulateResult = await taker.call(swapVM.quote(swapParams))
const [_, dstAmount] = decodeFunctionResult({
abi: ABI.SWAP_VM_ABI,
functionName: 'quote',
data: simulateResult.data!
})
console.log('dstAmount', dstAmount)
// Slippage protection: the swap reverts if it would deliver less than the quote minus 0.5%
const slippageBps = 50n
const minDstAmount = (dstAmount * (10_000n - slippageBps)) / 10_000n
// Swap
const swapTx = swapVM.swap({
...swapParams,
takerTraits: TakerTraits.default().with({ threshold: minDstAmount })
})
await taker.send(swapTx)Get a quote for a swap.
const quoteTx = swapVM.quote({
order: Order.decode(new HexString('0x...')),
tokenIn: new Address('0x...'),
tokenOut: new Address('0x...'),
amount: 1000000000000000000n,
takerTraits: TakerTraits.default(),
})Parameters:
order- The maker's order (fetched from ship event or from api)tokenIn- The input token addresstokenOut- The output token addressamount- The input amount to quotetakerTraits- Taker-specific traits configuration
Returns: CallInfo object with encoded transaction data
Execute a swap transaction.
// quotedAmountOut: amountOut returned by `quote` for the same order, tokens and amount
const slippageBps = 50n // 0.5%
const minAmountOut = (quotedAmountOut * (10_000n - slippageBps)) / 10_000n
const swapTx = swapVM.swap({
order: Order.decode(new HexString('0x...')),
tokenIn: new Address('0x...'),
tokenOut: new Address('0x...'),
amount: 1000000000000000000n,
takerTraits: TakerTraits.new({ exactIn: true, threshold: minAmountOut }),
})Parameters:
- All parameters from
quote takerTraits.threshold- Slippage bound checked on-chain: minimumamountOutfor exact-in swaps, maximumamountInfor exact-out swaps.0n(the default) disables the check, see Slippage protection
Returns: CallInfo object with encoded transaction data
TakerTraits.threshold is the only slippage check the router enforces, and it defaults to 0n. With 0n the threshold is left out of the encoded taker traits and the router skips the check, so the swap succeeds as long as amountOut > 0. Such a swap can be sandwiched, and it accepts whatever the order returns at execution time, even if that is far below the quote.
Set a threshold for every swap, derived from a fresh quote and an explicit slippage tolerance:
- Exact-in (
exactIn: true,amountis the input amount):thresholdis the minimumamountOut, for examplequotedAmountOut * (10_000n - slippageBps) / 10_000n. Below it, the swap reverts withTakerTraitsInsufficientMinOutputAmount. - Exact-out (
exactIn: false,amountis the output amount):thresholdis the maximumamountIn, for examplequotedAmountIn * (10_000n + slippageBps) / 10_000n. Above it, the swap reverts withTakerTraitsExceedingMaxInputAmount.
With strictThreshold: true, the swap must match threshold exactly instead.
Calculate the hash of an order (view).
const order = Order.new({
maker: new Address('0x...'),
traits: MakerTraits.default(),
program: new SwapVmProgram('0x...'),
})
const hashOrderTx = swapVM.hashOrder(order)Parameters:
order- The order to hash
Returns: CallInfo object with encoded transaction data for the hash order function
Orders authorized by a maker signature (useAquaInsteadOfSignature: false) are hashed as EIP-712 typed data Order(address maker,uint256 traits,bytes data), so order.hash(domain) needs the EIP-712 domain of the router that executes the order. Aqua orders (MakerTraits.default()) are hashed as keccak256(order.encode()) and ignore the domain.
The domain must match the router exactly. A hash computed with another name, version, chainId or verifyingContract still looks valid, but the router rejects its signature with BadSignature. The deployed AquaSwapVMRouter contracts all use the name 1inch SwapVM v1.0, and the version is 1.0.2 on every chain except Monad, Cronos, HyperEVM and Arc, where it is 1.0.
For the deployed routers, take the domain from the SDK:
import { Address, getAquaSwapVmEip712Domain, MakerTraits, NetworkEnum, Order } from '@1inch/swap-vm-sdk'
const order = Order.new({
maker: new Address('0x...'),
traits: MakerTraits.default().with({ useAquaInsteadOfSignature: false }),
program, // SwapVmProgram built with a program builder
})
// { chainId, name, version, verifyingContract }
const domain = getAquaSwapVmEip712Domain(NetworkEnum.ETHEREUM)
const orderHash = order.hash(domain)For any other router, read the domain from the contract (eip712Domain(), EIP-5267):
import { Address, HexString, SwapVMContract } from '@1inch/swap-vm-sdk'
const swapVM = new SwapVMContract(new Address('0x...')) // router address
const { data } = await publicClient.call(swapVM.eip712Domain()) // viem PublicClient
const domain = SwapVMContract.decodeEip712DomainResult(new HexString(data!))
const orderHash = order.hash(domain)Emitted when a swap is executed.
import { SwappedEvent } from '@1inch/swap-vm-sdk'
const log = { data: '0x...', topics: ['0x...'] }
const event = SwappedEvent.fromLog(log)
console.log(event.orderHash) // HexString
console.log(event.maker) // Address
console.log(event.taker) // Address
console.log(event.tokenIn) // Address
console.log(event.tokenOut) // Address
console.log(event.amountIn) // bigint
console.log(event.amountOut) // bigintThe Swap VM uses a comprehensive instruction system for building swap programs.
🔎 Instruction coverage vs. deployment
- The SDK ships two opcode tables in
src/swap-vm/instructions/index.ts:_allInstructions(theSwapVMRouterlayout,Opcodes.sol) andaquaInstructions(theAquaSwapVMRouterlayout,AquaOpcodes.sol). It can encode/decode every opcode in these tables; any other instruction needs a custom opcode table (see "Custom instruction sets &ProgramBuilder" below). ORACLE_PRICE_ADJUSTER_1Dis in neither table, and no router opcode table includes it: the SDK only ships its args and opcode definition (instructions.oraclePriceAdjuster), soRegularProgramBuilderandAquaProgramBuildercannot encode or decode it.- The currently deployed
AquaSwapVMRoutercontracts support only the Aqua instruction set (aquaInstructions): a subset of_allInstructionsplusONLY_TX_ORIGIN_TOKEN_BALANCE_NON_ZERO, which only the Aqua table has. - Any program that uses instructions outside
aquaInstructionswill not be executable on current Aqua deployments, even though encoding/decoding will succeed. - After the
FusakaEthereum hardfork, a fullSwapVMdeployment is planned; at that point, programs using the complete_allInstructionsset will be executable on-chain on Ethereum.
💡 Gotcha: When designing programs intended to run on today’s on-chain Aqua instances, treat aquaInstructions as the authoritative list of runtime-available opcodes, and the rest of the instruction set as future / generic Swap VM capabilities.
Instructions in the SDK opcode tables, by category (all of them are in _allInstructions unless noted):
STATIC_BALANCES_XD- Initialize static token balancesDYNAMIC_BALANCES_XD- Access and manipulate dynamic token balances
INVALIDATE_BIT_1D- Invalidate an order bit in the maker’s bitmapINVALIDATE_TOKEN_IN_1D- Invalidate orders by input tokenINVALIDATE_TOKEN_OUT_1D- Invalidate orders by output token
JUMP- Unconditional jump to another instructionJUMP_IF_TOKEN_IN- Conditional jump based on taker input tokenJUMP_IF_TOKEN_OUT- Conditional jump based on taker output tokenDEADLINE- Guard: only execute before a given timestampONLY_TAKER_TOKEN_BALANCE_NON_ZERO- Guard: only execute if taker token balance is non-zeroONLY_TAKER_TOKEN_BALANCE_GTE- Guard: only execute if balance >= thresholdONLY_TAKER_TOKEN_SUPPLY_SHARE_GTE- Guard: only execute if supply share >= thresholdONLY_TX_ORIGIN_TOKEN_BALANCE_NON_ZERO- Guard: only execute iftx.origintoken balance is non-zero (Aqua table only:aquaInstructionsand the deployedAquaSwapVMRoutercontracts)SALT- Add randomness to order hash
XYC_SWAP_XD- XYC swap for multi-dimensional poolsCONCENTRATE_GROW_LIQUIDITY_2D- Concentrate liquidity in 2-token pools (sqrtPriceMin/sqrtPriceMax, P = tokenGt/tokenLt, 1e18)PEGGED_SWAP_GROW_PRICE_RANGE_2D- Square-root linear swap curve for pegged assets in 2-token poolsDECAY_XD- Apply decay calculationLIMIT_SWAP_1D- Execute limit order swapLIMIT_SWAP_ONLY_FULL_1D- Execute limit order only if fully fillableREQUIRE_MIN_RATE_1D- Enforce minimum rate requirementADJUST_MIN_RATE_1D- Adjust minimum rate dynamicallyDUTCH_AUCTION_BALANCE_IN_1D- Dutch auction based on available input balanceDUTCH_AUCTION_BALANCE_OUT_1D- Dutch auction based on desired output balanceBASE_FEE_ADJUSTER_1D- Adjust for network base feesTWAP- Time-weighted average price swapEXTRUCTION- External contract instruction
FLAT_FEE_AMOUNT_IN_XD- Flat fee based on input amountPROTOCOL_FEE_AMOUNT_IN_XD- Protocol fee on input, transferred from the maker to the fee recipientAQUA_PROTOCOL_FEE_AMOUNT_IN_XD- Protocol fee on input, pulled from the maker's Aqua balanceDYNAMIC_PROTOCOL_FEE_AMOUNT_IN_XD- Protocol fee on input, with fee and recipient read from an external fee providerAQUA_DYNAMIC_PROTOCOL_FEE_AMOUNT_IN_XD- Dynamic protocol fee on input, pulled from the maker's Aqua balance
Experimental fee instructions (FeeExperimental.sol, not recommended for production, not in aquaInstructions):
FLAT_FEE_AMOUNT_OUT_XD- Flat fee based on output amountPROGRESSIVE_FEE_IN_XD- Progressive fee applied on inputPROGRESSIVE_FEE_OUT_XD- Progressive fee applied on outputPROTOCOL_FEE_AMOUNT_OUT_XD- Protocol fee on outputAQUA_PROTOCOL_FEE_AMOUNT_OUT_XD- Aqua protocol fee on output
Anyone can deploy a SwapVM-compatible contract with a custom instruction set (e.g. different opcode layout, subset, or extension of the core set) and still use this SDK to build programs for it.
The generic ProgramBuilder:
- Is instruction-set agnostic – you inject the opcode table via the constructor as
ixsSet: IOpcode[]. - Can build and decode programs for:
- The full
SwapVMinstruction set (_allInstructions) - The Aqua subset (
aquaInstructions) - Any custom opcode table that matches your own contract deployment
- The full
Take attention:
ProgramBuilder.add(ix)validates that the instruction’s opcode is present in the providedixsSet.- If you accidentally mix instructions from a different set, it throws with the list of supported opcode IDs.
ProgramBuilder.decode(program)uses the sameixsSetto map opcode indices back to instruction definitions, so your off-chain opcode table must match the on-chain contract layout.- Decoding is relative to the builder's opcode table: the same bytes can mean different instructions under different tables (e.g. byte
0x16isxycSwapXDin_allInstructionsbut a reserved slot inaquaInstructions). Always decode a program with the table of the router it targets, e.g.AquaProgramBuilder.decode(program)forAquaSwapVMRouterprograms. decodethrows on opcode bytes that are missing from the table or map to a reservedEMPTY_OPCODEslot, and on instructions whose args do not re-encode to exactly the original bytes. Programs containing debug opcodes decode only on a builder withwithDebug()enabled.
- Decoding is relative to the builder's opcode table: the same bytes can mean different instructions under different tables (e.g. byte
This makes it safe to:
- Deploy your own
SwapVM-style contract with a custom opcode mapping. - Use
ProgramBuilderwith your customixsSetto construct and parse programs for that deployment, without changing the rest of the SDK.
Control flow is not validated: jump, jumpIfTokenIn and jumpIfTokenOut targets are absolute byte offsets into the built program, and on-chain execution is bounded only by gas, so making a program terminate is up to the maker. build() accepts backward jumps (which can loop until the transaction runs out of gas), targets that are not an instruction start, and instructions that no execution path reaches. Call lint() on a builder (for a built program, AquaProgramBuilder.decode(program).lint()) to get these issues as warnings, without throwing:
new AquaProgramBuilder()
.jump({ nextPC: 0n }) // jumps to itself
.xycSwapXD()
.lint()
// [
// { code: 'backward-jump', instructionIndex: 0, message: 'Instruction 0 (Controls.jump) at offset 0 jumps back to offset 0, so execution can loop until it runs out of gas' },
// { code: 'unreachable-instruction', instructionIndex: 1, message: 'Instruction 1 (XYCSwap.xycSwapXD) at offset 4 is unreachable from the program start' },
// ]For strategies intended to run on today’s deployed AquaSwapVM contracts, it is recommended to use the specialized AquaProgramBuilder instead of the bare ProgramBuilder:
-
It is pre-wired with
aquaInstructions, so you cannot accidentally use opcodes that are not supported by Aqua. -
It exposes a rich set of high-level, typed methods for the Aqua instruction set 💡 Practical guidance:
-
Use
AquaProgramBuilderfor real-world strategy building on current Aqua deployments – it gives you a safer, higher-level API over the Aqua opcode subset. -
Use
ProgramBuilderwhen:- Targeting future full
SwapVMdeployments (post-Fusakaon Ethereum), or - Working with your own custom instruction sets and contracts.
- Targeting future full
A strategy is a reusable template that produces a SwapVmProgram – a sequence of instructions that defines how liquidity behaves and how swaps should be executed.
At a high level:
- You parameterize a strategy with business-level inputs (tokens, fees, decay periods, etc.).
- The strategy’s
.build()method compiles these into a low-levelSwapVmProgramusing a program builder. - That program is then embedded into an
Orderand shipped.
Strategies are thin wrappers around a program builder:
- Collect inputs (e.g. tokens, fee bps, decay parameters, protocol fee receiver).
- Instantiate a builder:
AquaProgramBuilderfor currentAquaSwapVMdeployments (recommended).ProgramBuilderwith a custom opcode set for non-Aqua/custom deployments.
- Append instructions in the desired execution order.
- Call
.build()to get aSwapVmProgram.
Because the strategy owns the builder, you can keep the strategy API stable even if the underlying instruction sequence evolves.
Aqua tracks a maker's balances per strategy hash (order.hash(), the keccak256 of the encoded order), and ship() accepts new tokens for a hash that already holds balances. Without a salt, the hash depends only on the maker, the traits and the strategy parameters, so shipping identical parameters for two token pairs puts both pairs under one hash and lets takers swap across them. Give each shipped strategy its own salt:
const program = AquaXYCAmmStrategy.new().withFeeTokenIn(5).withRandomSalt().build()withRandomSalt()draws a uint64 salt fromglobalThis.crypto.getRandomValues;withSalt(salt)sets your own value (0nincluded).- A random salt cannot be recomputed from the parameters: store it (or keep the shipped strategy bytes or hash) to recompute the strategy hash for docking.
- No salt is added by default, so
build()stays deterministic for the same parameters.
To define a custom strategy:
- Create a small builder class that:
- Stores your domain parameters (tokens, price bands, risk limits, etc.).
- Offers fluent
withX(...)methods to configure them.
- In
.build():- Create
ProgramBuilder. - Append instructions in the order you want them executed.
- Return
builder.build().
- Create
This pattern keeps your business logic readable at the strategy layer while leveraging the full flexibility of the underlying Swap VM instruction set.
For example:
import type { SwapVmProgram } from '@1inch/swap-vm-sdk'
import { AquaProgramBuilder, instructions, Address, Order, MakerTraits } from '@1inch/swap-vm-sdk'
import { parseUnits } from 'viem'
const { concentrate, fee } = instructions
/**
* Minimal strategy:
* - concentrates liquidity for a 2-token pool (price range in raw P = tokenGt/tokenLt, 1e18)
* - optionally charges a taker fee on input
* - always finishes with a simple XYC swap
*/
export class SimpleAmmStrategy {
private rawPriceMin?: bigint
private rawPriceMax?: bigint
private feeBpsIn?: number
constructor(
public readonly tokenA: Address,
public readonly tokenB: Address,
) {}
/**
* Sets the concentrated liquidity price range.
* Prices are P = tokenGt/tokenLt in 1e18 fixed-point, as a ratio of token base units
* (e.g. WETH wei per USDC unit when USDC < WETH), so they depend on both tokens' decimals.
*/
public withPriceRange(rawPriceMin: bigint, rawPriceMax: bigint): this {
this.rawPriceMin = rawPriceMin
this.rawPriceMax = rawPriceMax
return this
}
/**
* Sets taker fee (bps) applied to amountIn.
* If not called, no taker fee is applied.
*/
public withFeeTokenIn(bps: number): this {
this.feeBpsIn = bps
return this
}
/**
* Builds a SwapVmProgram for AquaSwapVM using a small, fixed instruction pipeline:
* [concentrate liquidity] -> [optional fee on input] -> [XYC swap]
*/
public build(): SwapVmProgram {
const builder = new AquaProgramBuilder()
if (this.rawPriceMin !== undefined && this.rawPriceMax !== undefined) {
const data = concentrate.ConcentrateGrowLiquidity2DArgs.fromRawPrices(
this.rawPriceMin,
this.rawPriceMax,
)
builder.add(concentrate.concentrateGrowLiquidity2D.createIx(data))
}
if (this.feeBpsIn !== undefined) {
const feeArgs = fee.FlatFeeArgs.fromBps(this.feeBpsIn)
builder.add(fee.flatFeeAmountInXD.createIx(feeArgs))
}
// Core swap step
builder.xycSwapXD()
return builder.build()
}
}
// Example usage: 1500–3000 USDC per WETH. USDC < WETH by address, so each raw price is
// (1 WETH in wei) * 1e18 / (price in USDC units), and the higher USDC price (3000) is the lower bound
const { ONE_E18 } = concentrate
const oneWeth = parseUnits('1', 18)
const strategy = new SimpleAmmStrategy(USDC, WETH)
.withPriceRange(
(oneWeth * ONE_E18) / parseUnits('3000', 6), // rawPriceMin: 3000 USDC per WETH
(oneWeth * ONE_E18) / parseUnits('1500', 6), // rawPriceMax: 1500 USDC per WETH
)
.withFeeTokenIn(5) // 5 bps taker fee on input (optional)
const program = strategy.build()
const order = Order.new({
maker: new Address(maker),
program,
traits: MakerTraits.default(),
})You can define your own high-level instructions as long as they:
- Have an on-chain implementation at a specific opcode index.
- Provide a TypeScript args type, a coder, and an
Opcodedefinition wired into an instruction set.
Here is an example of implementation flatFeeXD instruction. You can implement any custom instruction in the same way.
const FEE_100_PERCENT = 1e9 // 1e9 = 100%
/**
* Arguments for flat fee instruction
*/
export class FlatFeeArgs implements IArgsData {
public static readonly CODER = new FlatFeeArgsCoder()
constructor(public readonly fee: bigint) {
assert(fee >= 0n && fee <= UINT_32_MAX, `Invalid fee: ${fee}. Must be a valid uint32`)
assert(fee < BigInt(FEE_100_PERCENT), `Fee out of range: ${fee}. Must be < ${FEE_100_PERCENT}`)
}
/**
* Creates a FlatFeeArgs instance from basis points
* @param bps - Fee in basis points (10000 bps = 100%)
*/
public static fromBps(bps: number): FlatFeeArgs {
const fee = BigInt(bps * 100000)
return new FlatFeeArgs(fee)
}
toJSON(): Record<string, unknown> {
return {
fee: this.fee.toString(),
}
}
}Coders:
- Implement
IArgsCoder<T>. - Are responsible for binary layout of arguments.
- Must be strictly symmetric:
decode(encode(args)) === args.
export class FlatFeeArgsCoder implements IArgsCoder<FlatFeeArgs> {
encode(args: FlatFeeArgs): HexString {
const builder = new BytesBuilder()
builder.addUint32(args.fee)
return new HexString(add0x(builder.asHex()))
}
decode(data: HexString): FlatFeeArgs {
const iter = BytesIter.BigInt(data.toString())
const fee = iter.nextUint32()
return new FlatFeeArgs(fee)
}
}An Opcode ties together:
- A unique identifier (
Symbol) for this instruction. - The args coder to use for encoding/decoding.
/**
* Applies flat fee to computed swap amount (same rate for exactIn and exactOut)
*/
export const flatFeeXD = new Opcode(Symbol('Fee.flatFeeXD'), FlatFeeArgs.CODER)Once you have an Opcode:
flatFeeXD.createIx(args)produces a typed instruction.ProgramBuildercan add it to a program:builder.add(flatFeeXD.createIx(FlatFeeArgs.fromBps(5))).
To make your instruction usable at runtime, you must place it at the correct index in an instruction set that matches your on-chain VM:
export const myInstructionSet: Opcode<IArgsData>[] = [
/* ... previous opcodes ... */
flatFeeXD,
/* ... */
]ixsSet[index]) must match the opcode index used by your on-chain contract. A mismatch will not fail at encoding time but will execute the wrong instruction at runtime.
The SDK includes pre-configured contract addresses of AquaSwapVMRouter for the following networks:
| Network | Chain ID | Address |
|---|---|---|
| Ethereum | 1 | 0x111111338c5091e8440b67b168bae16a668ac0de |
| BNB Chain | 56 | 0x111111338c5091e8440b67b168bae16a668ac0de |
| Polygon | 137 | 0x111111338c5091e8440b67b168bae16a668ac0de |
| Arbitrum | 42161 | 0x111111338c5091e8440b67b168bae16a668ac0de |
| Avalanche | 43114 | 0x111111338c5091e8440b67b168bae16a668ac0de |
| Gnosis | 100 | 0x111111338c5091e8440b67b168bae16a668ac0de |
| Coinbase Base | 8453 | 0x111111338c5091e8440b67b168bae16a668ac0de |
| Optimism | 10 | 0x111111338c5091e8440b67b168bae16a668ac0de |
| zkSync Era | 324 | 0x111111338c5091e8440b67b168bae16a668ac0de |
| Linea | 59144 | 0x111111338c5091e8440b67b168bae16a668ac0de |
| Unichain | 130 | 0x111111338c5091e8440b67b168bae16a668ac0de |
| Sonic | 146 | 0x111111338c5091e8440b67b168bae16a668ac0de |
| Robinhood Chain | 4663 | 0x111111338c5091e8440b67b168bae16a668ac0de |
| Monad | 143 | 0x111111338c5091e8440b67b168bae16a668ac0de |
| Cronos | 25 | 0x111111338c5091e8440b67b168bae16a668ac0de |
| HyperEVM | 999 | 0x111111338c5091e8440b67b168bae16a668ac0de |
| Arc | 5042 | 0x111111338c5091e8440b67b168bae16a668ac0de |
Access addresses using:
import { AQUA_SWAP_VM_CONTRACT_ADDRESSES, NetworkEnum } from '@1inch/swap-vm-sdk'
const ethereumAddress = AQUA_SWAP_VM_CONTRACT_ADDRESSES[NetworkEnum.ETHEREUM]
const arbitrumAddress = AQUA_SWAP_VM_CONTRACT_ADDRESSES[NetworkEnum.ARBITRUM]The SDK exports:
SwapVMContract- Main contract class for encoding, decoding, and building transactionsAQUA_SWAP_VM_CONTRACT_ADDRESSES- Pre-configured contract addresses by networkAQUA_SWAP_VM_EIP712_DOMAINS,getAquaSwapVmEip712Domain- EIP-712 domain of the deployed routers by network, for hashing signature-based ordersSwappedEvent- Event class for parsing swapped eventsOrder- Order data structureMakerTraits- Maker-side configuration and flagsTakerTraits- Taker-side configuration and flagsABI- Contract ABI exports- Strategies -
AquaAMMStrategy(base),AquaXYCAmmStrategy(usenew()ornewConcentrate({ sqrtPriceMin, sqrtPriceMax })withPrice.toSqrt()bounds;newConcentrate({ rawPriceMin, rawPriceMax })rejects raw prices below 1e5),AquaPeggedAmmStrategy - Instructions - Comprehensive instruction system:
controls- Flow control instructionsbalances- Balance manipulation instructionsinvalidators- Invalidation instructionsxycSwap- XYC swap instructionsconcentrate- Liquidity concentration (e.g.ConcentrateGrowLiquidity2DArgs.fromPrices/fromSqrtPrices, exact;fromRawPricestakes P = tokenGt/tokenLt in 1e18 and rejects values below 1e5)peggedSwap- Pegged-asset swap curve instructions (stableSwapis a deprecated alias)decay- Decay calculation instructionslimitSwap- Limit order instructionsminRate- Minimum rate guard instructionsdutchAuction- Dutch auction instructionsoraclePriceAdjuster- Oracle-based price adjustment (args and opcode definition only, not in_allInstructionsoraquaInstructions)baseFeeAdjuster- Base fee adjustmenttwapSwap- Time-weighted average price instructionsextruction- External instruction callfee- Fee calculation instructions
This SDK is provided under the terms described in LICENSE and THIRD_PARTY_NOTICES.
For any licensing questions or requests, contact: