Starknet Defi logo

Starknet Defi

Organization
keep-starknet-strange
starknet-defi

Execute DeFi operations on Starknet including token swaps via avnu aggregator, DCA recurring buys, STRK staking, and lending/borrowing. Supports gasless transactions.

Overview

Publisherkeep-starknet-strange
Repositorystarknet-agentic
Skill namestarknet-defi
Stars
81
Forks
26
Bundled files
1
LicenseApache-2.0
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 1 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by keep-starknet-strange on GitHub. Read the source before you install it.

Installation

Install the Starknet Defi AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/keep-starknet-strange/starknet-agentic/tree/main/skills/starknet-defi
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/keep-starknet-strange/starknet-agentic.git /tmp/starknet-agentic
mkdir -p .claude/skills
cp -r /tmp/starknet-agentic/skills/starknet-defi .claude/skills/starknet-defi
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Starknet Defi in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Starknet Defi on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Starknet Defi is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Starknet DeFi Skill

Execute DeFi operations on Starknet using avnu aggregator and native protocols.

When to Use

  • Swaps, DCA orders, staking, and lending or borrowing flows on Starknet.
  • Agent workflows that need AVNU routing, paymaster support, or protocol-specific DeFi execution.

When NOT to Use

  • Plain wallet management without DeFi intent.
  • Cairo contract authoring, deployment operations, or security auditing.

Quick Start

  1. Install the AVNU + starknet.js dependencies and point the skill at a funded Starknet account.
  2. Use skills catalog when the flow expands into wallet setup, deployment, or auditing.

Prerequisites

bash
# ethers is a required peer of @avnu/avnu-sdk (snippets use its parseUnits); moment builds DCA frequencies
npm install starknet@^10.8.0 @avnu/avnu-sdk@^4.2.0 ethers@^6.15.0 moment@^2.30.1

Token Swaps (avnu SDK v4)

Get Quote and Execute Swap

typescript
import {
  getQuotes,
  executeSwap,
  fetchVerifiedTokenBySymbol,
  type QuoteRequest,
} from "@avnu/avnu-sdk";
import { Account, RpcProvider, ETransactionVersion } from "starknet";

const provider = new RpcProvider({ nodeUrl: process.env.STARKNET_RPC_URL });

// starknet.js v10: Account uses an options object; provider calls go through account.provider
const account = new Account({
  provider,
  address,
  signer: privateKey,
  transactionVersion: ETransactionVersion.V3,
});

// Resolve token addresses via avnu SDK (or use MCP server's TokenService)
const eth = await fetchVerifiedTokenBySymbol("ETH");
const strk = await fetchVerifiedTokenBySymbol("STRK");
// Returns undefined when the symbol is not a verified/unruggable token
if (!eth || !strk) throw new Error("Token not found in avnu token list");

// SDK v4: getQuotes takes QuoteRequest object directly
const quoteParams: QuoteRequest = {
  sellTokenAddress: eth.address,
  buyTokenAddress: strk.address,
  sellAmount: BigInt(10 ** 17), // 0.1 ETH
  takerAddress: account.address,
};

const quotes = await getQuotes(quoteParams);
const bestQuote = quotes[0];

// SDK v4: executeSwap takes single object param
const result = await executeSwap({
  provider: account,
  quote: bestQuote,
  slippage: 0.01, // 1%
  executeApprove: true,
});
console.log("Tx:", result.transactionHash);

Quote Response Fields (SDK v4)

typescript
// Main fields of the SDK's exported `Quote` type
interface Quote {
  quoteId: string;
  chainId: string;            // executeSwap rejects a quote from another network
  sellTokenAddress: string;
  buyTokenAddress: string;
  sellAmount: bigint;
  buyAmount: bigint;
  sellAmountInUsd: number;
  buyAmountInUsd: number;
  priceImpact: number;        // In basis points (15 = 0.15%)
  gasFees: bigint;
  gasFeesInUsd?: number;
  expiry?: number | null;
  routes: Array<{
    name: string;             // e.g., "Ekubo", "JediSwap"
    address: string;
    percent: number;          // e.g., 0.8 = 80%
  }>;
  fee: {
    feeToken: string;
    avnuFees: bigint;
    integratorFees: bigint;
  };
}

Build Swap Calls (for multicall composition)

typescript
import { quoteToCalls } from "@avnu/avnu-sdk";

// Returns AvnuCalls: { chainId, calls }
const { calls } = await quoteToCalls({
  quoteId: bestQuote.quoteId,
  takerAddress: account.address,
  slippage: 0.01,
  executeApprove: true,
});
// `calls` can be combined with other calls in account.execute([...calls, ...otherCalls])

Gasless Swap (Pay Gas in Token) - SDK v4 + PaymasterRpc

typescript
import { getQuotes, executeSwap } from "@avnu/avnu-sdk";
import { PaymasterRpc } from "starknet";

const quotes = await getQuotes(quoteParams);
const bestQuote = quotes[0];

// SDK v4: Use PaymasterRpc from starknet.js
// Mainnet: https://starknet.paymaster.avnu.fi
// Sepolia: https://sepolia.paymaster.avnu.fi
const paymaster = new PaymasterRpc({
  nodeUrl: process.env.AVNU_PAYMASTER_URL || "https://starknet.paymaster.avnu.fi",
});

const result = await executeSwap({
  provider: account,
  quote: bestQuote,
  slippage: 0.01,
  executeApprove: true,
  paymaster: {
    active: true,
    provider: paymaster,
    params: {
      version: "0x1",
      feeMode: {
        mode: "default",
        gasToken: "0x033068f6539f8e6e6b131e6b2b814e6c34a5224bc66947c47dab9dfee93b35fb", // USDC
      },
    },
  },
});

DCA (Dollar Cost Averaging)

Create DCA Order

typescript
import { executeCreateDca, type CreateDcaOrder } from "@avnu/avnu-sdk";
import { parseUnits } from "ethers";
import moment from "moment";

// Amounts are base-unit decimal strings; cycles = sellAmount / sellAmountPerCycle
const dcaOrder: CreateDcaOrder = {
  sellTokenAddress: usdcAddress,
  buyTokenAddress: strkAddress,
  sellAmount: parseUnits("100", 6).toString(),        // Total 100 USDC
  sellAmountPerCycle: parseUnits("10", 6).toString(), // 10 USDC per cycle -> 10 cycles
  frequency: moment.duration(1, "day"),               // moment.Duration object, not string
  pricingStrategy: {},                                // Market order; or { tokenToMinAmount, tokenToMaxAmount } (hex)
  traderAddress: account.address,
};

const result = await executeCreateDca({
  provider: account,
  order: dcaOrder,
});
console.log("Tx:", result.transactionHash);

Check and Cancel DCA

typescript
import { getDcaOrders, executeCancelDca, DcaOrderStatus } from "@avnu/avnu-sdk";

// Returns Page<DcaOrder>; the orders are in `content`
const { content: orders } = await getDcaOrders({
  traderAddress: account.address,
  status: DcaOrderStatus.ACTIVE, // INDEXING | ACTIVE | CLOSED
});

// Cancel an order (unspent funds return to the trader)
const [order] = orders;
if (order) {
  await executeCancelDca({
    provider: account,
    orderAddress: order.orderAddress,
  });
}

STRK Staking

Stake STRK

typescript
import { executeStake, getAvnuStakingInfo } from "@avnu/avnu-sdk";
import { parseUnits } from "ethers";

// Get avnu's delegation pools
const stakingInfo = await getAvnuStakingInfo();
// stakingInfo.delegationPools[i] = { poolAddress, tokenAddress, stakedAmount, stakedAmountInUsd, apr }
const strkPool = stakingInfo.delegationPools.find(
  (pool) => BigInt(pool.tokenAddress) === BigInt(TOKENS.STRK),
);
if (!strkPool) throw new Error("avnu STRK delegation pool not found");

const result = await executeStake({
  provider: account,
  poolAddress: strkPool.poolAddress,
  amount: parseUnits("100", 18), // 100 STRK
});

Get User Staking Info

typescript
import { getUserStakingInfo } from "@avnu/avnu-sdk";

const userInfo = await getUserStakingInfo(TOKENS.STRK, account.address);
console.log("Staked:", userInfo.amount);
console.log("Unclaimed rewards:", userInfo.unclaimedRewards);

Claim Rewards

typescript
import { executeClaimRewards } from "@avnu/avnu-sdk";

// Claim and restake (compound)
await executeClaimRewards({
  provider: account,
  poolAddress: poolAddress,
  restake: true,
});

Unstake

typescript
import { executeInitiateUnstake, executeUnstake } from "@avnu/avnu-sdk";
import { parseUnits } from "ethers";

// Step 1: Initiate (starts the 7-day unbonding period)
await executeInitiateUnstake({
  provider: account,
  poolAddress: poolAddress,
  amount: parseUnits("50", 18),
});

// Step 2: Complete unstake (after cooldown period)
await executeUnstake({
  provider: account,
  poolAddress: poolAddress,
});

Market Data

Token Prices

typescript
import { getPrices, fetchTokens, fetchVerifiedTokenBySymbol } from "@avnu/avnu-sdk";

// Get token by symbol (undefined if not a verified/unruggable token)
const strk = await fetchVerifiedTokenBySymbol("STRK");
if (!strk) throw new Error("STRK not found in avnu token list");

// Get prices for multiple tokens (1-50 per request)
const prices = await getPrices([ethAddress, strk.address, usdcAddress]);
// prices = [{ address, decimals, starknetMarket: { usd } | null, globalMarket: { usd } | null }, ...]
const strkUsd = prices.find((p) => BigInt(p.address) === BigInt(strk.address))?.starknetMarket?.usd;

// Browse tokens with pagination (returns Page<Token>; tokens are in `content`)
const { content: tokens } = await fetchTokens({ page: 0, size: 20, tags: ["Verified"] });

Protocol Reference

ProtocolOperationsNotes
avnuSwap aggregation, DCA, gaslessBest-price routing across all DEXs
EkuboAMM, concentrated liquidityHighest TVL on Starknet
JediSwapAMM, classic poolsV2 with concentrated liquidity
zkLendLending, borrowingVariable and stable rates
NostraLending, borrowingMulti-asset pools

Configuration

VariablePurposeDefault
STARKNET_RPC_URLStarknet JSON-RPC endpointRequired
STARKNET_ACCOUNT_ADDRESSAgent's account addressRequired
STARKNET_PRIVATE_KEYAgent's signing keyRequired
AVNU_BASE_URLavnu API base URLhttps://starknet.api.avnu.fi
AVNU_PAYMASTER_URLavnu paymaster URLhttps://starknet.paymaster.avnu.fi
AVNU_API_KEYOptional avnu integrator keyNone

avnu URL Reference

NetworkAPI URLPaymaster URL
Mainnethttps://starknet.api.avnu.fihttps://starknet.paymaster.avnu.fi
Sepoliahttps://sepolia.api.avnu.fihttps://sepolia.paymaster.avnu.fi

Error Handling

typescript
import { executeSwap, ContractError, type Quote } from "@avnu/avnu-sdk";
import type { AccountInterface } from "starknet";

async function safeSwap(account: AccountInterface, quote: Quote, slippage = 0.01) {
  try {
    return await executeSwap({
      provider: account,
      quote,
      slippage,
      executeApprove: true,
    });
  } catch (error) {
    // avnu API errors are plain Errors; contract reverts are ContractError with a revertError
    const message =
      error instanceof ContractError ? `${error.message} ${error.revertError}`
      : error instanceof Error ? error.message
      : String(error);
    if (message.includes("Invalid chainId")) {
      throw new Error("Quote and account are on different networks");
    }
    if (message.includes("INSUFFICIENT_BALANCE")) {
      throw new Error("Not enough tokens for swap");
    }
    if (message.includes("SLIPPAGE") || message.includes("Insufficient tokens received")) {
      // Retry with higher slippage
      return await executeSwap({
        provider: account,
        quote,
        slippage: slippage * 2,
        executeApprove: true,
      });
    }
    if (message.includes("QUOTE_EXPIRED")) {
      throw new Error("Quote expired. Please retry the operation.");
    }
    if (message.includes("INSUFFICIENT_LIQUIDITY")) {
      throw new Error("Insufficient liquidity. Try a smaller amount.");
    }
    throw error;
  }
}

References

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Starknet Defi AI skill do?

Execute DeFi operations on Starknet including token swaps via avnu aggregator, DCA recurring buys, STRK staking, and lending/borrowing. Supports gasless transactions.

Why use Starknet Defi on TypingMind?

Because you install it once and use it with any model. Starknet Defi is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Starknet Defi in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/keep-starknet-strange/starknet-agentic/tree/main/skills/starknet-defi. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Starknet Defi?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Starknet Defi?

As many as you like. As long as a model supports skills, you can use Starknet Defi with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Starknet Defi AI skill free?

Yes. It is published on GitHub by keep-starknet-strange under the Apache-2.0 license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇