Gasless
Import the ethers and @kaiachain/ethers-ext/v6 packages to add gasless features on ethers.js
The ERC20 token address (TEST token on Kairos testnet).
Declare senderAddr: The wallet address of the sender performing the swap and senderPriv: The sender’s private key for signing transactions.
Creating a JSON-RPC provider and an instance of Wallet with the Kaia Kairos testnet
A minimal ABI for the ERC20 token, including functions to query decimals, symbol, allowance, and balance.
A fixed amount of 0.01 KAIA (in wei) that the sender wants to receive from the swap to fund a subsequent application transaction.
Show token at address:
Creates an instance of an ERC20 token contract to interact with its functions.
Queries the token’s symbol (e.g., “TEST” for the TEST token).
Queries the token’s decimal places (e.g., 18 for most ERC20 tokens like ETH or TEST).
Queries the sender’s balance of the ERC20 token.
Display the sender’s initial balances.
Retrieves an instance of the GaslessSwapRouter contract, which facilitates gasless token swaps on the Kaia blockchain.
Retrieves the blockchain address of the GaslessSwapRouter contract.
Checks whether the specified ERC20 token is supported by the GaslessSwapRouter for gasless swaps.
Retrieves the commission rate charged by the GaslessSwapRouter for facilitating gasless swaps.
Show the GaslessSwapRouter address, true if the token is supported and commission rate.
Checks how many tokens the GaslessSwapRouter is allowed to spend on behalf of the sender.
Determines if an approval transaction is needed by checking if the allowance is zero.
Initializes an empty array to store transactions that will be sent later.
Checks if an approval transaction is needed based on the approveRequired flag. Generates an ERC20 approve transaction to allow the GaslessSwapRouter to spend the sender’s tokens.
Retrieves the current gas price from the blockchain and converts it to a JavaScript number.
Calculates the total KAIA amount (in wei) that the sender must repay to the block miner for funding the gas costs of the transactions.
Calculates the minimum amount of KAIA (in wei) that the swap must produce to cover the repayment, commission, and the desired application transaction fee.
Calculates the amount of ERC20 tokens to swap to receive at least minAmountOut KAIA, accounting for slippage.
Checks if the sender’s ERC20 token balance is insufficient to cover the amount of tokens required for the swap.
Generates the swap transaction to exchange a specified amount of ERC20 tokens for at least a minimum amount of KAIA, incorporating gasless repayment logic. Adds the swap transaction to the txs array for batch execution.
Sends all transactions in the txs array using the sender’s wallet. Iterates over the sent transactions to log their details.
Waits for the transaction to be mined and retrieves its transaction receipt.
Listing the block's transactions related to the sender
Final balance of the sender