Below are the two methods to get a quote for a swap from a given route using JSON-RPC or REST-API:

When providing HBAR in the path array, use the wrapped HBAR token ID (WHBAR).

Get Output Quote from Input Amount

No gas cost

Get the output amounts from a given input amount and a swap route.

Function name: getAmountsOut

Parameter NameDescription
uint amountInThe input token amount in its smallest unit
address[] pathAn ordered list of token EVM addresses
function getAmountsOut(
  uint amountIn,
  address[] calldata path
) external view returns (uint[] memory amounts);

Code Overview

Resources:

Typescript
import * as ethers from 'ethers'; //V6

//Set one of Hedera's JSON RPC Relay as the provider
const provider = new ethers.JsonRpcProvider(hederaJsonRelayUrl, '', {
  batchMaxCount: 1, //workaround for V6
});

//ABI data for the getAmountsOut
const abi = ['function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts)'];

//Load the ABI
const abiInterfaces = new ethers.Interface(abi);

//Example route
const tokenIn = '0x' + TokenId.fromString(whbarTokenId).toSolidityAddress();
const tokenOut = '0x' + TokenId.fromString(sauceTokenId).toSolidityAddress();
const route = [tokenIn, tokenOut];

const routerContract = new ethers.Contract(routerEvmAddress, abiInterfaces.fragments, provider);
const result = await routerContract.getAmountsOut(inputAmountInSmallestUnit, route);
const amounts = result; //uint[] amounts
const finalOutputAmount = amounts[amounts.length - 1]; //in token's smallest unit

Get Input Quote from Output Amount

No gas cost

Get the input amounts from a given output amount and a swap route.

Function name: getAmountsIn

Parameter NameDescription
uint amountOutThe output token amount in its smallest unit
address[] pathAn ordered list of token EVM addresses
function getAmountsIn(
  uint amountOut,
  address[] calldata path
) external view returns (uint[] memory amounts);

Code Overview

Resources:

Typescript
import * as ethers from 'ethers'; //V6

const networkId = 'testnet';
const provider = new ethers.JsonRpcProvider(`https://${networkId}.hashio.io/api`, '', {
  batchMaxCount: 1,
});

//ABI data for the getAmountsIn
const abi = ['function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts)'];

//Load the ABI
const abiInterfaces = new ethers.Interface(abi);

//Example route (WHBAR > SAUCE)
const tokenIn = '0x' + TokenId.fromString(whbarTokenId).toSolidityAddress();
const tokenOut = '0x' + TokenId.fromString(sauceTokenId).toSolidityAddress();
const route = [tokenIn, tokenOut];

const routerContract = new ethers.Contract(routerEvmAddress, abiInterfaces.fragments, provider);
const result = await routerContract.getAmountsIn(outputAmountInSmallestUnit, route);
const amounts = results; //uint[] amounts
const finalInputAmount = amounts[0]; //in token's smallest unit