Examples

Multi-Language Examples

Use the Buff REST API from any language. No SDK needed — just HTTP.

Note
These examples use the REST API. Replace the base URL with your deployed Buff instance.

Python

buff_roundup.py
typescript
1import requests
2
3BUFF_API = "https://sow-beryl.vercel.app"
4
5def calculate_roundup(tx_value_usd: float, plan: str = "sprout"):
6 """Calculate the round-up for a transaction."""
7 res = requests.post(f"{BUFF_API}/api/roundup", json={
8 "txValueUsd": tx_value_usd,
9 "plan": plan,
10 })
11 data = res.json()
12 if not data["ok"]:
13 raise Exception(data["error"])
14 return data["data"]
15
16def get_prices():
17 """Get current token prices."""
18 res = requests.get(f"{BUFF_API}/api/price")
19 return res.json()["data"]["prices"]
20
21def get_swap_quote(input_lamports: int, asset: str = "BTC"):
22 """Get a Jupiter swap quote."""
23 res = requests.post(f"{BUFF_API}/api/swap/quote", json={
24 "inputLamports": input_lamports,
25 "targetAsset": asset,
26 })
27 return res.json()["data"]
28
29# Usage
30breakdown = calculate_roundup(27.63, "tree")
31print(f"Tx: ${breakdown['txValueUsd']}")
32print(f"Round-up: ${breakdown['roundUpUsd']}")
33print(f"Investing: ${breakdown['userInvestmentUsd']}")
34print(f"Buff fee: ${breakdown['buffFeeUsd']}")
35
36# Get swap quote
37quote = get_swap_quote(100_000_000, "USDC") # 0.1 SOL
38print(f"Route: {quote['route']}")
39print(f"Expected output: {quote['outputAmount']}")

Rust

buff.rs
typescript
1use reqwest::Client;
2use serde::Deserialize;
3use serde_json::json;
4
5const BUFF_API: &str = "https://sow-beryl.vercel.app";
6
7#[derive(Debug, Deserialize)]
8struct ApiResponse {
9 ok: bool,
10 data: RoundUpData,
11}
12
13#[derive(Debug, Deserialize)]
14#[serde(rename_all = "camelCase")]
15struct RoundUpData {
16 round_up_usd: f64,
17 user_investment_usd: f64,
18 skipped: bool,
19}
20
21async fn calculate_roundup(
22 client: &Client, tx_value: f64, plan: &str,
23) -> Result<RoundUpData, Box<dyn std::error::Error>> {
24 let res: ApiResponse = client
25 .post(format!("{}/api/roundup", BUFF_API))
26 .json(&json!({"txValueUsd": tx_value, "plan": plan}))
27 .send().await?
28 .json().await?;
29 Ok(res.data)
30}
31
32#[tokio::main]
33async fn main() -> Result<(), Box<dyn std::error::Error>> {
34 let client = Client::new();
35 let b = calculate_roundup(&client, 27.63, "tree").await?;
36 println!("Round-up: {}", b.round_up_usd);
37 println!("Investing: {}", b.user_investment_usd);
38 println!("Skipped: {}", b.skipped);
39 Ok(())
40}

Go

buff.go
typescript
1package main
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "net/http"
8)
9
10const buffAPI = "https://sow-beryl.vercel.app"
11
12type RoundUpRequest struct {
13 TxValueUsd float64 `json:"txValueUsd"`
14 Plan string `json:"plan"`
15}
16
17type RoundUpData struct {
18 RoundUpUsd float64 `json:"roundUpUsd"`
19 UserInvestmentUsd float64 `json:"userInvestmentUsd"`
20 Skipped bool `json:"skipped"`
21}
22
23type Response struct {
24 Ok bool `json:"ok"`
25 Data RoundUpData `json:"data"`
26}
27
28func calculateRoundUp(txValue float64, plan string) (*RoundUpData, error) {
29 body, _ := json.Marshal(RoundUpRequest{
30 TxValueUsd: txValue,
31 Plan: plan,
32 })
33
34 resp, err := http.Post(
35 buffAPI+"/api/roundup",
36 "application/json",
37 bytes.NewReader(body),
38 )
39 if err != nil {
40 return nil, err
41 }
42 defer resp.Body.Close()
43
44 var result Response
45 json.NewDecoder(resp.Body).Decode(&result)
46 return &result.Data, nil
47}
48
49func main() {
50 b, err := calculateRoundUp(27.63, "tree")
51 if err != nil {
52 panic(err)
53 }
54
55 fmt.Printf("Round-up: $%.2f\n", b.RoundUpUsd)
56 fmt.Printf("Investing: $%.4f\n", b.UserInvestmentUsd)
57 fmt.Printf("Skipped: %v\n", b.Skipped)
58}

cURL

bash
bash
# Calculate round-up
curl -s -X POST https://sow-beryl.vercel.app/api/roundup \
-H "Content-Type: application/json" \
-d '{"txValueUsd": 27.63, "plan": "tree"}' | jq .data
# Get prices
curl -s https://sow-beryl.vercel.app/api/price | jq .data.prices
# Get swap quote
curl -s -X POST https://sow-beryl.vercel.app/api/swap/quote \
-H "Content-Type: application/json" \
-d '{"inputLamports": 100000000, "targetAsset": "USDC"}' | jq .data