lyra-plugin-onchain 0.1.10 → 0.2.0

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/README.md CHANGED
@@ -1,26 +1,30 @@
1
1
  # lyra-plugin-onchain
2
2
 
3
- The **Sui limbs** for **lyra** — the brain tools that do real on-chain work,
4
- every value-moving call routed through the deterministic policy → simulation
5
- approval pipeline:
3
+ The **Sui limbs** for **lyra** — the tools that do real on-chain work. Every
4
+ value-moving call is routed through the deterministic **policy → simulate
5
+ approve → execute** pipeline, and (when a vault is provisioned) sources funds from
6
+ the on-chain `Vault` via `vault_spend`, so nothing moves outside the on-chain
7
+ `lyra::policy` limits.
6
8
 
7
- - **Wallet / account** — `account.info`, `chain.balance`, `tokens.info`
8
- - **Transfers** — `chain.send`, `chain.wrap`, `chain.unwrap`
9
- - **Trading** — `swap.best` / `swap.compare` (**Cetus Finance** + **DeepBook**
10
- best-execution), `swap.quote` / `swap.execute`, `moe.quote` / `moe.swap`
11
- - **Lending** — full **Scallop V3** suite: `scallop.markets` / `position` / `supply` /
12
- `withdraw` / `borrow` / `repay`
13
- - **Discovery + risk** `defi.yields` (DeFiLlama), `risk.token`, `nansen.labels`,
14
- `cex.balance` (Bybit, read-only)
15
- - **Identity** — `identity.resolve` / `identity.register` (**lyra::policy** Trustless
16
- Agents)
17
- - **Controls + analysis** — `policy.show`, `tx.simulate`, `chain.read` /
18
- `chain.write`, `chain.tx` / `chain.contract` / `chain.activity`, `chain.block` /
19
- `chain.gas`
9
+ - **Wallet / reads** — `account.info`, `sui.balance`
10
+ - **Transfers** — `sui.send` (recipient-allowlist aware)
11
+ - **Swaps** — `swap` (7k aggregator best-route across Cetus / Turbos / FlowX /
12
+ Bluefin / Aftermath / Momentum / Kriya / DeepBook), `cetus.quote`
13
+ - **Lending** — `scallop.*` (markets / position / supply / withdraw),
14
+ `navi.*` (markets / position / supply / withdraw / borrow / repay),
15
+ `suilend.*` (position / supply / withdraw / borrow / repay)
16
+ - **Staking** — `sui.stake` / `sui.unstake` (native delegation), `volo.stake` /
17
+ `volo.unstake` (liquid staking vSUI)
18
+ - **Discovery** — `defi.yields` (DeFiLlama), `deepbook.markets`, `protocols.list`
19
+ (the honest read-vs-execute capability map)
20
+ - **Storage** `walrus.store` (durable, verifiable receipts/memory on Walrus)
21
+ - **Policy** — `policy.create` (provision an `AgentPolicy` + `Vault`), `policy.show`
20
22
 
21
23
  ## Install
22
24
 
23
25
  Auto-installed with [`lyra-ai-agent`](https://www.npmjs.com/package/lyra-ai-agent).
24
26
  Or directly: `bun add lyra-plugin-onchain`.
25
27
 
26
- See the [root README](https://github.com/rifkyeasy/lyra#readme) for the full tool reference.
28
+ The on-chain package it targets lives in
29
+ [`lyraai-protocol/contracts`](https://github.com/lyraai-protocol/contracts). See the
30
+ [root README](https://github.com/lyraai-protocol/lyra#readme) for the full architecture.
package/package.json CHANGED
@@ -1,28 +1,46 @@
1
1
  {
2
2
  "name": "lyra-plugin-onchain",
3
- "version": "0.1.10",
3
+ "version": "0.2.0",
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",
7
- "homepage": "https://github.com/rifkyeasy/lyra",
7
+ "homepage": "https://github.com/lyraai-protocol/lyra",
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "git+https://github.com/rifkyeasy/lyra.git",
10
+ "url": "git+https://github.com/lyraai-protocol/lyra.git",
11
11
  "directory": "packages/plugin-onchain"
12
12
  },
13
13
  "bugs": {
14
- "url": "https://github.com/rifkyeasy/lyra/issues"
14
+ "url": "https://github.com/lyraai-protocol/lyra/issues"
15
15
  },
16
- "keywords": ["lyra", "ai", "agent", "sui", "defi", "deepbook", "walrus", "policy", "plugin"],
16
+ "keywords": [
17
+ "lyra",
18
+ "ai",
19
+ "agent",
20
+ "sui",
21
+ "defi",
22
+ "deepbook",
23
+ "walrus",
24
+ "policy",
25
+ "plugin"
26
+ ],
17
27
  "publishConfig": {
18
28
  "access": "public"
19
29
  },
20
30
  "engines": {
21
31
  "bun": ">=1.1"
22
32
  },
23
- "files": ["src", "!src/**/*.test.ts", "README.md"],
33
+ "files": [
34
+ "src",
35
+ "!src/**/*.test.ts",
36
+ "README.md"
37
+ ],
24
38
  "main": "./src/index.ts",
25
39
  "types": "./src/index.ts",
40
+ "exports": {
41
+ ".": "./src/index.ts",
42
+ "./protocol-ids": "./src/protocol-ids.ts"
43
+ },
26
44
  "scripts": {
27
45
  "build": "tsc -b",
28
46
  "test": "bun test"
@@ -37,7 +55,7 @@
37
55
  "@scallop-io/sui-scallop-sdk": "^2.4.5",
38
56
  "@suilend/sdk": "1.1.99",
39
57
  "@suilend/sui-fe": "0.3.49",
40
- "lyra-core": "^0.1.10",
58
+ "lyra-core": "^0.2.0",
41
59
  "navi-sdk": "^1.7.3",
42
60
  "zod": "^3.23.8"
43
61
  }
package/src/guidance.ts CHANGED
@@ -21,20 +21,31 @@ Read-only / discovery:
21
21
  tagged executable / executeWith.
22
22
  - deepbook.markets — DeepBook spot mid prices.
23
23
  - cetus.quote — best swap route/price across many DEXes (aggregator, read-only).
24
- - scallop.markets / scallop.position, navi.markets / navi.position — lending
25
- rates + the agent's positions.
24
+ - scallop.markets / scallop.position, navi.markets / navi.position,
25
+ suilend.position — lending rates + the agent's positions.
26
+ - walrus.staking — the agent's WAL balance, current WAL staking positions
27
+ (StakedWal), and large Walrus storage nodes to stake with.
26
28
 
27
29
  Writes (policy-checked → simulated → executed):
28
30
  - policy.create — publish a shared on-chain AgentPolicy (budget, per-tx cap,
29
31
  expiry). Do this first to arm on-chain enforcement + receipts.
30
32
  - sui.send — transfer SUI. Blocked if out of policy; mints an on-chain receipt.
31
- - scallop.supply / scallop.withdraw, navi.supply / navi.withdraw lend or
32
- redeem idle SUI on Scallop / NAVI (the two largest Sui money markets).
33
+ - swap best-route swap across the major Sui DEXes (7k aggregator).
34
+ - Lending: scallop.supply / scallop.withdraw, navi.supply / navi.withdraw /
35
+ navi.borrow / navi.repay, suilend.supply / suilend.withdraw / suilend.borrow /
36
+ suilend.repay — lend, redeem, borrow, and repay across the largest Sui markets.
37
+ - Staking:
38
+ - sui.stake / sui.unstake — native SUI staking to a validator (min 1 SUI).
39
+ - volo.stake / volo.unstake — liquid staking, SUI ↔ vSUI.
40
+ - walrus.stake / walrus.unstake — stake WAL to a Walrus storage node to earn
41
+ rewards + secure decentralized storage (min 1 WAL; unstake returns WAL next
42
+ epoch). Use walrus.staking first to show the balance + available nodes.
33
43
  - walrus.store — persist a receipt/report/memory artifact to Walrus.
34
44
 
35
45
  The capability boundary (important):
36
46
  - Discovery is broad; EXECUTION is bounded. Lyra can only act on the protocols in
37
- protocols.list (currently Scallop + NAVI lending, Sui transfers, Walrus).
47
+ protocols.list (lending on Scallop / NAVI / Suilend; SUI transfers + swaps;
48
+ native + Volo (liquid) SUI staking; WAL staking on Walrus; Walrus storage).
38
49
  - If the best yield a user wants is on a protocol Lyra has NOT integrated, DO NOT
39
50
  invent a transaction. Say so honestly, then offer: (a) the best executable
40
51
  alternative (e.g. supply on NAVI/Scallop), or (b) concise manual steps. The
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  * Transfers: sui.send (policy → simulate → execute → on-chain receipt)
8
8
  * Policy: policy.show, policy.create (lyra::policy AgentPolicy)
9
9
  * Storage: walrus.store (durable, verifiable receipts/memory)
10
+ * WAL staking: walrus.stake, walrus.unstake, walrus.staking (Walrus storage nodes)
10
11
  * Markets: deepbook.markets (DeepBook spot mid prices, read-only)
11
12
  *
12
13
  * Value-moving tools run through policy → simulate → (approval) → execute, and
@@ -53,6 +54,7 @@ import {
53
54
  } from './tools/suilend'
54
55
  import { makeSwap } from './tools/swap'
55
56
  import { makeWalrusStore } from './tools/walrus'
57
+ import { makeWalrusStake, makeWalrusStaking, makeWalrusUnstake } from './tools/walrus-stake'
56
58
  import type { OnchainRuntimeContext } from './types'
57
59
 
58
60
  export {
@@ -132,6 +134,9 @@ const plugin: NativePlugin = {
132
134
  ctx.registerTool(makeUnstake(onchain) as ToolDef)
133
135
  ctx.registerTool(makeVoloStake(onchain) as ToolDef)
134
136
  ctx.registerTool(makeVoloUnstake(onchain) as ToolDef)
137
+ ctx.registerTool(makeWalrusStake(onchain) as ToolDef)
138
+ ctx.registerTool(makeWalrusUnstake(onchain) as ToolDef)
139
+ ctx.registerTool(makeWalrusStaking(onchain) as ToolDef)
135
140
  },
136
141
  }
137
142
 
@@ -1,48 +1,70 @@
1
1
  /**
2
- * Canonical on-chain protocol ids for the policy's protocol allowlist.
2
+ * Canonical on-chain protocol registry the SINGLE SOURCE OF TRUTH for the
3
+ * policy's protocol allowlist, shared by the tools (which tag a vault_spend with a
4
+ * protocol id), the console UI (which lets the owner toggle each one), and the
5
+ * landing. Adding a protocol is ONE entry in `REGISTRY` below — `PROTOCOL_IDS`,
6
+ * `PROTOCOL_LABELS`, and `ALLOWLISTABLE_PROTOCOLS` are all derived from it, and the
7
+ * web + landing import `ALLOWLISTABLE_PROTOCOLS` from here (via the package's
8
+ * `./protocol-ids` subpath) instead of maintaining their own copies.
3
9
  *
4
- * When a tool draws from the vault via `vault_spend`, it tags the action with the
5
- * protocol's package id. The owner's `allowed_protocols` allowlist (settable via
6
- * `lyra::policy::set_allowed_protocols`) is checked against this tag on-chain — so
7
- * an owner can restrict the agent to, say, only staking + NAVI. These ids are the
8
- * SINGLE SOURCE OF TRUTH shared by the tools (which tag) and the console UI (which
9
- * lets the owner toggle) so the two never drift.
10
- *
11
- * They are STABLE labels: a protocol upgrading its package doesn't change the tag
10
+ * The ids are STABLE labels: a protocol upgrading its package doesn't change the tag
12
11
  * (the tag is a self-reported label for the allowlist, not the call target), so an
13
12
  * owner's allowlist keeps working across protocol upgrades. Sourced from each
14
13
  * protocol's SDK on mainnet.
15
14
  *
15
+ * This file is a dependency-free leaf so the browser can import it safely.
16
+ *
16
17
  * `0x0` is the reserved "no specific protocol" tag used by transfers + swaps —
17
18
  * always allowed by the policy (they're bounded by budget/cap/coin/recipient/
18
19
  * slippage instead), so restricting protocols never blocks a plain transfer/swap.
19
20
  */
20
21
  export const NO_PROTOCOL = '0x0'
21
22
 
22
- export const PROTOCOL_IDS = {
23
- suiStaking: '0x3',
24
- navi: '0x1e4a13a0494d5facdbe8473e74127b838c2d446ecec0ce262e2eddafa77259cb',
25
- suilend: '0xf95b06141ed4a174f239417323bde3f209b972f5930d8521ea38a52aff3a6ddf',
26
- volo: '0x68d22cf8bdbcd11ecba1e094922873e4080d4d11133e2443fddda0bfd11dae20',
27
- scallop: '0xde5c09ad171544aa3724dc67216668c80e754860f419136a68d78504eb2e2805',
28
- } as const
23
+ /** The one place a protocol is declared. Everything below is derived. */
24
+ const REGISTRY = [
25
+ { key: 'suiStaking', id: '0x3', label: 'Sui staking' },
26
+ {
27
+ key: 'navi',
28
+ id: '0x1e4a13a0494d5facdbe8473e74127b838c2d446ecec0ce262e2eddafa77259cb',
29
+ label: 'NAVI',
30
+ },
31
+ {
32
+ key: 'suilend',
33
+ id: '0xf95b06141ed4a174f239417323bde3f209b972f5930d8521ea38a52aff3a6ddf',
34
+ label: 'Suilend',
35
+ },
36
+ {
37
+ key: 'volo',
38
+ id: '0x68d22cf8bdbcd11ecba1e094922873e4080d4d11133e2443fddda0bfd11dae20',
39
+ label: 'Volo (vSUI)',
40
+ },
41
+ {
42
+ key: 'scallop',
43
+ id: '0xde5c09ad171544aa3724dc67216668c80e754860f419136a68d78504eb2e2805',
44
+ label: 'Scallop',
45
+ },
46
+ // The type-defining (original) Walrus package — where `StakedWal` lives — as the
47
+ // stable tag for WAL staking (survives Walrus package upgrades).
48
+ {
49
+ key: 'walrusStaking',
50
+ id: '0xfdc88f7d7cf30afab2f82e8380d11ee8f70efb90e863d1de8616fae1bb09ea77',
51
+ label: 'Walrus staking',
52
+ },
53
+ ] as const
54
+
55
+ export type ProtocolKey = (typeof REGISTRY)[number]['key']
29
56
 
30
- export type ProtocolKey = keyof typeof PROTOCOL_IDS
57
+ /** `key package id`, for the tools that tag a vault_spend. */
58
+ export const PROTOCOL_IDS = Object.fromEntries(REGISTRY.map(p => [p.key, p.id])) as Record<
59
+ ProtocolKey,
60
+ string
61
+ >
31
62
 
32
- /** Human labels for each allowlistable protocol (for the owner UI + receipts). */
33
- export const PROTOCOL_LABELS: Record<string, string> = {
34
- [PROTOCOL_IDS.suiStaking]: 'Sui staking',
35
- [PROTOCOL_IDS.navi]: 'NAVI',
36
- [PROTOCOL_IDS.suilend]: 'Suilend',
37
- [PROTOCOL_IDS.volo]: 'Volo (vSUI)',
38
- [PROTOCOL_IDS.scallop]: 'Scallop',
39
- }
63
+ /** `package id human label`, for the owner UI + receipts. */
64
+ export const PROTOCOL_LABELS: Record<string, string> = Object.fromEntries(
65
+ REGISTRY.map(p => [p.id, p.label]),
66
+ )
40
67
 
41
68
  /** The allowlistable protocols in display order, for building the owner UI. */
42
- export const ALLOWLISTABLE_PROTOCOLS: { key: ProtocolKey; id: string; label: string }[] = [
43
- { key: 'suiStaking', id: PROTOCOL_IDS.suiStaking, label: 'Sui staking' },
44
- { key: 'navi', id: PROTOCOL_IDS.navi, label: 'NAVI' },
45
- { key: 'suilend', id: PROTOCOL_IDS.suilend, label: 'Suilend' },
46
- { key: 'volo', id: PROTOCOL_IDS.volo, label: 'Volo (vSUI)' },
47
- { key: 'scallop', id: PROTOCOL_IDS.scallop, label: 'Scallop' },
48
- ]
69
+ export const ALLOWLISTABLE_PROTOCOLS: { key: ProtocolKey; id: string; label: string }[] =
70
+ REGISTRY.map(p => ({ key: p.key, id: p.id, label: p.label }))
package/src/protocols.ts CHANGED
@@ -35,6 +35,15 @@ export const PROTOCOLS: ProtocolCapability[] = [
35
35
  execute: true,
36
36
  tools: ['walrus.store'],
37
37
  },
38
+ {
39
+ id: 'walrus-staking',
40
+ name: 'Walrus staking',
41
+ category: 'staking',
42
+ read: true,
43
+ execute: true,
44
+ tools: ['walrus.stake', 'walrus.unstake', 'walrus.staking'],
45
+ note: 'stake WAL to a Walrus storage node to earn rewards + secure decentralized storage (min 1 WAL)',
46
+ },
38
47
  {
39
48
  id: 'deepbook',
40
49
  name: 'DeepBook',
package/src/tools/send.ts CHANGED
@@ -124,7 +124,7 @@ export function makeSuiSend(ctx: OnchainRuntimeContext): ToolDef<Args> {
124
124
  const receipt = res.objectChanges?.find(
125
125
  c =>
126
126
  c.type === 'created' &&
127
- String((c as { objectType?: string }).objectType).endsWith('::policy::ActionReceipt'),
127
+ String((c as { objectType?: string }).objectType).endsWith('::receipt::ActionReceipt'),
128
128
  ) as { objectId?: string } | undefined
129
129
 
130
130
  return {
@@ -0,0 +1,326 @@
1
+ /**
2
+ * Walrus (WAL) staking — delegate WAL to a Walrus storage node's staking pool to
3
+ * earn rewards + help secure the storage network. This is the integration behind
4
+ * https://stake-wal.wal.app, exposed to the agent:
5
+ *
6
+ * walrus.stake → <walrus>::staking::stake_with_pool → StakedWal
7
+ * walrus.unstake → <walrus>::staking::request_withdraw_stake (returns WAL next epoch)
8
+ * walrus.staking → read: WAL balance, StakedWal positions, top nodes
9
+ *
10
+ * Same guarded pipeline as the other write tools: minimum-amount guard →
11
+ * deterministic off-chain policy → dry-run simulate → execute → on-chain effects
12
+ * check. WAL is drawn from the agent's WAL balance (not the SUI vault — the vault
13
+ * is SUI-typed), so the on-chain SUI budget doesn't apply; the action is bounded
14
+ * by the `walrus` protocol allowlist and audited by the on-chain StakedWal object.
15
+ */
16
+
17
+ import { Transaction } from '@mysten/sui/transactions'
18
+ import {
19
+ MAINNET_WALRUS_PACKAGE_CONFIG,
20
+ TESTNET_WALRUS_PACKAGE_CONFIG,
21
+ WalrusClient,
22
+ } from '@mysten/walrus'
23
+ import type { ToolDef } from 'lyra-core'
24
+ import { z } from 'zod'
25
+ import { evaluatePolicy, suiToMist } from '../policy'
26
+ import { simulate } from '../simulate'
27
+ import type { OnchainRuntimeContext } from '../types'
28
+
29
+ // WAL has 9 decimals (like SUI). Walrus rejects a pool contribution below its
30
+ // minimum stake (staked_wal::mint aborts with code 7 for a too-small stake) — the
31
+ // on-chain floor is 1 WAL, so reject anything smaller early with a clear message.
32
+ const MIN_WAL_FROST = 1_000_000_000n // 1 WAL (Walrus minimum stake)
33
+ const STAKED_WAL_SUFFIX = '::staked_wal::StakedWal'
34
+
35
+ const WAL_TYPE: Record<string, string> = {
36
+ mainnet: '0x356a26eb9e012a68958082340d4c4116e7f55615cf27affcff209cf0ae544f59::wal::WAL',
37
+ }
38
+
39
+ function fmtWal(frost: bigint): string {
40
+ return (Number(frost) / 1e9).toString()
41
+ }
42
+
43
+ interface WalrusStaking {
44
+ pkg: string // walrus package (moveCall target; resolved live so upgrades are safe)
45
+ stakingId: string // the shared Staking system object
46
+ walType: string
47
+ walrus: WalrusClient
48
+ }
49
+
50
+ /** Resolve the live Walrus staking objects + WAL coin type for the network. */
51
+ async function resolveWalrus(ctx: OnchainRuntimeContext): Promise<WalrusStaking> {
52
+ const network = ctx.walrusNetwork ?? ctx.network
53
+ const walrus = new WalrusClient({
54
+ network,
55
+ // cast: @mysten/walrus bundles a different @mysten/sui minor; runtime-compatible.
56
+ suiClient: ctx.client as never,
57
+ })
58
+ const stakingObj = await walrus.stakingObject()
59
+ const cfg = network === 'testnet' ? TESTNET_WALRUS_PACKAGE_CONFIG : MAINNET_WALRUS_PACKAGE_CONFIG
60
+ let walType = WAL_TYPE[network]
61
+ if (!walType) {
62
+ // Non-mainnet: discover the WAL type from the agent's own balances.
63
+ const balances = await ctx.client.getAllBalances({ owner: ctx.agentAddress })
64
+ walType = balances.find(b => b.coinType.endsWith('::wal::WAL'))?.coinType ?? ''
65
+ if (!walType) throw new Error(`could not resolve the WAL coin type on ${network}`)
66
+ }
67
+ return { pkg: stakingObj.package_id, stakingId: cfg.stakingPoolId, walType, walrus }
68
+ }
69
+
70
+ /** Pick a storage node to stake with: match `want` by node id, else the node with
71
+ * the most stake weight (a large, reliable committee member). */
72
+ async function resolveNode(
73
+ walrus: WalrusClient,
74
+ want?: string,
75
+ ): Promise<{ nodeId: string; weight: number } | null> {
76
+ const state = await walrus.systemState()
77
+ const members = state.committee.members
78
+ if (members.length === 0) return null
79
+ if (want?.trim()) {
80
+ const w = want.trim().toLowerCase()
81
+ const m = members.find(x => String(x.node_id).toLowerCase() === w)
82
+ if (m) return { nodeId: m.node_id, weight: m.weight }
83
+ if (w.startsWith('0x')) return { nodeId: want.trim(), weight: 0 }
84
+ return null
85
+ }
86
+ const best = members.reduce((a, b) => (Number(b.weight) > Number(a.weight) ? b : a))
87
+ return { nodeId: best.node_id, weight: best.weight }
88
+ }
89
+
90
+ // ─────────────────────────── walrus.stake ───────────────────────────
91
+
92
+ const StakeSchema = z.object({
93
+ amount: z.string().min(1).describe('Amount of WAL to stake (minimum 1 WAL).'),
94
+ node: z
95
+ .string()
96
+ .optional()
97
+ .describe('Storage node id (0x…) to stake with. Optional — defaults to a large active node.'),
98
+ })
99
+ type StakeArgs = z.infer<typeof StakeSchema>
100
+
101
+ export function makeWalrusStake(ctx: OnchainRuntimeContext): ToolDef<StakeArgs> {
102
+ return {
103
+ name: 'walrus.stake',
104
+ description:
105
+ 'Stake WAL to a Walrus storage node to earn staking rewards and help secure decentralized storage. Minimum 1 WAL. Policy-checked → simulated → executed; returns a StakedWal object.',
106
+ searchHint: 'walrus stake WAL storage node delegate earn rewards staking wal.app',
107
+ schema: StakeSchema,
108
+ handler: async args => {
109
+ try {
110
+ const frost = suiToMist(args.amount) // WAL shares SUI's 9-decimal scaling
111
+ if (frost === undefined || frost <= 0n) {
112
+ return { ok: false, error: `invalid amount "${args.amount}"` }
113
+ }
114
+ if (frost < MIN_WAL_FROST) {
115
+ return {
116
+ ok: false,
117
+ error: `amount too small: ${fmtWal(frost)} WAL is below the ${fmtWal(MIN_WAL_FROST)} WAL minimum for staking`,
118
+ }
119
+ }
120
+
121
+ const { pkg, stakingId, walType, walrus } = await resolveWalrus(ctx)
122
+
123
+ if (ctx.policy) {
124
+ const verdict = evaluatePolicy(
125
+ { kind: 'transfer', coinType: walType, amountMist: frost, protocol: 'walrus' },
126
+ ctx.policy,
127
+ )
128
+ if (!verdict.allowed) {
129
+ return { ok: false, error: `policy blocked: ${verdict.violations.join('; ')}` }
130
+ }
131
+ }
132
+
133
+ const bal = await ctx.client.getBalance({ owner: ctx.agentAddress, coinType: walType })
134
+ if (BigInt(bal.totalBalance) < frost) {
135
+ return {
136
+ ok: false,
137
+ error: `insufficient WAL: have ${fmtWal(BigInt(bal.totalBalance))}, need ${fmtWal(frost)}`,
138
+ }
139
+ }
140
+
141
+ const node = await resolveNode(walrus, args.node)
142
+ if (!node) return { ok: false, error: 'no active Walrus storage node found to stake with' }
143
+
144
+ const coins = await ctx.client.getCoins({ owner: ctx.agentAddress, coinType: walType })
145
+ const [firstCoin, ...restCoins] = coins.data
146
+ if (!firstCoin) return { ok: false, error: 'no WAL coins in the agent wallet' }
147
+
148
+ const tx = new Transaction()
149
+ const primary = tx.object(firstCoin.coinObjectId)
150
+ if (restCoins.length > 0) {
151
+ tx.mergeCoins(
152
+ primary,
153
+ restCoins.map(c => tx.object(c.coinObjectId)),
154
+ )
155
+ }
156
+ const [toStake] = tx.splitCoins(primary, [tx.pure.u64(frost)])
157
+ const staked = tx.moveCall({
158
+ target: `${pkg}::staking::stake_with_pool`,
159
+ arguments: [tx.object(stakingId), toStake, tx.pure.id(node.nodeId)],
160
+ })
161
+ tx.transferObjects([staked], ctx.agentAddress)
162
+
163
+ const sim = await simulate(ctx.client, tx, ctx.agentAddress)
164
+ if (!sim.ok) return { ok: false, error: `pre-flight simulation failed: ${sim.reason}` }
165
+
166
+ const res = await ctx.client.signAndExecuteTransaction({
167
+ signer: ctx.keypair,
168
+ transaction: tx,
169
+ options: { showEffects: true, showObjectChanges: true },
170
+ })
171
+ if (res.effects?.status?.status !== 'success') {
172
+ return {
173
+ ok: false,
174
+ error: `execution failed: ${res.effects?.status?.error ?? 'unknown'}`,
175
+ }
176
+ }
177
+ await ctx.client.waitForTransaction({ digest: res.digest })
178
+ const stakedWal = res.objectChanges?.find(
179
+ c =>
180
+ c.type === 'created' &&
181
+ String((c as { objectType?: string }).objectType).endsWith(STAKED_WAL_SUFFIX),
182
+ ) as { objectId?: string } | undefined
183
+
184
+ return {
185
+ ok: true,
186
+ data: {
187
+ protocol: 'walrus-staking',
188
+ action: 'stake',
189
+ amountWal: args.amount,
190
+ node: node.nodeId,
191
+ digest: res.digest,
192
+ stakedWalId: stakedWal?.objectId ?? null,
193
+ status: 'success',
194
+ },
195
+ }
196
+ } catch (e) {
197
+ return { ok: false, error: (e as Error).message.slice(0, 240) }
198
+ }
199
+ },
200
+ }
201
+ }
202
+
203
+ // ─────────────────────────── walrus.unstake ───────────────────────────
204
+
205
+ const UnstakeSchema = z.object({
206
+ stakedWalId: z
207
+ .string()
208
+ .optional()
209
+ .describe('StakedWal object id to withdraw. Optional — defaults to the first staked position.'),
210
+ })
211
+ type UnstakeArgs = z.infer<typeof UnstakeSchema>
212
+
213
+ export function makeWalrusUnstake(ctx: OnchainRuntimeContext): ToolDef<UnstakeArgs> {
214
+ return {
215
+ name: 'walrus.unstake',
216
+ description:
217
+ 'Request to withdraw staked WAL from a Walrus node. The principal + rewards become withdrawable after the next epoch. Uses a StakedWal object id, or the first staked position if omitted.',
218
+ searchHint: 'walrus unstake withdraw WAL staking redeem claim rewards storage node',
219
+ schema: UnstakeSchema,
220
+ handler: async args => {
221
+ try {
222
+ const { pkg, stakingId, walType } = await resolveWalrus(ctx)
223
+
224
+ let stakedId = args.stakedWalId?.trim()
225
+ if (!stakedId) {
226
+ const owned = await ctx.client.getOwnedObjects({
227
+ owner: ctx.agentAddress,
228
+ filter: { StructType: `${walType.split('::')[0]}${STAKED_WAL_SUFFIX}` },
229
+ })
230
+ stakedId = owned.data[0]?.data?.objectId
231
+ if (!stakedId) return { ok: false, error: 'no StakedWal position found to unstake' }
232
+ }
233
+
234
+ if (ctx.policy) {
235
+ const verdict = evaluatePolicy(
236
+ { kind: 'transfer', coinType: walType, amountMist: 0n, protocol: 'walrus' },
237
+ ctx.policy,
238
+ )
239
+ if (!verdict.allowed) {
240
+ return { ok: false, error: `policy blocked: ${verdict.violations.join('; ')}` }
241
+ }
242
+ }
243
+
244
+ const tx = new Transaction()
245
+ tx.moveCall({
246
+ target: `${pkg}::staking::request_withdraw_stake`,
247
+ arguments: [tx.object(stakingId), tx.object(stakedId)],
248
+ })
249
+
250
+ const sim = await simulate(ctx.client, tx, ctx.agentAddress)
251
+ if (!sim.ok) return { ok: false, error: `pre-flight simulation failed: ${sim.reason}` }
252
+
253
+ const res = await ctx.client.signAndExecuteTransaction({
254
+ signer: ctx.keypair,
255
+ transaction: tx,
256
+ options: { showEffects: true },
257
+ })
258
+ if (res.effects?.status?.status !== 'success') {
259
+ return {
260
+ ok: false,
261
+ error: `execution failed: ${res.effects?.status?.error ?? 'unknown'}`,
262
+ }
263
+ }
264
+ await ctx.client.waitForTransaction({ digest: res.digest })
265
+
266
+ return {
267
+ ok: true,
268
+ data: {
269
+ protocol: 'walrus-staking',
270
+ action: 'unstake',
271
+ stakedWalId: stakedId,
272
+ digest: res.digest,
273
+ note: 'WAL becomes withdrawable after the next Walrus epoch',
274
+ status: 'success',
275
+ },
276
+ }
277
+ } catch (e) {
278
+ return { ok: false, error: (e as Error).message.slice(0, 240) }
279
+ }
280
+ },
281
+ }
282
+ }
283
+
284
+ // ─────────────────────────── walrus.staking (read) ───────────────────────────
285
+
286
+ const ReadSchema = z.object({})
287
+ type ReadArgs = z.infer<typeof ReadSchema>
288
+
289
+ export function makeWalrusStaking(ctx: OnchainRuntimeContext): ToolDef<ReadArgs> {
290
+ return {
291
+ name: 'walrus.staking',
292
+ description:
293
+ "Read the agent's Walrus staking position: WAL balance, current StakedWal positions, and a few large storage nodes to stake with.",
294
+ searchHint: 'walrus staking position WAL balance staked nodes committee read status',
295
+ schema: ReadSchema,
296
+ handler: async () => {
297
+ try {
298
+ const { walType, walrus } = await resolveWalrus(ctx)
299
+ const [bal, owned, state] = await Promise.all([
300
+ ctx.client.getBalance({ owner: ctx.agentAddress, coinType: walType }),
301
+ ctx.client.getOwnedObjects({
302
+ owner: ctx.agentAddress,
303
+ filter: { StructType: `${walType.split('::')[0]}${STAKED_WAL_SUFFIX}` },
304
+ options: { showType: true },
305
+ }),
306
+ walrus.systemState(),
307
+ ])
308
+ const topNodes = [...state.committee.members]
309
+ .sort((a, b) => Number(b.weight) - Number(a.weight))
310
+ .slice(0, 5)
311
+ .map(m => ({ nodeId: m.node_id, weight: m.weight }))
312
+ return {
313
+ ok: true,
314
+ data: {
315
+ walBalance: fmtWal(BigInt(bal.totalBalance)),
316
+ stakedPositions: owned.data.map(o => o.data?.objectId).filter(Boolean),
317
+ committeeSize: state.committee.members.length,
318
+ topNodes,
319
+ },
320
+ }
321
+ } catch (e) {
322
+ return { ok: false, error: (e as Error).message.slice(0, 240) }
323
+ }
324
+ },
325
+ }
326
+ }
package/src/vault.ts CHANGED
@@ -9,10 +9,13 @@
9
9
  import { type SuiNetwork, makeSuiClient } from './client'
10
10
  import { deriveAgentAddress } from './derive'
11
11
 
12
- // A module keeps its DEFINING package id for types/events: `policy` shipped in
13
- // the original publish; `vault` was added in the first upgrade.
14
- const ORIGINAL_PKG = '0x250880a4c1a268da8011b164f599d4e100cefce84f862d36396cd1a943ee8a35'
15
- const VAULT_PKG = '0xa40689cc541f57af123e90819e73eab8a551e4385ab91bee89d02f6691590211'
12
+ // Types/events are addressed by the id of the package that DEFINES them. The v1
13
+ // package is a single fresh publish (policy, vault, receipt, allowlist, constants
14
+ // all shipped together), so every module shares one id today. These stay separate
15
+ // constants so a FUTURE upgrade can again split the LATEST (moveCall) id from a
16
+ // module's DEFINING id without touching call sites.
17
+ const ORIGINAL_PKG = '0x1925bced9aeb16ca8159be0a10d39a0778fe618404443a4b6149116ad9997617'
18
+ const VAULT_PKG = '0x1925bced9aeb16ca8159be0a10d39a0778fe618404443a4b6149116ad9997617'
16
19
 
17
20
  export interface OwnerVault {
18
21
  policyId: string