@zyfai/sdk 0.3.0 → 0.4.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
@@ -991,16 +991,16 @@ const earnings = await sdk.getOnchainEarnings(walletAddress);
991
991
  console.log("Total by token:", earnings.data.totalEarningsByToken);
992
992
  // Per-chain totals (chain → token → amount): { "8453": { "USDC": "0.01" }, "42161": {...} }
993
993
  console.log("Total by chain:", earnings.data.totalEarningsByChain);
994
- // Net totals: lifetime + unrealized + current × 0.9 (never total × 0.9)
994
+ // Net totals: (lifetime + unrealized + current) × 0.9
995
995
  console.log("Net by token:", earnings.data.totalEarningsByTokenWithFee);
996
996
  console.log("Net by chain:", earnings.data.totalEarningsByChainWithFee);
997
997
  ```
998
998
 
999
999
  **Fee formula for `*WithFee` earnings fields**
1000
1000
 
1001
- - `totalWithFee = lifetime + unrealized + current × 0.9`
1002
- - Do **not** apply `× 0.9` to lifetime or unrealized
1003
- - Aligns with portfolio: pending fee = `current × 0.1` only
1001
+ - `totalWithFee = (lifetime + unrealized + current) × 0.9`
1002
+ - Ledger lifetime and unrealized are gross (`fee × 10` when a fee is taken)
1003
+ - Portfolio `balanceWithFee` still subtracts only the pending fee on `current`
1004
1004
 
1005
1005
  #### Calculate Onchain Earnings (Refresh)
1006
1006
 
@@ -1459,33 +1459,95 @@ Some Data API endpoints may require server-side CORS configuration. If you see C
1459
1459
 
1460
1460
  ## Integration testing
1461
1461
 
1462
- Use opt-in Vitest integration tests to prove a new backend feature end-to-end through the **public SDK** against a **local** `zyfai-api` instance. This is the normal workflow when adding or changing execution API behaviour.
1463
-
1464
- Integration tests live in `src/integration/*.integration.test.ts`, mirror the matching script under `examples/`, and are **not** part of `npm run check` (no secrets required in CI). Unit tests in `src/utils/` stay mocked and fast.
1462
+ Use opt-in Vitest integration tests to prove backend behaviour end-to-end through the **public SDK**. Tests live in `src/integration/*.integration.test.ts`, mirror scripts under `examples/`, and are **not** part of `npm run check` (no secrets required in CI). Unit tests in `src/utils/` stay mocked and fast.
1465
1463
 
1466
1464
  ### Setup
1467
1465
 
1468
1466
  ```bash
1469
1467
  cd zyfai-sdk
1470
- cp .env.test.example .env.test # once — fill ZYFAI_API_KEY and PRIVATE_KEY (gitignored)
1468
+ cp .env.test.example .env.test # once — fill keys below (gitignored)
1471
1469
  ```
1472
1470
 
1473
- Vitest loads `.env.test` automatically (`vitest.config.ts`). Apply API migrations, then start the local stack from the workspace parent:
1471
+ Vitest loads `.env.test` automatically (`vitest.config.ts`).
1472
+
1473
+ **Credentials** — one shared signing wallet, per-environment partner keys:
1474
+
1475
+ | Variable | Purpose |
1476
+ | --- | --- |
1477
+ | `PRIVATE_KEY` | Same test EOA on local, staging, and production |
1478
+ | `LOCAL_ZYFAI_API_KEY` | Partner key when `ZYFAI_ENV=local` |
1479
+ | `STAGING_ZYFAI_API_KEY` | Partner key when `ZYFAI_ENV=staging` |
1480
+ | `PRODUCTION_ZYFAI_API_KEY` | Partner key when `ZYFAI_ENV=production` |
1481
+ | `LOCAL_SDK_API_KEYS_ADMIN_API_KEY` | Admin key for `POST /admin/sdk-api-keys` when `ZYFAI_ENV=local` |
1482
+ | `STAGING_SDK_API_KEYS_ADMIN_API_KEY` | Same when `ZYFAI_ENV=staging` |
1483
+ | `PRODUCTION_SDK_API_KEYS_ADMIN_API_KEY` | Same when `ZYFAI_ENV=production` |
1484
+
1485
+ `ZYFAI_ENV` selects the API stack and which `*_ZYFAI_API_KEY` is passed to `integrationSdkConfig()`.
1486
+
1487
+ | `ZYFAI_ENV` | Execution API |
1488
+ | --- | --- |
1489
+ | `local` (default) | `http://localhost:3000` |
1490
+ | `staging` | `https://staging-api.zyf.ai` |
1491
+ | `production` | `https://api.zyf.ai` |
1492
+
1493
+ Helpers in `src/integration/utils.ts` wire URLs from `src/config/endpoints.ts` (`integrationSdkConfig()`, `integrationEnvironment()`, `readIntegrationApiKey()`, `pollUntil`, fresh-user setup, shared release-smoke amount logic). **Do not** add helper `function`s at the top of `*.integration.test.ts` — extend `utils.ts` instead so tests stay readable (`describe` / `it` only, plus feature-local constants).
1494
+
1495
+ **Local stack only** (`ZYFAI_ENV=local`): apply API migrations, then start the workspace stack:
1474
1496
 
1475
1497
  ```bash
1476
- cd ../zyfai-api && pnpm migration:up # required for deposit lifecycle (eoa_deposit.lifecycle_status, …)
1498
+ cd ../zyfai-api && pnpm migration:up
1477
1499
  cd .. # zyfai-workspace root
1478
1500
  pnpm dev
1479
1501
  ```
1480
1502
 
1481
1503
  If the API starts before migrations run, deposit handover crons and `log_deposit` will fail with missing-column errors.
1482
1504
 
1505
+ **Test kinds**
1506
+
1507
+ Each suite uses `describeIntegrationSuite()` from `utils.ts` with `spendProfile`: `readonly` or `spends_funds`. Suites with `spends_funds` **skip automatically** when `ZYFAI_ENV=production` (use staging for deposit/withdraw smokes).
1508
+
1509
+ | Kind | Environments | `describeIntegrationSuite` options |
1510
+ | --- | --- | --- |
1511
+ | Read-only (e.g. `get-protocols`) | local, staging, production | `{ spendProfile: "readonly" }` |
1512
+ | Fresh funded user (`setupFreshFundedUser`) | local, staging | `{ spendProfile: "spends_funds", credentialGate: "fresh_user" }` — **0.1 USDC** per run |
1513
+ | Persistent wallet (`PRIVATE_KEY` EOA) | local, staging | `{ spendProfile: "spends_funds" }` (default `credentialGate: "persistent_wallet"`) |
1514
+
1515
+ Release prep on **staging**: run one file via workspace skill **[backend-smoke](../.cursor/skills/backend-smoke/SKILL.md)** (e.g. `deposit-withdraw` or `send-deposit-wait-credit` for wallet pool / handover). After prod deploy, use **`get-protocols`** (or another `readonly` suite) only.
1516
+
1517
+ #### Fresh-user tests on staging or prod
1518
+
1519
+ These call `POST /api/v1/admin/sdk-api-keys`. The api process must have **`SDK_API_KEYS_ADMIN_API_KEY`** in deploy `.env` (many boxes only have `API_KEY` today). One-time on the api host:
1520
+
1521
+ ```bash
1522
+ cd /root/staging-zyfai # or prod deploy path
1523
+ grep '^API_KEY=' .env # existing ops key — do not paste into chat
1524
+ # Add a new line (staging: often same value as API_KEY; prod: prefer a dedicated secret):
1525
+ # SDK_API_KEYS_ADMIN_API_KEY='…'
1526
+ pm2 reload ecosystem.config.js # reload API + background per your runbook
1527
+ ```
1528
+
1529
+ In `zyfai-sdk/.env.test`:
1530
+
1531
+ ```env
1532
+ ZYFAI_ENV=staging
1533
+ PRIVATE_KEY=…
1534
+ STAGING_SDK_API_KEYS_ADMIN_API_KEY=… # same value as SDK_API_KEYS_ADMIN_API_KEY on the server
1535
+ ```
1536
+
1537
+ Fund `PRIVATE_KEY` on **Base** with a little ETH and USDC (fresh-user tests transfer **0.1 USDC** to each ephemeral EOA). No `STAGING_ZYFAI_API_KEY` required — each run mints a new partner key.
1538
+
1539
+ ```bash
1540
+ npm run test:integration -- send-deposit-wait-credit
1541
+ npm run test:integration -- deposit-reconciliation
1542
+ ```
1543
+
1483
1544
  ### Run tests
1484
1545
 
1485
1546
  ```bash
1486
1547
  npm run test:integration # all integration tests (sequential)
1487
- npm run test:integration -- wallet-v-async-deposit # one file: src/integration/<feature-id>.integration.test.ts
1548
+ npm run test:integration -- deposit-withdraw # one file by feature id
1488
1549
  npm run test:integration -- get-protocols
1550
+ ZYFAI_ENV=staging npm run test:integration -- deposit-withdraw
1489
1551
  npx vitest src/integration/get-protocols.integration.test.ts --fileParallelism=false # watch mode
1490
1552
  ```
1491
1553
 
@@ -1493,7 +1555,9 @@ npx vitest src/integration/get-protocols.integration.test.ts --fileParallelism=f
1493
1555
 
1494
1556
  Tests call `describe.skipIf(!integrationEnvReady())` and skip cleanly when `.env.test` is missing or invalid.
1495
1557
 
1496
- When `executionApiUrl` points at local `zyfai-api` and `NODE_ENV` is not `production`, the SDK skips client-side minimum portfolio checks so small test deposits (e.g. 0.1 USDC) work without topping up 100 USDC on Base.
1558
+ When the execution API is **local** or **staging** and `NODE_ENV` is not `production`, the SDK skips client-side minimum portfolio checks so small test deposits (e.g. 0.1 USDC) work without topping up 100 USDC on Base. Production (`api.zyf.ai`) always enforces real minimums.
1559
+
1560
+ **Release smoke (`deposit-withdraw`)** on Base USDC: **local and staging only** — **0.1 USDC** round-trip (fund the test EOA on Base with ~0.1 USDC plus gas). Staging api must have **`SMOKE_AMOUNTS_ENABLED=true`** in its `.env` (see `zyfai-api/docs/deployment.md`). One withdraw per run. Production does not run fund-spending integration tests.
1497
1561
 
1498
1562
  ### Add a test for a new feature
1499
1563
 
@@ -1502,42 +1566,46 @@ When `executionApiUrl` points at local `zyfai-api` and `NODE_ENV` is not `produc
1502
1566
  3. Add `src/integration/<feature-id>.integration.test.ts`:
1503
1567
 
1504
1568
  ```typescript
1505
- import { describe, expect, it } from "vitest";
1506
- import { LOCAL_EXECUTION_API_BASE_URL } from "../config/endpoints";
1507
- import { integrationEnvReady } from "./utils";
1508
-
1509
- describe.skipIf(!integrationEnvReady())("<feature-id>", { timeout: 180_000 }, () => {
1510
- it("verifies the contract", async () => {
1511
- const { ZyfaiSDK } = await import("../core/ZyfaiSDK");
1512
-
1513
- const sdk = new ZyfaiSDK({
1514
- apiKey: process.env.ZYFAI_API_KEY!,
1515
- executionApiUrl: LOCAL_EXECUTION_API_BASE_URL, // http://localhost:3000
1569
+ import { expect, it } from "vitest";
1570
+ import { ZyfaiSDK } from "../core/ZyfaiSDK";
1571
+ import {
1572
+ describeIntegrationSuite,
1573
+ integrationSdkConfig,
1574
+ logIntegrationEvidence,
1575
+ } from "./utils";
1576
+
1577
+ describeIntegrationSuite(
1578
+ "<feature-id>",
1579
+ { spendProfile: "readonly", timeout: 180_000 },
1580
+ () => {
1581
+ it("verifies the contract", async () => {
1582
+ const sdk = new ZyfaiSDK(integrationSdkConfig());
1583
+ await sdk.connectAccount(process.env.PRIVATE_KEY!, 8453);
1584
+ // public SDK calls + expect(); poll async terminal state when needed
1585
+ logIntegrationEvidence("<feature-id>", { chainId: 8453, /* timings, hashes, addresses */ });
1516
1586
  });
1517
-
1518
- await sdk.connectAccount(process.env.PRIVATE_KEY!, 8453);
1519
- // public SDK calls + expect(); poll async terminal state when needed
1520
- });
1521
- });
1587
+ },
1588
+ );
1522
1589
  ```
1523
1590
 
1524
1591
  Conventions:
1525
1592
 
1526
- - Target local API via `LOCAL_EXECUTION_API_BASE_URL` from `src/config/endpoints.ts` — never production in integration tests.
1593
+ - Use `integrationSdkConfig()` so `ZYFAI_ENV` selects the API stack.
1527
1594
  - Import `ZyfaiSDK` from `../core/ZyfaiSDK` (working tree), not a published npm build.
1528
- - Use only public SDK methods; hardcode chain id and amounts per test file.
1529
- - Set `{ timeout: 180_000 }` on `describe` for async flows (deposits, handover, polling).
1595
+ - Use only public SDK methods; hardcode chain id and amounts that apply only to this feature in the test file; put reusable helpers in `./utils`.
1596
+ - Set `{ timeout: 180_000 }` (or higher for deposit/withdraw) on `describe` for async flows.
1597
+ - At the end of each passing test, call `logIntegrationEvidence("<feature-id>", { chainId, userAddress, tx hashes, timings, … })` from `./utils`. It prints one JSON line (including a `links` map: execution API, Basescan/Etherscan/Arbiscan tx and address URLs) plus a short `[integration] … links` block for copy-paste.
1530
1598
 
1531
- See `src/integration/get-protocols.integration.test.ts` for a minimal example.
1599
+ See `src/integration/get-protocols.integration.test.ts` for a minimal example and `deposit-withdraw.integration.test.ts` for persistent-wallet release smoke.
1532
1600
 
1533
1601
  ### Cross-repo features
1534
1602
 
1535
- When a feature spans `zyfai-sdk`, `zyfai-api`, and optionally `predeployment-service`, follow the workspace skill **[functional-feature-verification](../.cursor/skills/functional-feature-verification/SKILL.md)** in the `zyfai-workspace` parent. It covers verification contracts, temporary diagnostics, local stack readiness, and the evidence report template.
1603
+ When a feature spans `zyfai-sdk`, `zyfai-api`, and optionally `predeployment-service`, follow the workspace skill **[functional-feature-verification](../.cursor/skills/functional-feature-verification/SKILL.md)** for **local** proof on working heads. For **staging/prod** release smoke, use **[backend-smoke](../.cursor/skills/backend-smoke/SKILL.md)**.
1536
1604
 
1537
1605
  | Command | What it runs |
1538
1606
  | --- | --- |
1539
1607
  | `npm run check` | typecheck + unit tests + build (every PR) |
1540
- | `npm run test:integration` | opt-in tests against local stack (`--fileParallelism=false`) |
1608
+ | `npm run test:integration` | opt-in tests (`--fileParallelism=false`; `ZYFAI_ENV` selects API) |
1541
1609
 
1542
1610
  ## Contributing
1543
1611