Skip to content
lending-instructions logo

Kapan Lending Instructions System

lending-instructions

Load when working with KapanRouter instructions, UTXO tracking, flash loan flows, or debugging transaction failures

SKILL.md

Full skill instructions

Kapan Lending Instructions System

The KapanRouter uses a UTXO-based instruction system where each operation can consume inputs from previous outputs and produce new outputs. Understanding this is critical for building correct flows.

Core Concepts

UTXO (Unspent Transaction Output)

Each instruction can create outputs that subsequent instructions reference by index. The router maintains an outputs[] array during execution.

Two Instruction Types

  1. Router Instructions (protocolName: "router") - Handled by KapanRouter directly
  2. Protocol Instructions (protocolName: "aave", "compound", etc.) - Delegated to gateways

Router Instructions

Defined in utils/​v2/​instructionHelpers.ts:4-13:

TypeCreates UTXO?Description
FlashLoanYesBorrows from flash loan provider, creates output for repayment amount
PullTokenNoPulls tokens from user to router (requires user approval)
PushTokenNoSends tokens from UTXO to user
ToOutputYesCreates a UTXO from hardcoded amount/​token (no actual transfer)
ApproveYes (empty)Approves gateway to spend UTXO. Creates empty output for index sync!
SplitYes (2)Splits UTXO into fee portion + remainder (for Aave flash loan fees)
AddYesCombines two UTXOs of same token
SubtractYesSubtracts one UTXO from another

Critical: Approve Creates Empty Output

The Approve instruction creates an empty output to maintain index synchronization. This is why output indices jump after approvals:

// After Approve(2), the next output is index 3, not 2!
addRouter(encodeApprove(2, "aave"), true); // createsUtxo=true

Lending Operations

Defined in utils/​v2/​instructionHelpers.ts:26-36:

OpCreates UTXO?Description
DepositNoSupply tokens to lending protocol
DepositCollateralNoSupply as collateral (Morpho, Compound)
WithdrawCollateralYesWithdraw collateral, creates output
BorrowYesBorrow tokens, creates output
RepayYesRepay debt, creates refund output (usually 0)
GetBorrowBalanceYesQuery debt balance, creates output with amount
GetSupplyBalanceYesQuery supply balance, creates output with amount
SwapYes (2)Swap via DEX, creates (tokenOut, refund) outputs
SwapExactOutYes (2)Exact output swap, creates (tokenOut, refund) outputs

Input Index Conventions

  • inputIndex: 999 - Ignore input, use amount parameter directly
  • inputIndex: 0-998 - Read amount/​token from outputs[inputIndex]

Flash Loan Providers

enum FlashLoanProvider {
  BalancerV2 = 0,  // 0% fee
  BalancerV3 = 1,  // 0% fee  
  Aave = 2,        // ~5-9 bps fee
  ZeroLend = 3,    // ~5 bps fee
  UniswapV3 = 4,   // Requires pool address
  Morpho = 5,      // 0% fee
}

Important: Aave/​ZeroLend flash loans create an output with the repayment amount (principal + fee), not the borrowed amount. The router receives the principal but must track repayment separately.

Common Flows

Basic Deposit

[
  PullToken(amount, token, user),      // No output
  Approve(0, protocol),                // Output[0] = empty (for sync)
  DepositCollateral(token, user, 0, inputIndex=0),  // No output
]

Withdraw Max

[
  GetSupplyBalance(token, user),       // Output[0] = balance
  WithdrawCollateral(token, user, inputIndex=0),  // Output[1] = withdrawn
  PushToken(1, user),                  // No output
]

Flash Loan Pattern

[
  ToOutput(amount, token),             // Output[0] = virtual UTXO
  FlashLoan(provider, inputIndex=0),   // Output[1] = repayment amount
  // ... use borrowed funds (router has Output[0] worth of tokens)
  // ... must leave Output[1] worth in router for repayment
]

Aave Flash Loan with Fee (Max Withdrawal)

When using Aave flash loans for max operations, use Split to account for fees:

[
  GetSupplyBalance(token),             // Output[0] = 100
  Split(0, 9),                         // Output[1] = 0.09 (fee buffer), Output[2] = 99.91
  FlashLoan(Aave, 2),                  // Output[3] = 100 (repayment), router has 99.91
  // ... operations using Output[2] (what we actually have)
  // ... withdraw Output[3] worth to repay
]

File Locations

  • Instruction Helpers: packages/​nextjs/​utils/​v2/​instructionHelpers.ts
  • Flow Builders: packages/​nextjs/​hooks/​useKapanRouterV2.tsx:219-936
  • Move Builder: packages/​nextjs/​hooks/​useKapanRouterV2.tsx:1519-1631
  • Starknet Instructions: packages/​nextjs/​hooks/​useStarknetMovePosition.ts

Debugging Tips

  1. Track UTXO indices manually - Draw out the output array as you build instructions
  2. Approve creates empty output - Always increment your expected index after Approve
  3. Flash loan outputs - Remember: Aave Output = repayment (more than borrowed)
  4. Use simulation - simulateInstructions() catches most errors before execution
  5. Check authorization - getAuthorizations() returns needed approvals

Protocol Context Encoding

Different protocols need different context bytes:

// Aave: empty context
context = "0x"

// Compound: market address
context = encodeAbiParameters([{ type: "address" }], [marketAddress])

// Morpho: full MarketParams tuple
context = encodeMorphoContext({ loanToken, collateralToken, oracle, irm, lltv })

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View