lyra-plugin-onchain 0.1.7 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lyra-plugin-onchain",
3
- "version": "0.1.7",
3
+ "version": "0.1.8",
4
4
  "type": "module",
5
5
  "description": "The Sui on-chain tools for Lyra: SUI transfers, DeepBook market data, Walrus receipts/memory — every write policy-checked, simulated, and recorded on-chain via lyra::policy",
6
6
  "license": "MIT",
@@ -13,28 +13,14 @@
13
13
  "bugs": {
14
14
  "url": "https://github.com/rifkyeasy/lyra/issues"
15
15
  },
16
- "keywords": [
17
- "lyra",
18
- "ai",
19
- "agent",
20
- "sui",
21
- "defi",
22
- "deepbook",
23
- "walrus",
24
- "policy",
25
- "plugin"
26
- ],
16
+ "keywords": ["lyra", "ai", "agent", "sui", "defi", "deepbook", "walrus", "policy", "plugin"],
27
17
  "publishConfig": {
28
18
  "access": "public"
29
19
  },
30
20
  "engines": {
31
21
  "bun": ">=1.1"
32
22
  },
33
- "files": [
34
- "src",
35
- "!src/**/*.test.ts",
36
- "README.md"
37
- ],
23
+ "files": ["src", "!src/**/*.test.ts", "README.md"],
38
24
  "main": "./src/index.ts",
39
25
  "types": "./src/index.ts",
40
26
  "scripts": {
@@ -47,7 +33,10 @@
47
33
  "@mysten/deepbook-v3": "^0.18.0",
48
34
  "@mysten/sui": "^1.40.0",
49
35
  "@mysten/walrus": "^0.6.4",
36
+ "@pythnetwork/pyth-sui-js": "2.2.0",
50
37
  "@scallop-io/sui-scallop-sdk": "^2.4.5",
38
+ "@suilend/sdk": "1.1.99",
39
+ "@suilend/sui-fe": "0.3.49",
51
40
  "lyra-core": "^0.1.2",
52
41
  "navi-sdk": "^1.7.3",
53
42
  "zod": "^3.23.8"
package/src/index.ts CHANGED
@@ -25,6 +25,7 @@ import { makeAccountInfo, makeSuiBalance } from './tools/balance'
25
25
  import { makeCetusQuote } from './tools/cetus'
26
26
  import { makeDeepbookMarkets } from './tools/deepbook'
27
27
  import { makeDefiYields } from './tools/defillama'
28
+ import { makeVoloStake, makeVoloUnstake } from './tools/liquid-stake'
28
29
  import {
29
30
  makeNaviBorrow,
30
31
  makeNaviMarkets,
@@ -36,13 +37,22 @@ import {
36
37
  import { makePolicyCreate, makePolicyShow } from './tools/policy'
37
38
  import { makeProtocolsList } from './tools/protocols'
38
39
  import {
40
+ makeScallopBorrow,
39
41
  makeScallopMarkets,
40
42
  makeScallopPosition,
43
+ makeScallopRepay,
41
44
  makeScallopSupply,
42
45
  makeScallopWithdraw,
43
46
  } from './tools/scallop'
44
47
  import { makeSuiSend } from './tools/send'
45
48
  import { makeStake, makeUnstake } from './tools/stake'
49
+ import {
50
+ makeSuilendBorrow,
51
+ makeSuilendPosition,
52
+ makeSuilendRepay,
53
+ makeSuilendSupply,
54
+ makeSuilendWithdraw,
55
+ } from './tools/suilend'
46
56
  import { makeSwap } from './tools/swap'
47
57
  import { makeWalrusStore } from './tools/walrus'
48
58
  import type { OnchainRuntimeContext } from './types'
@@ -95,16 +105,25 @@ const plugin: NativePlugin = {
95
105
  ctx.registerTool(makeScallopPosition(onchain) as ToolDef)
96
106
  ctx.registerTool(makeScallopSupply(onchain) as ToolDef)
97
107
  ctx.registerTool(makeScallopWithdraw(onchain) as ToolDef)
108
+ ctx.registerTool(makeScallopBorrow(onchain) as ToolDef)
109
+ ctx.registerTool(makeScallopRepay(onchain) as ToolDef)
98
110
  ctx.registerTool(makeNaviMarkets(onchain) as ToolDef)
99
111
  ctx.registerTool(makeNaviPosition(onchain) as ToolDef)
100
112
  ctx.registerTool(makeNaviSupply(onchain) as ToolDef)
101
113
  ctx.registerTool(makeNaviWithdraw(onchain) as ToolDef)
102
114
  ctx.registerTool(makeNaviBorrow(onchain) as ToolDef)
103
115
  ctx.registerTool(makeNaviRepay(onchain) as ToolDef)
116
+ ctx.registerTool(makeSuilendSupply(onchain) as ToolDef)
117
+ ctx.registerTool(makeSuilendWithdraw(onchain) as ToolDef)
118
+ ctx.registerTool(makeSuilendBorrow(onchain) as ToolDef)
119
+ ctx.registerTool(makeSuilendRepay(onchain) as ToolDef)
120
+ ctx.registerTool(makeSuilendPosition(onchain) as ToolDef)
104
121
 
105
- // Native staking (delegate SUI to a validator; min 1 SUI).
122
+ // Staking: native delegation (min 1 SUI) + Volo liquid staking (vSUI).
106
123
  ctx.registerTool(makeStake(onchain) as ToolDef)
107
124
  ctx.registerTool(makeUnstake(onchain) as ToolDef)
125
+ ctx.registerTool(makeVoloStake(onchain) as ToolDef)
126
+ ctx.registerTool(makeVoloUnstake(onchain) as ToolDef)
108
127
  },
109
128
  }
110
129
 
package/src/protocols.ts CHANGED
@@ -43,7 +43,7 @@ export const PROTOCOLS: ProtocolCapability[] = [
43
43
  execute: false,
44
44
  tools: ['deepbook.markets'],
45
45
  llamaProjects: ['deepbook'],
46
- note: 'market data read; on-chain order execution not wired yet',
46
+ note: 'market data read; swaps route through DeepBook via the 7k aggregator',
47
47
  },
48
48
  {
49
49
  id: 'scallop',
@@ -51,8 +51,16 @@ export const PROTOCOLS: ProtocolCapability[] = [
51
51
  category: 'lending',
52
52
  read: true,
53
53
  execute: true,
54
- tools: ['scallop.markets', 'scallop.position', 'scallop.supply', 'scallop.withdraw'],
54
+ tools: [
55
+ 'scallop.markets',
56
+ 'scallop.position',
57
+ 'scallop.supply',
58
+ 'scallop.withdraw',
59
+ 'scallop.borrow',
60
+ 'scallop.repay',
61
+ ],
55
62
  llamaProjects: ['scallop-lending', 'scallop'],
63
+ note: 'full supply / withdraw / borrow / repay',
56
64
  },
57
65
  {
58
66
  id: 'navi',
@@ -60,13 +68,55 @@ export const PROTOCOLS: ProtocolCapability[] = [
60
68
  category: 'lending',
61
69
  read: true,
62
70
  execute: true,
63
- tools: ['navi.markets', 'navi.position', 'navi.supply', 'navi.withdraw'],
71
+ tools: [
72
+ 'navi.markets',
73
+ 'navi.position',
74
+ 'navi.supply',
75
+ 'navi.withdraw',
76
+ 'navi.borrow',
77
+ 'navi.repay',
78
+ ],
64
79
  llamaProjects: ['navi-lending', 'navi-protocol', 'navi'],
65
- note: 'largest Sui lending market by TVL',
80
+ note: 'largest Sui lending market by TVL; full supply / withdraw / borrow / repay',
81
+ },
82
+ {
83
+ id: 'suilend',
84
+ name: 'Suilend',
85
+ category: 'lending',
86
+ read: true,
87
+ execute: true,
88
+ tools: [
89
+ 'suilend.position',
90
+ 'suilend.supply',
91
+ 'suilend.withdraw',
92
+ 'suilend.borrow',
93
+ 'suilend.repay',
94
+ ],
95
+ llamaProjects: ['suilend'],
96
+ note: 'MAIN_POOL market; full supply / withdraw / borrow / repay',
97
+ },
98
+ {
99
+ id: 'native-staking',
100
+ name: 'Sui Native Staking',
101
+ category: 'staking',
102
+ read: false,
103
+ execute: true,
104
+ tools: ['sui.stake', 'sui.unstake'],
105
+ note: 'delegate SUI to a validator (min 1 SUI); classic staking rewards',
106
+ },
107
+ {
108
+ id: 'volo',
109
+ name: 'Volo (Liquid Staking)',
110
+ category: 'staking',
111
+ read: false,
112
+ execute: true,
113
+ tools: ['volo.stake', 'volo.unstake'],
114
+ llamaProjects: ['volo', 'volo-staked-sui'],
115
+ note: 'stake SUI → vSUI, a liquid staking token usable across DeFi while earning',
66
116
  },
67
117
  {
68
118
  id: 'aggregator',
69
- name: 'DEX aggregator (7k / Cetus / FlowX / Bluefin)',
119
+ name: 'DEX aggregator (7k best-route)',
70
120
  category: 'aggregator',
71
121
  read: true,
72
122
  execute: true,
@@ -81,8 +131,12 @@ export const PROTOCOLS: ProtocolCapability[] = [
81
131
  'bluefin',
82
132
  'turbos',
83
133
  'kriya-dex',
134
+ 'aftermath-amm',
135
+ 'aftermath',
136
+ 'momentum',
137
+ 'mmt',
84
138
  ],
85
- note: 'swap executes via the 7k aggregator, routing across Cetus/FlowX/Bluefin/DeepBook',
139
+ note: 'swap executes via the 7k aggregator, routing best price across Cetus / Turbos / FlowX / Bluefin / Aftermath / Momentum / Kriya / DeepBook',
86
140
  },
87
141
  ]
88
142
 
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Volo liquid staking — stake SUI for vSUI (a liquid staking token that keeps
3
+ * earning while remaining tradeable / usable in DeFi), and unstake vSUI back to
4
+ * SUI. Built on navi-sdk's Volo PTB helpers.
5
+ *
6
+ * volo.stake → SUI → vSUI (stake_pool::stake)
7
+ * volo.unstake → vSUI → SUI (stake_pool::unstake)
8
+ *
9
+ * Same guarded pipeline: minimum guard → policy → dry-run simulate → execute →
10
+ * on-chain effects check.
11
+ */
12
+
13
+ import { Transaction, coinWithBalance } from '@mysten/sui/transactions'
14
+ import type { ToolDef } from 'lyra-core'
15
+ import { stakeTovSuiPTB, unstakeTovSui } from 'navi-sdk'
16
+ import { z } from 'zod'
17
+ import { checkMinimum } from '../minimums'
18
+ import { evaluatePolicy, suiToMist } from '../policy'
19
+ import { simulate } from '../simulate'
20
+ import type { OnchainRuntimeContext } from '../types'
21
+
22
+ const SUI_TYPE = '0x2::sui::SUI'
23
+ const VSUI_TYPE = '0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT'
24
+
25
+ const StakeSchema = z.object({
26
+ amount: z.string().min(1).describe('Amount of SUI to liquid-stake (minimum 1 SUI).'),
27
+ })
28
+ type StakeArgs = z.infer<typeof StakeSchema>
29
+
30
+ const UnstakeSchema = z.object({
31
+ amount: z.string().min(1).describe('Amount of vSUI to unstake back to SUI.'),
32
+ })
33
+ type UnstakeArgs = z.infer<typeof UnstakeSchema>
34
+
35
+ export function makeVoloStake(ctx: OnchainRuntimeContext): ToolDef<StakeArgs> {
36
+ return {
37
+ name: 'volo.stake',
38
+ description:
39
+ 'Liquid-stake SUI with Volo and receive vSUI — a liquid staking token that keeps earning staking rewards while remaining tradeable and usable across Sui DeFi (unlike native staking, which locks the position). Minimum 1 SUI. Policy-checked, simulated, then executed.',
40
+ searchHint:
41
+ 'volo liquid stake vsui lst liquid-staking derivative earn yield tradeable sui defi',
42
+ schema: StakeSchema,
43
+ handler: async args => {
44
+ try {
45
+ if (ctx.network !== 'mainnet') return { ok: false, error: 'Volo supports mainnet only' }
46
+ const amountMist = suiToMist(args.amount)
47
+ if (amountMist === undefined || amountMist <= 0n) {
48
+ return { ok: false, error: `invalid amount "${args.amount}"` }
49
+ }
50
+ const tooSmall = checkMinimum('stake', amountMist)
51
+ if (tooSmall) return { ok: false, error: tooSmall }
52
+
53
+ if (ctx.policy) {
54
+ const verdict = evaluatePolicy(
55
+ { kind: 'transfer', coinType: SUI_TYPE, amountMist, protocol: 'stake' },
56
+ ctx.policy,
57
+ )
58
+ if (!verdict.allowed) {
59
+ return { ok: false, error: `policy blocked: ${verdict.violations.join('; ')}` }
60
+ }
61
+ }
62
+
63
+ const tx = new Transaction()
64
+ const [suiCoin] = tx.splitCoins(tx.gas, [amountMist])
65
+ const vsui = await stakeTovSuiPTB(tx as never, suiCoin as never)
66
+ tx.transferObjects([vsui as never], ctx.agentAddress)
67
+
68
+ const sim = await simulate(ctx.client, tx, ctx.agentAddress)
69
+ if (!sim.ok) return { ok: false, error: `pre-flight simulation failed: ${sim.reason}` }
70
+
71
+ const res = await ctx.client.signAndExecuteTransaction({
72
+ signer: ctx.keypair,
73
+ transaction: tx,
74
+ options: { showEffects: true },
75
+ })
76
+ if (res.effects?.status?.status !== 'success') {
77
+ return {
78
+ ok: false,
79
+ error: `execution failed: ${res.effects?.status?.error ?? 'unknown'}`,
80
+ }
81
+ }
82
+ await ctx.client.waitForTransaction({ digest: res.digest })
83
+ return {
84
+ ok: true,
85
+ data: {
86
+ protocol: 'volo',
87
+ action: 'liquid-stake',
88
+ amountSui: args.amount,
89
+ received: 'vSUI',
90
+ digest: res.digest,
91
+ status: 'success',
92
+ },
93
+ }
94
+ } catch (e) {
95
+ return { ok: false, error: (e as Error).message.slice(0, 240) }
96
+ }
97
+ },
98
+ }
99
+ }
100
+
101
+ export function makeVoloUnstake(ctx: OnchainRuntimeContext): ToolDef<UnstakeArgs> {
102
+ return {
103
+ name: 'volo.unstake',
104
+ description:
105
+ 'Unstake vSUI back to SUI via Volo (returns SUI including accrued staking rewards). The amount is denominated in vSUI. Simulated, then executed.',
106
+ searchHint: 'volo unstake vsui redeem convert back sui liquid staking withdraw',
107
+ schema: UnstakeSchema,
108
+ handler: async args => {
109
+ try {
110
+ if (ctx.network !== 'mainnet') return { ok: false, error: 'Volo supports mainnet only' }
111
+ const amountMist = suiToMist(args.amount)
112
+ if (amountMist === undefined || amountMist <= 0n) {
113
+ return { ok: false, error: `invalid amount "${args.amount}"` }
114
+ }
115
+
116
+ const tx = new Transaction()
117
+ // coinWithBalance resolves the agent's vSUI coins into one of the exact size.
118
+ const vsuiCoin = coinWithBalance({ type: VSUI_TYPE, balance: amountMist })
119
+ const sui = await unstakeTovSui(tx as never, vsuiCoin as never)
120
+ tx.transferObjects([sui as never], ctx.agentAddress)
121
+
122
+ const sim = await simulate(ctx.client, tx, ctx.agentAddress)
123
+ if (!sim.ok) return { ok: false, error: `pre-flight simulation failed: ${sim.reason}` }
124
+
125
+ const res = await ctx.client.signAndExecuteTransaction({
126
+ signer: ctx.keypair,
127
+ transaction: tx,
128
+ options: { showEffects: true },
129
+ })
130
+ if (res.effects?.status?.status !== 'success') {
131
+ return {
132
+ ok: false,
133
+ error: `execution failed: ${res.effects?.status?.error ?? 'unknown'}`,
134
+ }
135
+ }
136
+ await ctx.client.waitForTransaction({ digest: res.digest })
137
+ return {
138
+ ok: true,
139
+ data: {
140
+ protocol: 'volo',
141
+ action: 'unstake',
142
+ amountVsui: args.amount,
143
+ digest: res.digest,
144
+ status: 'success',
145
+ },
146
+ }
147
+ } catch (e) {
148
+ return { ok: false, error: (e as Error).message.slice(0, 240) }
149
+ }
150
+ },
151
+ }
152
+ }
package/src/tools/navi.ts CHANGED
@@ -126,7 +126,12 @@ async function runNaviWrite(
126
126
  // repay/supply move SUI out). Withdraw pulls the agent's own funds back.
127
127
  if (ctx.policy && kind !== 'withdraw') {
128
128
  const verdict = evaluatePolicy(
129
- { kind: 'transfer', coinType: SUI_TYPE, amountMist, protocol: kind === 'borrow' ? 'borrow' : 'navi' },
129
+ {
130
+ kind: 'transfer',
131
+ coinType: SUI_TYPE,
132
+ amountMist,
133
+ protocol: kind === 'borrow' ? 'borrow' : 'navi',
134
+ },
130
135
  ctx.policy,
131
136
  )
132
137
  if (!verdict.allowed)
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Integration coverage — LIVE mainnet dry-runs (devInspect, never broadcast).
3
+ *
4
+ * Gated: runs only when `LYRA_RUN_INTEGRATION=1` and a real `LYRA_AGENT_KEY` is
5
+ * present. In CI (no secret) the whole suite is skipped, so it never flakes the
6
+ * default `bun test`. Run locally with:
7
+ *
8
+ * LYRA_RUN_INTEGRATION=1 bun test src/tools/onchain.integration.test.ts
9
+ *
10
+ * Each write case builds the exact PTB its tool builds and simulates it against
11
+ * mainnet, proving the SDK integration + PTB are valid on-chain without moving
12
+ * funds. Read-only tools are invoked directly (safe).
13
+ */
14
+
15
+ import { describe, expect, test } from 'bun:test'
16
+ import { Transaction } from '@mysten/sui/transactions'
17
+ import { LENDING_MARKET_ID, LENDING_MARKET_TYPE, SuilendClient } from '@suilend/sdk'
18
+ import { stakeTovSuiPTB } from 'navi-sdk'
19
+ import { keypairFromSecret, makeSuiClient } from '../client'
20
+ import type { OnchainRuntimeContext } from '../types'
21
+ import { makeScallopMarkets } from './scallop'
22
+ import { makeSuilendPosition } from './suilend'
23
+
24
+ const SUI = '0x2::sui::SUI'
25
+ const RUN = process.env.LYRA_RUN_INTEGRATION === '1' && !!process.env.LYRA_AGENT_KEY
26
+ const ONE_SUI = 1_000_000_000n
27
+
28
+ function realCtx(): OnchainRuntimeContext {
29
+ const client = makeSuiClient('mainnet')
30
+ const keypair = keypairFromSecret(process.env.LYRA_AGENT_KEY as string)
31
+ return {
32
+ client,
33
+ keypair,
34
+ agentAddress: keypair.getPublicKey().toSuiAddress(),
35
+ network: 'mainnet',
36
+ agentDir: '/tmp/lyra-integration',
37
+ }
38
+ }
39
+
40
+ async function simStatus(ctx: OnchainRuntimeContext, tx: Transaction): Promise<string | undefined> {
41
+ const r = await ctx.client.devInspectTransactionBlock({
42
+ sender: ctx.agentAddress,
43
+ transactionBlock: tx as never,
44
+ })
45
+ return r.effects?.status?.status
46
+ }
47
+
48
+ describe.skipIf(!RUN)('mainnet dry-run integration', () => {
49
+ test('native stake (1 SUI → validator) simulates success', async () => {
50
+ const ctx = realCtx()
51
+ const state = await ctx.client.getLatestSuiSystemState()
52
+ const validator = state.activeValidators
53
+ .slice()
54
+ .sort((a, b) => Number(b.votingPower) - Number(a.votingPower))[0]
55
+ if (!validator) throw new Error('no active validators')
56
+ const tx = new Transaction()
57
+ tx.setSender(ctx.agentAddress)
58
+ const [coin] = tx.splitCoins(tx.gas, [ONE_SUI])
59
+ tx.moveCall({
60
+ target: '0x3::sui_system::request_add_stake',
61
+ arguments: [tx.object('0x5'), coin, tx.pure.address(validator.suiAddress)],
62
+ })
63
+ expect(await simStatus(ctx, tx)).toBe('success')
64
+ }, 45_000)
65
+
66
+ test('Volo liquid stake (1 SUI → vSUI) simulates success', async () => {
67
+ const ctx = realCtx()
68
+ const tx = new Transaction()
69
+ tx.setSender(ctx.agentAddress)
70
+ const [coin] = tx.splitCoins(tx.gas, [ONE_SUI])
71
+ const vsui = await stakeTovSuiPTB(tx as never, coin as never)
72
+ tx.transferObjects([vsui as never], ctx.agentAddress)
73
+ expect(await simStatus(ctx, tx)).toBe('success')
74
+ }, 45_000)
75
+
76
+ test('Suilend supply (1 SUI) simulates success', async () => {
77
+ const ctx = realCtx()
78
+ const suilend = await SuilendClient.initialize(
79
+ LENDING_MARKET_ID,
80
+ LENDING_MARKET_TYPE,
81
+ ctx.client as never,
82
+ )
83
+ const caps = await SuilendClient.getObligationOwnerCaps(
84
+ ctx.agentAddress,
85
+ [LENDING_MARKET_TYPE],
86
+ ctx.client as never,
87
+ )
88
+ const tx = new Transaction()
89
+ tx.setSender(ctx.agentAddress)
90
+ const [coin] = tx.splitCoins(tx.gas, [ONE_SUI])
91
+ if (caps.length === 0) {
92
+ const cap = suilend.createObligation(tx as never)
93
+ suilend.deposit(coin as never, SUI, cap, tx as never)
94
+ tx.transferObjects([cap as never], ctx.agentAddress)
95
+ } else {
96
+ const c = caps[0] as { id: string | { id: string } }
97
+ const capId = typeof c.id === 'string' ? c.id : c.id.id
98
+ suilend.deposit(coin as never, SUI, capId, tx as never)
99
+ }
100
+ expect(await simStatus(ctx, tx)).toBe('success')
101
+ }, 45_000)
102
+
103
+ test('read-only tools return live data', async () => {
104
+ const ctx = realCtx()
105
+ const position = await makeSuilendPosition(ctx).handler({})
106
+ expect(position.ok).toBe(true)
107
+
108
+ const markets = await makeScallopMarkets(ctx).handler({ coins: 'sui' })
109
+ expect(markets.ok).toBe(true)
110
+ }, 45_000)
111
+ })
@@ -132,22 +132,29 @@ type AmountArgs = z.infer<typeof AmountSchema>
132
132
  async function runScallopWrite(
133
133
  ctx: OnchainRuntimeContext,
134
134
  amount: string,
135
- kind: 'supply' | 'withdraw',
135
+ kind: 'supply' | 'withdraw' | 'borrow' | 'repay',
136
136
  ): Promise<{ ok: true; data: unknown } | { ok: false; error: string }> {
137
137
  const err = ensureMainnet(ctx)
138
138
  if (err) return { ok: false, error: err }
139
139
  const amountMist = suiToMist(amount)
140
140
  if (amountMist === undefined || amountMist <= 0n)
141
141
  return { ok: false, error: `invalid amount "${amount}"` }
142
- if (kind === 'supply') {
143
- const tooSmall = checkMinimum('supply', amountMist)
142
+ // Minimum guard for value-moving actions (withdraw pulls the agent's own funds).
143
+ const minAction = kind === 'borrow' ? 'borrow' : kind === 'withdraw' ? null : 'supply'
144
+ if (minAction) {
145
+ const tooSmall = checkMinimum(minAction, amountMist)
144
146
  if (tooSmall) return { ok: false, error: tooSmall }
145
147
  }
146
148
 
147
- // Policy gate (deterministic). Supplying moves funds out; withdrawing back in.
148
- if (ctx.policy && kind === 'supply') {
149
+ // Policy gate on value-moving actions (borrow creates debt + hands out funds).
150
+ if (ctx.policy && kind !== 'withdraw') {
149
151
  const verdict = evaluatePolicy(
150
- { kind: 'transfer', coinType: SUI_TYPE, amountMist, protocol: 'scallop' },
152
+ {
153
+ kind: 'transfer',
154
+ coinType: SUI_TYPE,
155
+ amountMist,
156
+ protocol: kind === 'borrow' ? 'borrow' : 'scallop',
157
+ },
151
158
  ctx.policy,
152
159
  )
153
160
  if (!verdict.allowed)
@@ -159,15 +166,16 @@ async function runScallopWrite(
159
166
  const builder = await sdk.createScallopBuilder()
160
167
  const tx = builder.createTxBlock()
161
168
  tx.setSender(ctx.agentAddress)
162
- // deposit/withdraw auto-select the user's coins and return the resulting
163
- // coin to hand back to the owner. depositQuick's 3rd arg returnSCoin=false
164
- // keeps the old market-coin standard, which withdrawQuick can redeem (the
165
- // new sCoin standard is not found by withdrawQuick → "No valid coins").
166
- const out =
167
- kind === 'supply'
168
- ? await tx.depositQuick(Number(amountMist), 'sui', false)
169
- : await tx.withdrawQuick(Number(amountMist), 'sui')
170
- if (out) tx.transferObjects([out], ctx.agentAddress)
169
+ // *Quick helpers auto-select the user's coins/obligation. supply/withdraw and
170
+ // borrow return a coin to hand back; repay consumes coins. depositQuick's 3rd
171
+ // arg returnSCoin=false keeps the old market-coin standard (withdrawQuick
172
+ // redeems it; the new sCoin standard → "No valid coins").
173
+ let out: unknown
174
+ if (kind === 'supply') out = await tx.depositQuick(Number(amountMist), 'sui', false)
175
+ else if (kind === 'withdraw') out = await tx.withdrawQuick(Number(amountMist), 'sui')
176
+ else if (kind === 'borrow') out = await tx.borrowQuick(Number(amountMist), 'sui')
177
+ else await tx.repayQuick(Number(amountMist), 'sui')
178
+ if (out) tx.transferObjects([out as never], ctx.agentAddress)
171
179
  const transaction = tx.txBlock
172
180
 
173
181
  const sim = await simulate(ctx.client, transaction, ctx.agentAddress)
@@ -220,3 +228,24 @@ export function makeScallopWithdraw(ctx: OnchainRuntimeContext): ToolDef<AmountA
220
228
  handler: async args => runScallopWrite(ctx, args.amount, 'withdraw'),
221
229
  }
222
230
  }
231
+
232
+ export function makeScallopBorrow(ctx: OnchainRuntimeContext): ToolDef<AmountArgs> {
233
+ return {
234
+ name: 'scallop.borrow',
235
+ description:
236
+ 'Borrow SUI from Scallop against supplied collateral. Requires an existing supply position with enough health; the pre-flight simulation fails cleanly if under-collateralized. Policy-checked, simulated, then executed.',
237
+ searchHint: 'scallop borrow loan leverage debt against collateral sui',
238
+ schema: AmountSchema,
239
+ handler: async args => runScallopWrite(ctx, args.amount, 'borrow'),
240
+ }
241
+ }
242
+
243
+ export function makeScallopRepay(ctx: OnchainRuntimeContext): ToolDef<AmountArgs> {
244
+ return {
245
+ name: 'scallop.repay',
246
+ description: 'Repay borrowed SUI debt on Scallop. Simulated, then executed.',
247
+ searchHint: 'scallop repay pay back debt loan close sui',
248
+ schema: AmountSchema,
249
+ handler: async args => runScallopWrite(ctx, args.amount, 'repay'),
250
+ }
251
+ }
@@ -31,7 +31,7 @@ async function resolveValidator(
31
31
  // biome-ignore lint/suspicious/noExplicitAny: SuiSystemState validator fields
32
32
  const vals = (state.activeValidators ?? []) as any[]
33
33
  if (vals.length === 0) return null
34
- if (want && want.trim()) {
34
+ if (want?.trim()) {
35
35
  const w = want.trim().toLowerCase()
36
36
  const m = vals.find(
37
37
  v => String(v.suiAddress).toLowerCase() === w || String(v.name ?? '').toLowerCase() === w,
@@ -100,7 +100,10 @@ export function makeStake(ctx: OnchainRuntimeContext): ToolDef<StakeArgs> {
100
100
  options: { showEffects: true, showObjectChanges: true },
101
101
  })
102
102
  if (res.effects?.status?.status !== 'success') {
103
- return { ok: false, error: `execution failed: ${res.effects?.status?.error ?? 'unknown'}` }
103
+ return {
104
+ ok: false,
105
+ error: `execution failed: ${res.effects?.status?.error ?? 'unknown'}`,
106
+ }
104
107
  }
105
108
  await ctx.client.waitForTransaction({ digest: res.digest })
106
109
  const staked = res.objectChanges?.find(
@@ -181,7 +184,10 @@ export function makeUnstake(ctx: OnchainRuntimeContext): ToolDef<UnstakeArgs> {
181
184
  options: { showEffects: true },
182
185
  })
183
186
  if (res.effects?.status?.status !== 'success') {
184
- return { ok: false, error: `execution failed: ${res.effects?.status?.error ?? 'unknown'}` }
187
+ return {
188
+ ok: false,
189
+ error: `execution failed: ${res.effects?.status?.error ?? 'unknown'}`,
190
+ }
185
191
  }
186
192
  await ctx.client.waitForTransaction({ digest: res.digest })
187
193
 
@@ -0,0 +1,419 @@
1
+ /**
2
+ * Suilend lending tools (supporting integration): SUI supply / withdraw /
3
+ * borrow / repay + a read-only position, on Suilend's MAIN_POOL lending market.
4
+ *
5
+ * Suilend is one of the three largest money markets on Sui. Its SDK's 3.x line
6
+ * pins @mysten/sui v2 (a Transaction-class ABI break vs. our v1 stack), so we
7
+ * use @suilend/sdk@1.1.x, whose @mysten/sui is a *peerDependency* — it binds to
8
+ * our hosted v1 copy, so the v1 Transaction we build is accepted directly by the
9
+ * SDK (verified end-to-end with a live mainnet dry-run of a deposit).
10
+ *
11
+ * Value semantics (checked against the SDK source):
12
+ * deposit / borrow / repay → underlying MIST (clean).
13
+ * withdraw → cTokens; we convert the requested underlying via
14
+ * the reserve's cToken exchange rate.
15
+ *
16
+ * Every write runs the same guarded pipeline as sui.send: minimum guard →
17
+ * policy gate → dry-run simulate → execute → on-chain effects check. The
18
+ * simulate is the safety net — an under-collateralized borrow or an over-sized
19
+ * withdraw fails before broadcast, never a false success.
20
+ */
21
+
22
+ import { Transaction } from '@mysten/sui/transactions'
23
+ import {
24
+ LENDING_MARKET_ID,
25
+ LENDING_MARKET_TYPE,
26
+ SuilendClient,
27
+ initializeSuilend,
28
+ } from '@suilend/sdk'
29
+ import type { ToolDef } from 'lyra-core'
30
+ import { z } from 'zod'
31
+ import { checkMinimum } from '../minimums'
32
+ import { evaluatePolicy, suiToMist } from '../policy'
33
+ import { simulate } from '../simulate'
34
+ import type { OnchainRuntimeContext } from '../types'
35
+
36
+ const SUI_TYPE = '0x2::sui::SUI'
37
+ // Canonical + long-form SUI coin types (reserve maps may use either).
38
+ const SUI_LONG = `0x${'0'.repeat(63)}2::sui::SUI`
39
+
40
+ function ensureMainnet(ctx: OnchainRuntimeContext): string | null {
41
+ return ctx.network === 'mainnet' ? null : 'Suilend SDK supports mainnet only'
42
+ }
43
+
44
+ async function newSuilend(ctx: OnchainRuntimeContext): Promise<SuilendClient> {
45
+ // ctx.client is @mysten/sui v1.4x; @suilend/sdk@1.1.x binds @mysten/sui as a
46
+ // peer, so the client interops directly across the copy boundary.
47
+ return SuilendClient.initialize(LENDING_MARKET_ID, LENDING_MARKET_TYPE, ctx.client as never)
48
+ }
49
+
50
+ /** Extract the object id from a parsed ObligationOwnerCap (`id` is a UID). */
51
+ function capObjectId(cap: { id: unknown }): string {
52
+ const id = cap.id as string | { id: string }
53
+ return typeof id === 'string' ? id : id.id
54
+ }
55
+
56
+ function isSuiType(t: string): boolean {
57
+ return t === SUI_TYPE || t === SUI_LONG
58
+ }
59
+
60
+ /** The agent's obligation cap + id, or null if it has no Suilend position yet. */
61
+ async function findObligation(
62
+ ctx: OnchainRuntimeContext,
63
+ ): Promise<{ capId: string; obligationId: string } | null> {
64
+ const caps = await SuilendClient.getObligationOwnerCaps(
65
+ ctx.agentAddress,
66
+ [LENDING_MARKET_TYPE],
67
+ ctx.client as never,
68
+ )
69
+ if (!caps.length) return null
70
+ const c = caps[0] as { id: unknown; obligationId: string | { id: string } }
71
+ const obligationId = typeof c.obligationId === 'string' ? c.obligationId : c.obligationId.id
72
+ return { capId: capObjectId(c), obligationId }
73
+ }
74
+
75
+ // --- suilend.supply --------------------------------------------------------
76
+
77
+ const AmountSchema = z.object({
78
+ amount: z.string().min(1).describe('Amount of SUI, e.g. "1.5".'),
79
+ })
80
+ type AmountArgs = z.infer<typeof AmountSchema>
81
+
82
+ export function makeSuilendSupply(ctx: OnchainRuntimeContext): ToolDef<AmountArgs> {
83
+ return {
84
+ name: 'suilend.supply',
85
+ description:
86
+ 'Supply (deposit) idle SUI into Suilend to earn lending yield. Creates a Suilend obligation on first use, then deposits into it. Policy-checked, simulated, then executed.',
87
+ searchHint: 'suilend supply deposit lend sui earn yield idle money market',
88
+ schema: AmountSchema,
89
+ handler: async args => {
90
+ const err = ensureMainnet(ctx)
91
+ if (err) return { ok: false, error: err }
92
+ const amountMist = suiToMist(args.amount)
93
+ if (amountMist === undefined || amountMist <= 0n)
94
+ return { ok: false, error: `invalid amount "${args.amount}"` }
95
+ const tooSmall = checkMinimum('supply', amountMist)
96
+ if (tooSmall) return { ok: false, error: tooSmall }
97
+ if (ctx.policy) {
98
+ const verdict = evaluatePolicy(
99
+ { kind: 'transfer', coinType: SUI_TYPE, amountMist, protocol: 'suilend' },
100
+ ctx.policy,
101
+ )
102
+ if (!verdict.allowed)
103
+ return { ok: false, error: `policy blocked: ${verdict.violations.join('; ')}` }
104
+ }
105
+ try {
106
+ const suilend = await newSuilend(ctx)
107
+ const existing = await findObligation(ctx)
108
+ const tx = new Transaction()
109
+ tx.setSender(ctx.agentAddress)
110
+ const [coin] = tx.splitCoins(tx.gas, [amountMist])
111
+ // The @suilend/sdk@1.1.x SDK carries its own nested @mysten/sui copy, so
112
+ // TS sees a distinct Transaction class — cast at the boundary. The two
113
+ // copies interop at runtime (verified with a live mainnet dry-run).
114
+ if (existing) {
115
+ suilend.deposit(coin as never, SUI_TYPE, existing.capId, tx as never)
116
+ } else {
117
+ const cap = suilend.createObligation(tx as never)
118
+ suilend.deposit(coin as never, SUI_TYPE, cap, tx as never)
119
+ tx.transferObjects([cap as never], ctx.agentAddress)
120
+ }
121
+ const sim = await simulate(ctx.client, tx, ctx.agentAddress)
122
+ if (!sim.ok) return { ok: false, error: `pre-flight simulation failed: ${sim.reason}` }
123
+ const res = await ctx.client.signAndExecuteTransaction({
124
+ signer: ctx.keypair,
125
+ transaction: tx,
126
+ options: { showEffects: true },
127
+ })
128
+ if (res.effects?.status?.status !== 'success')
129
+ return {
130
+ ok: false,
131
+ error: `execution failed: ${res.effects?.status?.error ?? 'unknown'}`,
132
+ }
133
+ await ctx.client.waitForTransaction({ digest: res.digest })
134
+ return {
135
+ ok: true,
136
+ data: {
137
+ protocol: 'suilend',
138
+ action: 'supply',
139
+ amountSui: args.amount,
140
+ newObligation: !existing,
141
+ digest: res.digest,
142
+ policyEnforced: ctx.policy != null,
143
+ },
144
+ }
145
+ } catch (e) {
146
+ return { ok: false, error: (e as Error).message.slice(0, 240) }
147
+ }
148
+ },
149
+ }
150
+ }
151
+
152
+ // --- suilend.withdraw ------------------------------------------------------
153
+
154
+ export function makeSuilendWithdraw(ctx: OnchainRuntimeContext): ToolDef<AmountArgs> {
155
+ return {
156
+ name: 'suilend.withdraw',
157
+ description:
158
+ 'Withdraw supplied SUI from Suilend back to the agent (amount in underlying SUI). Refreshes prices, converts to cTokens at the current exchange rate, simulated, then executed.',
159
+ searchHint: 'suilend withdraw redeem unlend remove supplied sui money market',
160
+ schema: AmountSchema,
161
+ handler: async args => {
162
+ const err = ensureMainnet(ctx)
163
+ if (err) return { ok: false, error: err }
164
+ const amountMist = suiToMist(args.amount)
165
+ if (amountMist === undefined || amountMist <= 0n)
166
+ return { ok: false, error: `invalid amount "${args.amount}"` }
167
+ try {
168
+ const suilend = await newSuilend(ctx)
169
+ const obligation = await findObligation(ctx)
170
+ if (!obligation)
171
+ return { ok: false, error: 'no Suilend position — supply SUI before withdrawing' }
172
+ // Convert underlying → cTokens using the SUI reserve exchange rate.
173
+ const data = await initializeSuilend(ctx.client as never, suilend)
174
+ const rate = suiReserveExchangeRate(data)
175
+ if (rate === null) return { ok: false, error: 'could not read SUI reserve exchange rate' }
176
+ // cTokens = floor(underlying / rate); floor keeps us at/under the request.
177
+ const ctokens = BigInt(Math.floor(Number(amountMist) / rate))
178
+ if (ctokens <= 0n) return { ok: false, error: 'amount too small to withdraw' }
179
+ const tx = new Transaction()
180
+ tx.setSender(ctx.agentAddress)
181
+ await suilend.withdrawAndSendToUser(
182
+ ctx.agentAddress,
183
+ obligation.capId,
184
+ obligation.obligationId,
185
+ SUI_TYPE,
186
+ ctokens.toString(),
187
+ tx as never,
188
+ )
189
+ const sim = await simulate(ctx.client, tx, ctx.agentAddress)
190
+ if (!sim.ok) return { ok: false, error: `pre-flight simulation failed: ${sim.reason}` }
191
+ const res = await ctx.client.signAndExecuteTransaction({
192
+ signer: ctx.keypair,
193
+ transaction: tx,
194
+ options: { showEffects: true },
195
+ })
196
+ if (res.effects?.status?.status !== 'success')
197
+ return {
198
+ ok: false,
199
+ error: `execution failed: ${res.effects?.status?.error ?? 'unknown'}`,
200
+ }
201
+ await ctx.client.waitForTransaction({ digest: res.digest })
202
+ return {
203
+ ok: true,
204
+ data: {
205
+ protocol: 'suilend',
206
+ action: 'withdraw',
207
+ amountSui: args.amount,
208
+ digest: res.digest,
209
+ },
210
+ }
211
+ } catch (e) {
212
+ return { ok: false, error: (e as Error).message.slice(0, 240) }
213
+ }
214
+ },
215
+ }
216
+ }
217
+
218
+ // --- suilend.borrow --------------------------------------------------------
219
+
220
+ export function makeSuilendBorrow(ctx: OnchainRuntimeContext): ToolDef<AmountArgs> {
221
+ return {
222
+ name: 'suilend.borrow',
223
+ description:
224
+ 'Borrow SUI from Suilend against supplied collateral (amount in underlying SUI). Requires an existing obligation with enough health; the pre-flight simulation fails cleanly if under-collateralized. Policy-checked, simulated, then executed.',
225
+ searchHint: 'suilend borrow loan leverage debt against collateral sui money market',
226
+ schema: AmountSchema,
227
+ handler: async args => {
228
+ const err = ensureMainnet(ctx)
229
+ if (err) return { ok: false, error: err }
230
+ const amountMist = suiToMist(args.amount)
231
+ if (amountMist === undefined || amountMist <= 0n)
232
+ return { ok: false, error: `invalid amount "${args.amount}"` }
233
+ const tooSmall = checkMinimum('borrow', amountMist)
234
+ if (tooSmall) return { ok: false, error: tooSmall }
235
+ if (ctx.policy) {
236
+ const verdict = evaluatePolicy(
237
+ { kind: 'transfer', coinType: SUI_TYPE, amountMist, protocol: 'borrow' },
238
+ ctx.policy,
239
+ )
240
+ if (!verdict.allowed)
241
+ return { ok: false, error: `policy blocked: ${verdict.violations.join('; ')}` }
242
+ }
243
+ try {
244
+ const suilend = await newSuilend(ctx)
245
+ const obligation = await findObligation(ctx)
246
+ if (!obligation)
247
+ return { ok: false, error: 'no Suilend position — supply collateral before borrowing' }
248
+ const tx = new Transaction()
249
+ tx.setSender(ctx.agentAddress)
250
+ // borrow() self-refreshes prices (addRefreshCalls default true).
251
+ await suilend.borrowAndSendToUser(
252
+ ctx.agentAddress,
253
+ obligation.capId,
254
+ obligation.obligationId,
255
+ SUI_TYPE,
256
+ amountMist.toString(),
257
+ tx as never,
258
+ )
259
+ const sim = await simulate(ctx.client, tx, ctx.agentAddress)
260
+ if (!sim.ok) return { ok: false, error: `pre-flight simulation failed: ${sim.reason}` }
261
+ const res = await ctx.client.signAndExecuteTransaction({
262
+ signer: ctx.keypair,
263
+ transaction: tx,
264
+ options: { showEffects: true },
265
+ })
266
+ if (res.effects?.status?.status !== 'success')
267
+ return {
268
+ ok: false,
269
+ error: `execution failed: ${res.effects?.status?.error ?? 'unknown'}`,
270
+ }
271
+ await ctx.client.waitForTransaction({ digest: res.digest })
272
+ return {
273
+ ok: true,
274
+ data: {
275
+ protocol: 'suilend',
276
+ action: 'borrow',
277
+ amountSui: args.amount,
278
+ digest: res.digest,
279
+ policyEnforced: ctx.policy != null,
280
+ },
281
+ }
282
+ } catch (e) {
283
+ return { ok: false, error: (e as Error).message.slice(0, 240) }
284
+ }
285
+ },
286
+ }
287
+ }
288
+
289
+ // --- suilend.repay ---------------------------------------------------------
290
+
291
+ export function makeSuilendRepay(ctx: OnchainRuntimeContext): ToolDef<AmountArgs> {
292
+ return {
293
+ name: 'suilend.repay',
294
+ description:
295
+ 'Repay borrowed SUI debt on Suilend (amount in underlying SUI). Simulated, then executed.',
296
+ searchHint: 'suilend repay pay back debt loan close sui money market',
297
+ schema: AmountSchema,
298
+ handler: async args => {
299
+ const err = ensureMainnet(ctx)
300
+ if (err) return { ok: false, error: err }
301
+ const amountMist = suiToMist(args.amount)
302
+ if (amountMist === undefined || amountMist <= 0n)
303
+ return { ok: false, error: `invalid amount "${args.amount}"` }
304
+ if (ctx.policy) {
305
+ const verdict = evaluatePolicy(
306
+ { kind: 'transfer', coinType: SUI_TYPE, amountMist, protocol: 'suilend' },
307
+ ctx.policy,
308
+ )
309
+ if (!verdict.allowed)
310
+ return { ok: false, error: `policy blocked: ${verdict.violations.join('; ')}` }
311
+ }
312
+ try {
313
+ const suilend = await newSuilend(ctx)
314
+ const obligation = await findObligation(ctx)
315
+ if (!obligation) return { ok: false, error: 'no Suilend position — nothing to repay' }
316
+ const tx = new Transaction()
317
+ tx.setSender(ctx.agentAddress)
318
+ await suilend.repayIntoObligation(
319
+ ctx.agentAddress,
320
+ obligation.obligationId,
321
+ SUI_TYPE,
322
+ amountMist.toString(),
323
+ tx as never,
324
+ )
325
+ const sim = await simulate(ctx.client, tx, ctx.agentAddress)
326
+ if (!sim.ok) return { ok: false, error: `pre-flight simulation failed: ${sim.reason}` }
327
+ const res = await ctx.client.signAndExecuteTransaction({
328
+ signer: ctx.keypair,
329
+ transaction: tx,
330
+ options: { showEffects: true },
331
+ })
332
+ if (res.effects?.status?.status !== 'success')
333
+ return {
334
+ ok: false,
335
+ error: `execution failed: ${res.effects?.status?.error ?? 'unknown'}`,
336
+ }
337
+ await ctx.client.waitForTransaction({ digest: res.digest })
338
+ return {
339
+ ok: true,
340
+ data: {
341
+ protocol: 'suilend',
342
+ action: 'repay',
343
+ amountSui: args.amount,
344
+ digest: res.digest,
345
+ },
346
+ }
347
+ } catch (e) {
348
+ return { ok: false, error: (e as Error).message.slice(0, 240) }
349
+ }
350
+ },
351
+ }
352
+ }
353
+
354
+ // --- suilend.position (read) -----------------------------------------------
355
+
356
+ const PositionSchema = z.object({})
357
+ type PositionArgs = z.infer<typeof PositionSchema>
358
+
359
+ export function makeSuilendPosition(ctx: OnchainRuntimeContext): ToolDef<PositionArgs> {
360
+ return {
361
+ name: 'suilend.position',
362
+ description:
363
+ "The agent's Suilend position: deposits, borrows, and per-asset balances. Read-only.",
364
+ searchHint: 'suilend position portfolio deposits borrows collateral debt health',
365
+ schema: PositionSchema,
366
+ handler: async () => {
367
+ const err = ensureMainnet(ctx)
368
+ if (err) return { ok: false, error: err }
369
+ try {
370
+ const suilend = await newSuilend(ctx)
371
+ const obligation = await findObligation(ctx)
372
+ if (!obligation)
373
+ return {
374
+ ok: true,
375
+ data: { protocol: 'suilend', hasPosition: false, deposits: [], borrows: [] },
376
+ }
377
+ const parsed = (await suilend.getObligation(obligation.obligationId)) as {
378
+ deposits?: Array<{ coinType?: { name?: string }; depositedCtokenAmount?: bigint }>
379
+ borrows?: Array<{ coinType?: { name?: string }; borrowedAmount?: { value?: bigint } }>
380
+ }
381
+ return {
382
+ ok: true,
383
+ data: {
384
+ protocol: 'suilend',
385
+ hasPosition: true,
386
+ obligationId: obligation.obligationId,
387
+ deposits: (parsed.deposits ?? []).map(d => ({
388
+ coin: d.coinType?.name,
389
+ ctokens: String(d.depositedCtokenAmount ?? 0n),
390
+ })),
391
+ borrows: (parsed.borrows ?? []).map(b => ({
392
+ coin: b.coinType?.name,
393
+ borrowed: String(b.borrowedAmount?.value ?? 0n),
394
+ })),
395
+ },
396
+ }
397
+ } catch (e) {
398
+ return { ok: false, error: (e as Error).message.slice(0, 240) }
399
+ }
400
+ },
401
+ }
402
+ }
403
+
404
+ /** Find the SUI reserve's cToken exchange rate (underlying per cToken) from an
405
+ * initializeSuilend() result, or null if not present. */
406
+ function suiReserveExchangeRate(data: unknown): number | null {
407
+ const d = data as {
408
+ reserveMap?: Record<string, { coinType?: string; cTokenExchangeRate?: unknown }>
409
+ }
410
+ const map = d.reserveMap
411
+ if (!map) return null
412
+ const reserve =
413
+ map[SUI_TYPE] ??
414
+ map[SUI_LONG] ??
415
+ Object.values(map).find(r => typeof r.coinType === 'string' && isSuiType(r.coinType))
416
+ if (!reserve) return null
417
+ const rate = Number(String(reserve.cTokenExchangeRate))
418
+ return Number.isFinite(rate) && rate > 0 ? rate : null
419
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Unit coverage for the DeFi tool surface: (1) the plugin registers every
3
+ * value-moving adapter, and (2) each new write tool runs its guard checks
4
+ * (mainnet-only, valid amount, minimum size) BEFORE it ever touches the
5
+ * network — so a dust/invalid/testnet request fails fast and deterministically,
6
+ * never a false success.
7
+ *
8
+ * These tests deliberately use a bare stub context: the guard branches return
9
+ * before any `client`/`keypair` access, so no RPC is needed. Live end-to-end
10
+ * PTB simulation lives in `onchain.integration.test.ts` (gated on a real key).
11
+ */
12
+
13
+ import { describe, expect, test } from 'bun:test'
14
+ import type { PluginContext, ToolDef } from 'lyra-core'
15
+ import plugin from '../index'
16
+ import type { OnchainRuntimeContext } from '../types'
17
+ import { makeVoloStake } from './liquid-stake'
18
+ import { makeScallopBorrow, makeScallopRepay } from './scallop'
19
+ import { makeSuilendBorrow, makeSuilendSupply } from './suilend'
20
+
21
+ // A context whose network/amount guards resolve before any client access.
22
+ function stubCtx(network: 'mainnet' | 'testnet' = 'mainnet'): OnchainRuntimeContext {
23
+ return {
24
+ network,
25
+ agentAddress: '0x0000000000000000000000000000000000000000000000000000000000000abc',
26
+ agentDir: '/tmp/lyra-test',
27
+ // Accessing either of these would throw — guards must return first.
28
+ client: new Proxy(
29
+ {},
30
+ {
31
+ get() {
32
+ throw new Error('network access before guard')
33
+ },
34
+ },
35
+ ) as never,
36
+ keypair: {} as never,
37
+ }
38
+ }
39
+
40
+ describe('onchain plugin registration', () => {
41
+ test('registers the full DeFi write surface (lending + staking + swap)', () => {
42
+ const names: string[] = []
43
+ const ctx = {
44
+ registerTool: (def: ToolDef) => names.push(def.name),
45
+ registerListener: () => {},
46
+ addHook: () => {},
47
+ network: 'mainnet',
48
+ agentDir: '/tmp',
49
+ agentId: 'test',
50
+ // side-banded onchain runtime the plugin reads off PluginContext
51
+ onchain: stubCtx(),
52
+ } as unknown as PluginContext
53
+ plugin.register(ctx)
54
+
55
+ for (const expected of [
56
+ // lending: the three biggest Sui money markets, full CRUD
57
+ 'scallop.supply',
58
+ 'scallop.withdraw',
59
+ 'scallop.borrow',
60
+ 'scallop.repay',
61
+ 'navi.supply',
62
+ 'navi.borrow',
63
+ 'navi.repay',
64
+ 'suilend.supply',
65
+ 'suilend.withdraw',
66
+ 'suilend.borrow',
67
+ 'suilend.repay',
68
+ 'suilend.position',
69
+ // staking: native + Volo liquid staking
70
+ 'sui.stake',
71
+ 'sui.unstake',
72
+ 'volo.stake',
73
+ 'volo.unstake',
74
+ // swap aggregator
75
+ 'swap',
76
+ ]) {
77
+ expect(names).toContain(expected)
78
+ }
79
+ })
80
+
81
+ test('registers nothing without an onchain runtime (safe no-op for loaders)', () => {
82
+ const names: string[] = []
83
+ const ctx = {
84
+ registerTool: (def: ToolDef) => names.push(def.name),
85
+ registerListener: () => {},
86
+ addHook: () => {},
87
+ network: 'mainnet',
88
+ agentDir: '/tmp',
89
+ agentId: 'test',
90
+ } as unknown as PluginContext
91
+ plugin.register(ctx)
92
+ expect(names).toHaveLength(0)
93
+ })
94
+ })
95
+
96
+ describe('write-tool guards (fail before network)', () => {
97
+ test('suilend.supply rejects a dust amount below the supply minimum', async () => {
98
+ const res = await makeSuilendSupply(stubCtx()).handler({ amount: '0.001' })
99
+ expect(res.ok).toBe(false)
100
+ if (!res.ok) expect(res.error).toContain('amount too small')
101
+ })
102
+
103
+ test('suilend.borrow rejects a dust amount below the borrow minimum', async () => {
104
+ const res = await makeSuilendBorrow(stubCtx()).handler({ amount: '0.0001' })
105
+ expect(res.ok).toBe(false)
106
+ if (!res.ok) expect(res.error).toContain('amount too small')
107
+ })
108
+
109
+ test('volo.stake rejects below the 1 SUI staking minimum', async () => {
110
+ const res = await makeVoloStake(stubCtx()).handler({ amount: '0.1' })
111
+ expect(res.ok).toBe(false)
112
+ if (!res.ok) expect(res.error).toContain('amount too small')
113
+ })
114
+
115
+ test('scallop.borrow rejects a dust amount', async () => {
116
+ const res = await makeScallopBorrow(stubCtx()).handler({ amount: '0.001' })
117
+ expect(res.ok).toBe(false)
118
+ if (!res.ok) expect(res.error).toContain('amount too small')
119
+ })
120
+
121
+ test('invalid amount strings are rejected before any network call', async () => {
122
+ const res = await makeVoloStake(stubCtx()).handler({ amount: 'not-a-number' })
123
+ expect(res.ok).toBe(false)
124
+ if (!res.ok) expect(res.error).toContain('invalid amount')
125
+ })
126
+
127
+ test('mainnet-only tools refuse to run on testnet', async () => {
128
+ const supply = await makeSuilendSupply(stubCtx('testnet')).handler({ amount: '5' })
129
+ expect(supply.ok).toBe(false)
130
+ if (!supply.ok) expect(supply.error).toContain('mainnet only')
131
+
132
+ const stake = await makeVoloStake(stubCtx('testnet')).handler({ amount: '5' })
133
+ expect(stake.ok).toBe(false)
134
+ if (!stake.ok) expect(stake.error).toContain('mainnet only')
135
+ })
136
+
137
+ test('scallop.repay is a registered, well-formed tool', () => {
138
+ const tool = makeScallopRepay(stubCtx())
139
+ expect(tool.name).toBe('scallop.repay')
140
+ expect(typeof tool.handler).toBe('function')
141
+ })
142
+ })