Skip to main content

DeFi Token Swaps

Sphere's DeFi service allows users to easily swap one cryptocurrency for another across various supported chains. This feature integrates with underlying DeFi protocols to find optimal rates and execute swaps, abstracting away much of the complexity involved in direct DEX interactions. Users can choose between "gasless" swaps, where the Stratosphere Network handles gas fees (with a service fee applied), or "normal" swaps, where the user's wallet pays the network transaction fees.

This page explains how to use sphere.defi.swap() to perform these operations.

Prerequisites

  • User Authentication: The user performing the swap must be authenticated.
  • SDK Authenticated: Your Sphere SDK instance must be authenticated with the user's accessToken.
  • Sufficient Balances:
    • For the token being sold (token_to_sell).
    • For "normal" swaps, the user's wallet must also have enough native currency of the chosen chain to cover gas fees.
    • For "gasless" swaps, the user must have enough of token_to_sell to also cover Sphere's service fee, which is deducted from this token.

Refer to wallet and authentication documentation for setup:

import Sphere, {
Environment,
ChainName,
TokenSymbol, // Useful for identifying common tokens
SwapRequest,
SwapResponse,
SwapFlow,
} from "@stratosphere/wallet";

const sphere = new Sphere({
apiKey: "YOUR_API_KEY",
environment: Environment.DEVELOPMENT,
});

// Example: After user login
// sphere.setBearerToken("USER_ACCESS_TOKEN");

Performing a Token Swap (sphere.defi.swap)

The sphere.defi.swap() method is the core function for executing token swaps.

Intuition: Imagine using a currency exchange. You specify which currency (token) you have, which one you want, and how much you want to trade. Sphere finds a good rate and handles the exchange for you. You can choose a "full-service" option (gasless, Sphere handles network fees for a service charge) or a "self-service" option (normal, you pay network fees directly).

Flow:

  1. Your application gathers swap details from the user (chain, tokens to sell/buy, amount, flow type).
  2. It calls sphere.defi.swap() with these details.
  3. The Sphere SDK communicates with the Stratosphere Network.
  4. Stratosphere Network interacts with DeFi protocols to get quotes and execute the swap.
    • For gasless flow, it manages gas payment.
    • For normal flow, the user's wallet will be prompted to approve and sign the transaction, paying gas.
  5. A response is returned indicating the outcome of the swap submission.

Diagram: Token Swap Flow

SDK Usage: Performing a Swap

async function executeTokenSwap(
chain: ChainName,
flow: SwapFlow,
tokenToSell: string, // Can be TokenSymbol or contract address string
tokenToBuy: string, // Can be TokenSymbol or contract address string
valueToSell: string, // Amount of tokenToSell as a string, e.g., "10.5"
tokenToSellAddress?: string, // Optional: contract address if tokenToSell is not a known symbol
tokenToBuyAddress?: string // Optional: contract address if tokenToBuy is not a known symbol
): Promise<SwapResponse | null> {
if (!sphere.isAuthenticated()) {
console.error("SDK is not authenticated. Please log in the user first.");
return null;
}

try {
const requestPayload: SwapRequest = {
chain,
flow,
token_to_sell: tokenToSell,
token_to_buy: tokenToBuy,
value: valueToSell,
...(tokenToSellAddress && { token_to_sell_address: tokenToSellAddress }),
...(tokenToBuyAddress && { token_to_buy_address: tokenToBuyAddress }),
// amountOut: "...", // Optional: if you want to specify desired output amount (slippage applies)
// isEth: ..., // Optional: if selling native ETH
// isBuyingEth: ..., // Optional: if buying native ETH
};

console.log(
`Initiating swap of ${valueToSell} ${tokenToSell} for ${tokenToBuy} on ${chain} via ${flow} flow...`
);
const response = await sphere.defi.swap(requestPayload);

if (response && response["swap successful"]) {
// Check for the success message
console.log("Swap call successful:", response["swap successful"]);
// The response is minimal. Actual swap confirmation (txHash) would likely
// come via TXConfirmedEvent or need to be looked up based on user activity.
return response;
} else {
console.error("Swap failed or response format unexpected.", response);
return null;
}
} catch (error) {
console.error("Error during token swap:", error);
throw error;
}
}

// Example Usage:
/*
// Swap 100 USDC for ETH on Arbitrum (gasless)
executeTokenSwap(ChainName.ARBITRUM, SwapFlow.GASLESS, "USDC", "ETH", "100")
.then(response => {
if (response) {
console.log("Gasless swap initiated successfully.");
// Monitor events or user's balance for swap completion
}
})
.catch(err => console.error("Gasless swap failed:", err));

// Swap 0.1 WBERA for USDC on Berachain (normal flow, user pays gas)
// Assuming WBERA is TokenSymbol.WBERA and USDC is TokenSymbol.USDC
executeTokenSwap(ChainName.BERACHAIN, SwapFlow.NORMAL, TokenSymbol.WBERA, TokenSymbol.USDC, "0.1")
.then(response => {
if (response) {
console.log("Normal swap initiated. User will be prompted to confirm.");
}
});

// Example with custom token addresses:
executeTokenSwap(
ChainName.POLYGON,
SwapFlow.GASLESS,
"MyCustomSellTokenSymbol", // Display symbol
"MyCustomBuyTokenSymbol", // Display symbol
"500",
"0xSellTokenContractAddress...",
"0xBuyTokenContractAddress..."
);
*/

SwapRequest Parameters:

  • chain: ChainName: The blockchain on which the swap will occur.
  • flow: SwapFlow: Specifies the execution flow:
    • "gasless": Stratosphere Network attempts to cover the gas fees. A service fee, deducted from token_to_sell, will apply (see Transaction Fees).
    • "normal": The user's wallet pays the gas fees for the transaction.
  • token_to_sell: string: The symbol or name of the token the user wants to sell (e.g., "USDC", "ETH").
  • token_to_buy: string: The symbol or name of the token the user wants to buy.
  • value: string: The amount of token_to_sell to be swapped, as a string (e.g., "100", "0.05").
  • token_to_sell_address?: string: Optional. The contract address of token_to_sell. Required if token_to_sell is not a commonly recognized symbol automatically resolved by Sphere.
  • token_to_buy_address?: string: Optional. The contract address of token_to_buy. Required if token_to_buy is not a commonly recognized symbol.
  • amountOut?: string: Optional. The desired minimum amount of token_to_buy the user wishes to receive. If provided, the swap might only execute if this amount can be met (subject to slippage settings at the DEX level).
  • isEth?: boolean: Optional. Set to true if token_to_sell is the native currency of the chain (e.g., selling ETH on Ethereum, MATIC on Polygon).
  • isBuyingEth?: boolean: Optional. Set to true if token_to_buy is the native currency of the chain.

SwapResponse

The provided SwapResponse is { "swap successful": string; }. This indicates the swap request was successfully submitted to the Stratosphere Network for processing. Actual on-chain confirmation, transaction hash, and amounts received would typically be:

  • Communicated via TXConfirmedEvent or TXFailedEvent if sphere.events is used.
  • Reflected in updated user balances fetched via sphere.wallet.getBalances() or sphere.wallet.getTokenBalance().
  • Found by querying transaction history using sphere.transactions.getHistory().

Important Considerations

  • Slippage: Swaps executed on decentralized exchanges (DEXs) are subject to price slippage, especially for large orders or volatile tokens. The actual amount of token_to_buy received might differ slightly from the quoted amount. The amountOut parameter can be used to set a minimum acceptable output