Skip to content
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 141 additions & 0 deletions .github/workflows/claude-review.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
name: Perform a code review when a pull request is created.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This CI workflow has nothing to do with Save support. Please split it into its own PR so it can be reviewed and reverted separately.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This CI workflow has nothing to do with Save support. It should go in its own PR (or be dropped here) so the protocol change can be reviewed and reverted on its own.

on:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]

jobs:
claude:
# Skip drafts, and skip fork PRs: on `pull_request` they don't get the
# ANTHROPIC_API_KEY secret, so the review would only fail.
if: >-
!github.event.pull_request.draft &&
github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
structured_output: ${{ steps.run_claude.outputs.structured_output }}
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
with:
# Explicitly check out the PR's merge commit.
ref: refs/pull/${{ github.event.pull_request.number }}/merge
persist-credentials: false

- name: Pre-fetch base and head refs for the PR
env:
PR_BASE_REF: ${{ github.event.pull_request.base.ref }}
PR_NUMBER: ${{ github.event.pull_request.number }}
run: |
# Pass GitHub expressions through env and quote shell expansions.
git fetch --no-tags origin \
"$PR_BASE_REF" \
"+refs/pull/$PR_NUMBER/head"

# If you want Claude to build and run code, install any dependencies that
# need to be downloaded before the "Run Claude" step, and add the commands
# it may run to --allowedTools below (e.g. "Bash(npm test:*)"). Any tool
# not listed there is denied.

- name: Run Claude
id: run_claude
uses: anthropics/claude-code-action@86d88e619d8e6caf07b5c3944dd14f441c533718 # v1.0.243
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
# Use this job's read-only token instead of the Claude GitHub App,
# which needs `id-token: write` and would get write access.
github_token: ${{ github.token }}
prompt: |
This is PR #${{ github.event.pull_request.number }} for ${{ github.repository }}.

Review ONLY the changes introduced by the PR, so consider:
git log --oneline ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }}
git diff ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }}

Suggest any improvements, potential bugs, or issues.
Be concise and specific in your feedback.

Return your review in two parts:
- `summary`: a short Markdown overview of the PR and your overall assessment.
- `comments`: one entry per specific issue, anchored to the line it concerns.
`path` is relative to the repository root. `line` is the line number in
the PR head version of the file (${{ github.event.pull_request.head.sha }}),
and must be a line shown in the diff above. The working tree is the merge
commit, so its line numbers can differ; check them with
`git show ${{ github.event.pull_request.head.sha }}:<path>`.
Put issues that don't belong to a single line in `summary` instead.

Pull request title and body:
----
${{ github.event.pull_request.title }}
${{ github.event.pull_request.body }}
claude_args: |
--allowedTools "Read,Grep,Glob,Bash(git log:*),Bash(git diff:*),Bash(git show:*)"
--json-schema '{
"type": "object",
"properties": {
"summary": {
"type": "string",
"description": "Overall review as Markdown, posted as the review body."
},
"comments": {
"type": "array",
"description": "Inline comments, each anchored to one line of the PR diff.",
"items": {
"type": "object",
"properties": {
"path": { "type": "string", "description": "File path relative to the repository root." },
"line": { "type": "integer", "minimum": 1, "description": "Line number in the PR head version of the file. Must be within the diff." },
"body": { "type": "string", "description": "The comment, as Markdown." }
},
"required": ["path", "line", "body"]
}
}
},
"required": ["summary", "comments"]
}'

post_feedback:
runs-on: ubuntu-latest
needs: claude
if: needs.claude.outputs.structured_output != ''
permissions:
issues: write
pull-requests: write
steps:
- name: Report Claude feedback
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0
env:
CLAUDE_STRUCTURED_OUTPUT: ${{ needs.claude.outputs.structured_output }}
with:
github-token: ${{ github.token }}
script: |
const { summary = '', comments = [] } = JSON.parse(process.env.CLAUDE_STRUCTURED_OUTPUT);
const pr = context.payload.pull_request;
if (!summary.trim() && comments.length === 0) {
core.info('Claude returned an empty review; nothing to post.');
return;
}

try {
await github.rest.pulls.createReview({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: pr.number,
commit_id: pr.head.sha,
event: 'COMMENT',
body: summary.trim() || 'See inline comments.',
comments: comments.map(({ path, line, body }) => ({ path, line, side: 'RIGHT', body })),
});
} catch (error) {
// GitHub rejects the whole review if any comment points outside the
// diff. Fall back to a single PR comment so no feedback is lost.
core.warning(`Could not post inline review (${error.message}); posting a plain comment instead.`);
const details = comments.map(({ path, line, body }) => `**\`${path}:${line}\`**\n\n${body}`);
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
body: [summary.trim(), ...details].filter(Boolean).join('\n\n---\n\n'),
});
}
8 changes: 8 additions & 0 deletions crates/core/src/scenarios/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Protocols that are natively supported by Surfpool will have their IDLs included
- **Switchboard On-Demand** - On-demand oracle with QuoteAccount override template
- **Kamino** – Lending (v1.23.0), Scope oracle, Farms, Swap/LIMO, Earn vaults and Liquidity, across six programs. See [protocols/kamino/README.md](./protocols/kamino/README.md)
- **Drift v2** - Perp and spot markets, user state, and global state
- **Save v2.0.2** – Lending (formerly Solend) with reserve risk, rate, limit and liquidity templates and a one-deposit, one-borrow obligation template. See [protocols/save/v2/README.md](./protocols/save/v2/README.md)
- **Pump v1** - Bonding curve launchpad with curve reserve and global config override templates
- **Phoenix Eternal** - Perpetuals venue with trader collateral, mark price, maintenance margin, market fee, withdraw limit, trader capability, stop-loss trigger and delegated permission templates. See [protocols/phoenix-eternal/README.md](./protocols/phoenix-eternal/README.md)
- **PumpSwap v1** - Constant-product AMM with pool state and global config override templates, including canonical pool derivation for migrated pump.fun coins
Expand Down Expand Up @@ -48,6 +49,13 @@ accounts from mainnet, so they need a network connection and are compiled only b
cargo test -p surfpool-core --features integration-tests kamino
```

Save coverage in `crates/core/src/tests/save/` works the same way, and also runs the deployed Save
program in LiteSVM over those accounts:

```
cargo test -p surfpool-core --features integration-tests save
```

Set `SURFPOOL_TEST_RPC_URL` to use a private endpoint instead of the public one. The default test
run needs no network.

Expand Down
188 changes: 188 additions & 0 deletions crates/core/src/scenarios/protocols/save/v2/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
# Save

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we have any moving parts like with Phoenix, that one change affects the entire protocol and we should update it?


Save, formerly Solend, is a pool lender. Program `So1endDq2YkqhipRh3WViPa8hdiSpxWy6z3Z6tMCpAo`,
build 2.0.2. Six templates: four on reserves and two on obligations.

Save publishes no IDL and its accounts carry no discriminator, so the templates write bytes at fixed
offsets. They describe a 619-byte Reserve and a 1300-byte Obligation. Point them only at accounts of
that kind; the account is the caller's responsibility.

Save stores settings someone chose (`liquidation_threshold`) and values it computed from them
(`market_price`, the obligation's `borrowed_value`). Every borrow, withdraw and liquidation needs
`refresh_reserve` and `refresh_obligation` in the same slot, and those recompute every computed
value. So override inputs, not results:

| Want to change | Override this | Not this |
|---|---|---|
| A price | `pyth-price-feed-v2` on the reserve's oracle | the reserve's `market_price` |
| Position health | `save-reserve-risk` → `config.liquidation_threshold` | the obligation's `*_value` fields |

# Template index

| Template | Overrides |
|---|---|
| `save-reserve-risk` | loan to value, liquidation threshold and bonus, borrow weight |
| `save-reserve-rates` | the borrow rate curve |
| `save-reserve-limits` | deposit and borrow caps |
| `save-reserve-liquidity` | how much the reserve can lend or pay out |
| `save-obligation-position` | a whole position: one collateral deposit and one borrow |
| `save-obligation-owner` | the wallet that owns an existing position |

## Number formats

| You'll see | It means | Example |
|---|---|---|
| `*_wads` | value x 10^18, as a decimal **string** | 500 USDC of debt → `"500000000000000000000000000"` |
| percent fields | whole percent in one byte | `72` = 72% |
| `*_bps` | basis points | `10000` = 100% |
| `deposited_amount` | cTokens, the reserve's collateral mint, in its smallest unit | |
| token amounts | the mint's smallest unit | 1 USDC → `1000000`, 1 SOL → `1000000000` |

u128 values exceed what a JSON number holds exactly, so they must be quoted.

## Picking a market

Every template takes the account it writes; callers are responsible for passing a reserve or an
obligation. The main pool is `4UpD2fh7xH3VP9QQaXtsS1YY3bxzWhtfpks7FatyKvdY`. A token's reserve
and the price account it reads come from one `getProgramAccounts` call on the program: filter on
`dataSize` 619, the market at offset 10 and the liquidity mint at offset 42, with a `dataSlice` of
32 bytes at offset 107. The templates' `llm_context` spells the call out. For example, the main
pool's SOL reserve is `8PbodeaosQP19SjYFx855UMqWxH2HynZLdBXmsrbac36` and its USDC reserve
`BgxfHJDzm44T7XG68MYKx7YisTjZu73tVovyZSjJMpmw`.

**An obligation is not a PDA.** Its address is
`createWithSeed(owner, seed, So1endDq2YkqhipRh3WViPa8hdiSpxWy6z3Z6tMCpAo)`, where `seed` is the first
32 characters of the market's address. For the main pool that is `4UpD2fh7xH3VP9QQaXtsS1YY3bxzWhtf`.
A wallet's obligations can also be listed with `getProgramAccounts`, filtered on `dataSize: 1300` and
the owner at offset 42.

Each reserve names its price oracle at offset 107. In the main pool these are Pyth PriceUpdateV2
accounts, the same accounts `pyth-price-feed-v2` writes:

| Reserve | Oracle | `pyth-price-feed-v2` feed |
|---|---|---|
| SOL | `7UVimffxr9ow1uXYxsr4LHAcV58mLzhmwaeKvJ1pjLiE` | SOL/USD |
| USDC | `Dpw1EAVrSB1ibxiDQyTAW6Zip3J4Btk2x4SgApQCeFbX` | USDC/USD |

**Feeds are shared.** SOL/USD also prices other main-pool reserves, most of them liquid-staking
tokens priced as SOL times a fixed multiplier.

# Recipes

## Make a position liquidatable

Two independent levers. Either one works.

```
save-reserve-risk on the SOL reserve
config.liquidation_threshold: 50 # was 72
```

```
pyth-price-feed-v2 feed_id: SOL/USD, fetchBeforeUse: true
price_message.price: 5900000000 # $59, 8 decimals
price_message.ema_price: 5900000000
```

**Why:** a position is liquidatable once its borrowed value reaches its collateral's value times the
threshold. Lowering the threshold shrinks the limit; halving the price halves the collateral's
value. Both survive `refresh_obligation`.

## Build a position from scratch

```
save-obligation-position on an existing obligation
owner: <your wallet>
lending_market: 4UpD2fh7xH3VP9QQaXtsS1YY3bxzWhtfpks7FatyKvdY
deposits_len: 1
borrows_len: 1
deposits.0.deposit_reserve: <the SOL reserve>
deposits.0.deposited_amount: 100000000000 # 100 cSOL
borrows.0.borrow_reserve: <the USDC reserve>
borrows.0.cumulative_borrow_rate_wads: "<the USDC reserve's value at offset 195>"
borrows.0.borrowed_amount_wads: "5000000000000000000000000000" # 5000 USDC
```

**Set every property.** The account's old entries are not cleared, so a field left out keeps
whatever was there.

- `deposited_amount` is in cTokens. One cToken is worth `(available_amount + borrowed_amount_wads /
10^18 - accumulated_protocol_fees_wads / 10^18) / collateral.mint_total_supply` of the underlying
token, all read from the collateral reserve.
- `cumulative_borrow_rate_wads` must be copied from the debt reserve. A higher value fails with
`NegativeInterestRate`; a lower one charges the difference as interest on the next refresh.

The obligation must already exist. Pull a mainnet obligation from upstream with
`fetchBeforeUse: true`, or create one for your wallet with `init_obligation` first.

## Take over a real position

```
save-obligation-owner on a mainnet obligation
owner: <your wallet>
```

The position keeps its deposits, debt and address. Your wallet can now withdraw or borrow against
it. A client that finds obligations by deriving the address from the wallet will not find it; one
that searches by owner will.

## Block an action to test the rejection

```
save-reserve-limits config.borrow_limit: 0 # no new borrows on this reserve
save-reserve-limits config.deposit_limit: 0 # no new deposits
```

## Run a reserve dry

```
save-reserve-liquidity liquidity.available_amount: 0
```

**Lower, never raise.** The field mirrors the reserve's liquidity vault, which the template does not
touch. Lowering it makes large borrows and withdrawals fail. Raising it above the vault's real
balance promises tokens the vault cannot pay, and the transaction fails when it settles.

## Make borrowing expensive

```
save-reserve-rates
config.min_borrow_rate: 50
config.optimal_borrow_rate: 50
config.max_borrow_rate: 50
config.super_max_borrow_rate: 50
```

Rates are APR in whole percent, compounded per slot on the next `refresh_reserve`.

## Prices on a fork

Save accepts a Pyth price for **120 seconds** after its `publish_time`, measured against the Surfnet
clock, and has no setting for it. Nothing publishes Pyth prices on a surfnet, so a price is usable
for 120 seconds of Surfnet clock after it was loaded:

- A price override with `fetchBeforeUse: true` loads upstream's current price account when it plays,
so leave `publish_time` unset. Playing the scenario again loads it again.
- A transaction refreshes every reserve the obligation lists, so every one of their prices must be
fresh, not only the one the scenario moves. Reload an older one with `surfnet_resetAccount` on its
price account; the next read loads upstream's current copy.
- Studio's paused clock stops prices ageing after Play. A running clock or a time travel ages them.
- An older `publish_time` written into the scenario makes a price stale on purpose.

Keep-alive ([solana-foundation/surfpool#906](https://github.com/solana-foundation/surfpool/pull/906))
will keep the prices published once it lands.

# Troubleshooting

| Symptom | Fix |
|---|---|
| A price override on SOL had no effect | The Pyth price aged past 120 s while the clock ran, and SOL fell back to its Switchboard feed. Play the scenario again - see "Prices on a fork" |
| `InvalidOracleConfig` on refresh_reserve | Same cause on a reserve with no fallback, such as USDC; reload its price account with `surfnet_resetAccount`. It also fires when `conf x 10 > price`, so lower `conf` along with a crashed price |
| `Math operation overflow` on refresh_reserve | The reserve was loaded from upstream after the Surfnet clock stopped, so its `last_update.slot` is ahead of the clock. Move the clock to the current time with `surfnet_timeTravel`: `[{"absoluteTimestamp": <now in milliseconds>}]` |
| A health or `market_price` override disappeared | Recomputed by `refresh_reserve` or `refresh_obligation`. Override the oracle or the reserve's settings instead |
| `NegativeInterestRate` | The borrow entry's `cumulative_borrow_rate_wads` is above the reserve's. Copy the reserve's current value |
| `ReserveStale` or `ObligationStale` | A reserve or obligation is fresh only in the slot it was refreshed. Put `refresh_reserve` for every reserve the obligation lists, then `refresh_obligation`, in the same transaction |
| A liquidation says the obligation is healthy | The borrow value is still below the threshold value. Lower `config.liquidation_threshold` further or crash the price further |
| The position override did nothing | The obligation account does not exist on the surfnet yet. Pull a mainnet one from upstream with `fetchBeforeUse: true` or create it with `init_obligation` |
| Unexpected entries after a position override | The old account had more entries and a property was left out. Set every property of `save-obligation-position` |
| The entries swapped places after a refresh | Not a bug. `refresh_obligation` moves the highest-weighted borrow first and drops empty entries |
Loading
Loading