### Example Usage of Staking Class Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/products/liquid-staking A practical example demonstrating the typical workflow of using the Staking class: initializing the SDK, fetching validators, staking SUI, and checking staking positions. This serves as a quick start guide. ```typescript const afSdk = new Aftermath("MAINNET"); await afSdk.init(); const staking = afSdk.Staking(); // Get active validators and APYs const validators = await staking.getActiveValidators(); const apys = await staking.getValidatorApys(); // Stake SUI const stakeTx = await staking.getStakeTransaction({ walletAddress: "0x...", suiStakeAmount: BigInt("1000000000"), // 1 SUI validatorAddress: validators[0].suiAddress, }); // Check staking positions const positions = await staking.getStakingPositions({ walletAddress: "0x...", }); // Unstake atomic const unstakeTx = await staking.getUnstakeTransaction({ walletAddress: "0x...", afSuiUnstakeAmount: BigInt("1000000000"), // 1 afSUI isAtomic: true, ``` -------------------------------- ### Full Example Usage Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/products/prices An end-to-end example demonstrating the initialization of the SDK, accessing the Prices module, and fetching price data for both a single coin (SUI) and multiple coins. ```typescript const afSdk = new Aftermath("MAINNET"); await afSdk.init(); const prices = afSdk.Prices(); // Get price info for SUI const suiPriceInfo = await prices.getCoinPriceInfo({ coin: "0x2::sui::SUI", }); // Get prices for multiple coins const multiPrices = await prices.getCoinsToPrice({ coins: [ "0x2::sui::SUI", "0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN", ], }); console.log(`SUI Price: $${suiPriceInfo.price}`); console.log(`24h Change: ${suiPriceInfo.priceChange24HoursPercentage}%`); ``` -------------------------------- ### Complete User Data Example Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/utils/users-data A comprehensive example demonstrating the full workflow: setting up the SDK, creating a user public key via signing, and then retrieving the user's public key. It includes environment variable loading and keypair management. ```typescript import { Aftermath } from "aftermath-ts-sdk"; import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519"; import dotenv from "dotenv"; dotenv.config(); const privateKeyHex = String(process.env.SECRET); // Use your own secret key const keyPair = Ed25519Keypair.fromSecretKey(privateKeyHex); const walletAddress = keyPair.getPublicKey().toSuiAddress(); const aftermath = new Aftermath("MAINNET"); const userData = aftermath.UserData(); const test = async () => { const messageToSign = userData.createUserAccountMessageToSign(); const message = new TextEncoder().encode(JSON.stringify(messageToSign)); const signedMessage = await keyPair.signPersonalMessage(message); const success = await userData.createUserPublicKey({ ...signedMessage, walletAddress, }); const userPk = await userData.getUserPublicKey({ walletAddress, }); console.log({ success, userPk }); }; test(); ``` -------------------------------- ### Install Aftermath TS SDK Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk Installs the Aftermath Finance TypeScript SDK using npm. This is the first step to integrate the SDK into your project. ```bash npm i aftermath-ts-sdk ``` -------------------------------- ### Aftermath Finance SDK Example Usage Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/products/farms Demonstrates common operations using the Aftermath Finance SDK, such as initializing the SDK, retrieving staking pools, fetching user positions, creating stake transactions, and harvesting rewards. This example showcases the SDK's asynchronous methods for interacting with the Aftermath finance protocol. ```typescript const afSdk = new Aftermath("MAINNET"); await afSdk.init(); const farms = afSdk.Farms(); // Get all staking pools const stakingPools = await farms.getAllStakingPools(); // Get user's staked positions const stakedPositions = await farms.getOwnedStakedPositions({ walletAddress: "0x...", }); // Create a new staking position const stakingPool = stakingPools[0]; const stakeTx = await stakingPool.getStakeTransaction({ stakeAmount: BigInt("1000000"), lockDurationMs: 2592000000, // 30 days walletAddress: "0x...", }); // Harvest rewards from a position const position = stakedPositions[0]; const harvestTx = await position.getHarvestRewardsTransaction({ walletAddress: "0x...", stakingPool: stakingPool, }); ``` -------------------------------- ### Basic Trading Example Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/products/router A comprehensive example demonstrating a typical trading workflow using the Router. It covers initialization, fetching a trade route based on input amount, and generating the necessary transaction to execute the trade. ```typescript // Initialize router const afSdk = new Aftermath("MAINNET"); await afSdk.init(); const router = afSdk.Router(); // Get a trade route const route = await router.getCompleteTradeRouteGivenAmountIn({ coinInType: "0x2::sui::SUI", coinOutType: "0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN", coinInAmount: BigInt(10_000_000_000), referrer: "0x...", }); // Generate transaction for the route const tx = await router.getTransactionForCompleteTradeRoute({ walletAddress: "0x...", completeRoute: route, slippage: 0.01, }); ``` -------------------------------- ### Example Usage: Coin Operations Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/utils/coin A comprehensive example demonstrating the practical application of the Coin class methods, from fetching coin data to performing currency conversions and displaying values. ```typescript const afSdk = new Aftermath("MAINNET"); await afSdk.init(); const coin = afSdk.Coin(); // Get coin information const metadata = await coin.getCoinMetadata("0x2::sui::SUI"); const priceInfo = await coin.getPrice("0x2::sui::SUI"); const decimals = await coin.getCoinsToDecimals({ coins: ["0x2::sui::SUI"], }); // Convert amounts const onChainAmount = Coin.normalizeBalance(1.5, 9); const displayAmount = Coin.balanceWithDecimals(1500000000n, 9); const usdValue = Coin.balanceWithDecimalsUsd(1500000000n, 9, priceInfo.price); console.log(`Price: $${priceInfo.price}`); console.log(`24h Change: ${priceInfo.priceChange24HoursPercentage}%`); console.log(`Amount: ${displayAmount} SUI ($${usdValue})`); ``` -------------------------------- ### Get One-Time Admin Caps Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/products/farms Retrieves one-time administrative capabilities (admin caps) for staking pools associated with a wallet address. These are typically used for initial setup or specific administrative tasks. ```typescript // Get one-time admin caps const adminCaps = await farms.getOwnedStakingPoolOneTimeAdminCaps({ walletAddress: "0x...", }); ``` -------------------------------- ### Initialize Aftermath SDK and Farms Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/products/farms Demonstrates how to create an instance of the Aftermath SDK for a specific network (e.g., MAINNET) and initialize it. It then shows how to access the Farms module from the SDK instance. ```typescript const afSdk = new Aftermath("MAINNET"); await afSdk.init(); // initialize provider const farms = afSdk.Farms(); ``` -------------------------------- ### Quick Start: Aftermath SDK Integration Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk Demonstrates simplified integration with the Aftermath SDK for common tasks. It shows how to initialize the SDK with a network environment and access various financial protocols like Router, Pools, Staking, Farms, and DCA. ```typescript const afSdk = new Aftermath("MAINNET"); // "MAINNET" | "TESTNET" await afSdk.init(); // initialize provider // Access protocols const router = afSdk.Router(); const pools = afSdk.Pools(); const staking = afSdk.Staking(); const farms = afSdk.Farms(); const dca = afSdk.Dca(); ``` -------------------------------- ### Initialize Aftermath SDK and Staking Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/products/liquid-staking Demonstrates how to initialize the Aftermath SDK for a specific network and access the Staking class. This is the first step before performing any staking operations. ```typescript const afSdk = new Aftermath("MAINNET"); await afSdk.init(); // initialize provider const staking = afSdk.Staking(); ``` -------------------------------- ### Initialize Aftermath SDK and Prices Module Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/products/prices Demonstrates how to initialize the Aftermath SDK for a specific network (e.g., MAINNET) and then access the Prices module for price-related operations. ```typescript const afSdk = new Aftermath("MAINNET"); await afSdk.init(); // initialize provider const prices = afSdk.Prices(); ``` -------------------------------- ### Get Multiple Coins Current Prices Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/products/prices Retrieves the current prices in USD for a list of specified coins. ```typescript const prices = await prices.getCoinsToPrice({ coins: ["0x2::sui::SUI", "0x..."], }); console.log(prices); /* { "0x2::sui::SUI": 1.23, "0x...": 4.56 } */ ``` -------------------------------- ### Get Coin Information Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/utils/coin Fetches detailed information about coins, including their decimal places, metadata, and current prices. Supports fetching for single or multiple coins. ```typescript // Get coin decimals const decimals = await coin.getCoinsToDecimals({ coins: ["0x2::sui::SUI"], }); // Get coin metadata const metadata = await coin.getCoinMetadata("0x2::sui::SUI"); // Get metadata for multiple coins const metadatas = await coin.getCoinMetadatas({ coins: ["0x2::sui::SUI", "0x..."], }); // Get coin price const priceInfo = await coin.getPrice("0x2::sui::SUI"); // Get verified coins const verifiedCoins = await coin.getVerifiedCoins(); ``` -------------------------------- ### Example Usage: Authorized Requests Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/utils/authorization Demonstrates a complete workflow: initializing the SDK, setting up authorization with a private key, making authorized API calls for pools and prices, and cleaning up by stopping authorization. ```typescript const afSdk = new Aftermath("MAINNET"); await afSdk.init(); // Initialize with private key const keypair = Helpers.keypairFromPrivateKey("your-private-key"); const stopAuth = await afSdk.Auth().init({ signMessageCallback: async ({ message }) => { const { signature } = await keypair.signPersonalMessage(message); return { signature }; }, walletAddress: keypair.toSuiAddress(), }); // Make authorized requests const pools = await afSdk.Pools().getAllPools(); const prices = await afSdk.Prices().getCoinPrice({ coin: "0x2::sui::SUI", }); // Clean up stopAuth(); ``` -------------------------------- ### Get Staked Position Unlock Timestamp Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/products/farms Retrieves the timestamp when a staked position will become unlocked and available for withdrawal. This is relevant for positions with lock durations. ```typescript // Get unlock timestamp const unlockTime = position.unlockTimestamp(); ``` -------------------------------- ### Full Example Usage Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/products/dynamic-gas Demonstrates the end-to-end process of using the DynamicGas service. This includes initializing the SDK, preparing a transaction, setting a custom gas coin type, signing the transaction with both user and sponsor signatures, and executing it on the Sui network. ```typescript const afSdk = new Aftermath("MAINNET"); await afSdk.init(); const dynamicGas = afSdk.DynamicGas(); // Create some transaction const tx = new Transaction(); // Add some move calls to transaction // ... // Use USDC to pay for gas instead of SUI const { txBytes, sponsoredSignature } = await dynamicGas.getUseDynamicGasForTx({ tx, walletAddress: "0x", gasCoinType: "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC", }); // Derive updated transaction from response const updatedTx = Transaction.from(res.txBytes); // Sign transaction const signedTxData = await signTransaction({ ransaction: updatedTx, }); // Create Sui client const client = new SuiClient({ transport: new SuiHTTPTransport({ url: "https://fullnode.mainnet.sui.io:443", }), }); // Execute transaction const transactionResponse = await client.provider.executeTransactionBlock({ ransactionBlock: signedTxData.txBytes, // Requires both user's signature and sponsor's signature signature: [signedTxData.signature, sponsoredSignature], requestType: "WaitForEffectsCert", options: { showEvents: true, showBalanceChanges: true, showEffects: true, showObjectChanges: true, }, }); console.log("Transaction Response:", transactionResponse); ``` -------------------------------- ### Get All Staking Pools Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/products/farms Retrieves all available staking pools within the system. This method is useful for obtaining a comprehensive list of active staking opportunities. ```typescript // Get all staking pools const allPools = await farms.getAllStakingPools(); ``` -------------------------------- ### Initialize Router Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/products/router Demonstrates how to create a Router instance by first initializing the Aftermath SDK with a network provider and then accessing the router service. ```typescript const afSdk = new Aftermath("MAINNET"); await afSdk.init(); // initialize provider const router = afSdk.Router(); ``` -------------------------------- ### Initialize SDK Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/utils/authorization Initializes the Aftermath SDK for a specific network and retrieves the authorization module for managing rate limits. ```typescript const afSdk = new Aftermath("MAINNET"); await afSdk.init(); // initialize provider const auth = afSdk.Auth(); ``` -------------------------------- ### Router Constants Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/products/router Provides access to constant values used by the Router class, such as configuration limits. For example, `maxExternalFeePercentage` defines the maximum allowed percentage for external fees. ```typescript Router.constants = { maxExternalFeePercentage: 0.5, // Maximum allowed external fee (50%) }; ``` -------------------------------- ### Get User Public Key Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/utils/users-data Retrieves a user's public key by providing their wallet address. This method is used to fetch existing public key information associated with a wallet. ```typescript const publicKey = userData.getUserPublicKey({ walletAddress: "0x.." }); ``` -------------------------------- ### Initialize Aftermath SDK and Coin Module Source: https://docs.aftermath.finance/developers/aftermath-ts-sdk/utils/coin Demonstrates how to initialize the Aftermath SDK with a network provider and access the Coin module for subsequent operations. ```typescript const afSdk = new Aftermath("MAINNET"); await afSdk.init(); // initialize provider const coin = afSdk.Coin(); ```