@zyfai/sdk 0.2.56 → 0.2.57

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
@@ -25,6 +25,28 @@ yarn add @zyfai/sdk viem
25
25
  pnpm add @zyfai/sdk viem
26
26
  ```
27
27
 
28
+ ## Releasing
29
+
30
+ This package uses [Changesets](https://github.com/changesets/changesets) for versioning and changelogs. Maintainer details: [`docs/RELEASING.md`](docs/RELEASING.md).
31
+
32
+ ### Adding a changeset
33
+
34
+ When your PR includes user-facing SDK changes:
35
+
36
+ ```bash
37
+ npm run changeset
38
+ ```
39
+
40
+ - **patch** — bug fixes
41
+ - **minor** — new features (non-breaking)
42
+ - **major** — breaking changes
43
+
44
+ Commit the generated file in `.changeset/` with your PR.
45
+
46
+ ### Publishing (maintainers)
47
+
48
+ After changesets merge to `main`, a maintainer runs `npm run version-packages`, then `npm publish`. Details: [`docs/RELEASING.md`](docs/RELEASING.md).
49
+
28
50
  ## Prerequisites
29
51
 
30
52
  1. **API Key**: Single API key for both Execution API (Safe deployment, transactions, session keys) and Data API (earnings, opportunities, analytics)
@@ -115,6 +137,13 @@ This method:
115
137
  > Net effect: onboarding a predeployed wallet takes a **single signature — the
116
138
  > USDC deposit** (no wallet-deploy or session-key signatures).
117
139
  >
140
+ > **Registering the deposit (do not skip).** For pool wallets, an on-chain
141
+ > ERC-20 transfer alone does **not** subscribe the user. The backend must also
142
+ > receive `POST /users/log_deposit` with a **user JWT** (`Authorization: Bearer
143
+ > …`) from SIWE — your SDK API key is not enough (that call returns **401**).
144
+ > Without a successful `log_deposit`, ownership is not rotated, the session key
145
+ > is not activated, and funds sit idle in the Safe.
146
+ >
118
147
  > The pool's ERC-7579 module addresses are exported as reference constants
119
148
  > (`POOL_MODULE_ADDRESSES`, `INTENT_SMART_SESSIONS`, `PROXY_EXECUTOR`, …) for
120
149
  > parity/validation only — the SDK does not install them.
@@ -150,6 +179,7 @@ if (result.success) {
150
179
 
151
180
  - `"conservative"` (default): Low-risk, stable yield strategy
152
181
  - `"aggressive"`: High-risk, high-reward strategy
182
+ - `"yieldmaxxing"`: Aggressive plus protocols with delayed withdrawals — see [Strategies](#strategies)
153
183
 
154
184
  ### 2. Multi-Chain Support
155
185
 
@@ -306,6 +336,7 @@ Deploy a Safe smart wallet for a user. **Deployment is handled by the backend AP
306
336
  - `strategy`: Optional strategy selection (default: `"conservative"`)
307
337
  - `"conservative"`: Low-risk, stable yield strategy (default)
308
338
  - `"aggressive"`: High-risk, high-reward strategy
339
+ - `"yieldmaxxing"`: Aggressive plus protocols with delayed withdrawals — see [Strategies](#strategies)
309
340
 
310
341
  **Returns:**
311
342
 
@@ -422,21 +453,42 @@ if (result.success) {
422
453
  - Amount must be in least decimal units. For USDC (6 decimals): 1 USDC = 1000000
423
454
  - `asset` is required (`"USDC"`, `"WETH"`, or `"EURC"` — EURC on Mainnet/Base only); token address is selected from that for the chain
424
455
  - The total Safe balance must meet the per-asset minimum after the deposit (see above). WETH uses a live ETH/USD price, so the wei threshold moves with the market.
425
- - The SDK automatically authenticates via SIWE before logging the deposit with Zyfai's API, so no extra steps are required on your end once the transfer confirms
426
- - **First deposit only** (before transfer + `log_deposit`): if the USDC profile has no `chains` yet, the SDK patches protocols for **USDC, WETH, and EURC** across all supported chains (EURC on Mainnet/Base only → `assetTypeSettings.[usdc|eth|eurc]`). Pass optional `strategy` (`"conservative"` default or `"aggressive"`) — same role as the former `deploySafe` strategy argument. Later deposits skip this.
456
+ - Call `connectAccount()` on the **same** `ZyfaiSDK` instance before `depositFunds()`. The method uses that session's JWT when it calls `log_deposit` after the transfer.
457
+ - If first-deposit protocol patching fails, the transfer still runs but `log_deposit` may run **without** a JWT (401). Treat a confirmed on-chain tx as **not** subscribed until `log_deposit` succeeds.
458
+ - **`depositFunds` can return `success: true` even when `log_deposit` failed** — failures are only `console.warn`ed. Check logs or retry `logDeposit` after `connectAccount()`.
459
+ - **First deposit only** (before transfer + `log_deposit`): if the USDC profile has no `chains` yet, the SDK patches protocols for **USDC, WETH, and EURC** across all supported chains (EURC on Mainnet/Base only → `assetTypeSettings.[usdc|eth|eurc]`). Pass optional `strategy` (`"conservative"` default, `"aggressive"` or `"yieldmaxxing"`) — same role as the former `deploySafe` strategy argument. Later deposits skip this.
460
+ - **`strategy` is ignored on later deposits, and no error is raised.** Re-running the patch would overwrite a protocol selection the user may have customised, so passing `"yieldmaxxing"` to an account that has already deposited leaves it on its current strategy. To change an existing account, call `updateUserProfile({ asset, strategy })` for each asset concerned:
461
+
462
+ ```typescript
463
+ await sdk.updateUserProfile({ asset: "USDC", strategy: "yieldmaxxing" });
464
+ ```
427
465
 
428
466
  #### Log External Deposit (For Sponsored Transactions)
429
467
 
430
468
  `depositFunds()` already calls `logDeposit` after the transfer. If you **do not** use `depositFunds()` and send the ERC20 yourself (front, Privy, Biconomy, custom wallet), you **must** call `logDeposit` — otherwise the backend never sees the deposit: a reserved pool wallet stays reserved (no ownership rotation), and yield/agent tracking does not start.
431
469
 
470
+ **Authentication (required).** `log_deposit` is a **user** endpoint. You need both:
471
+
472
+ | Credential | Purpose |
473
+ | ---------- | ------- |
474
+ | `X-API-Key` | Identifies your SDK integration (set when constructing `ZyfaiSDK`) |
475
+ | `Authorization: Bearer <jwt>` | Proves which user deposited (from `connectAccount()` → SIWE) |
476
+
477
+ Calling `logDeposit()` **without** `connectAccount()` on the **same** SDK instance sends only the API key → **401 Unauthorized**. A common mistake is SIWE in the browser and `logDeposit()` on a **new** server-side `ZyfaiSDK` with no JWT.
478
+
432
479
  ```typescript
433
- // 1. Execute deposit with your own wallet implementation (e.g., Privy)
480
+ const sdk = new ZyfaiSDK({ apiKey: process.env.ZYFAI_API_KEY! });
481
+
482
+ // Required before logDeposit — same instance that will post log_deposit
483
+ await sdk.connectAccount(walletProviderOrPrivateKey, chainId);
484
+
485
+ // 1. Execute deposit with your own wallet implementation (e.g., Privy, Bankr)
434
486
  const txHash = await privyWallet.sendTransaction({
435
487
  to: safeAddress,
436
488
  data: transferData, // ERC20 transfer encoded data
437
489
  });
438
490
 
439
- // 2. Log the deposit to Zyfai backend for tracking and yield optimization
491
+ // 2. Register the deposit (must return success — do not treat tx confirmation alone as "subscribed")
440
492
  const result = await sdk.logDeposit(
441
493
  8453, // chainId
442
494
  txHash, // transaction hash from your wallet
@@ -456,6 +508,10 @@ if (result.success) {
456
508
  - You need more control over transaction execution
457
509
  - You want to pay gas fees for your users
458
510
 
511
+ **When to prefer `depositFunds()` instead:** one SDK instance, `connectAccount()` once, transfer + `log_deposit` in one call — fewer ways to miss the JWT.
512
+
513
+ **Serverless / split frontend–backend:** if the browser calls `connectAccount()` but the server calls `logDeposit()`, the server must either (a) run `connectAccount()` itself with the user's signer, or (b) forward the JWT to the same `ZyfaiSDK` instance that posts `log_deposit`. API key alone is not sufficient.
514
+
459
515
  **Parameters:**
460
516
 
461
517
  - `chainId`: Chain ID where the deposit was made
@@ -498,6 +554,36 @@ if (result.success) {
498
554
  - Check the `message` field for the withdrawal status
499
555
  - Use `getHistory()` to track the withdrawal transaction once it's processed
500
556
 
557
+ **Delayed withdrawals (`yieldmaxxing` strategy)**
558
+
559
+ Positions held in protocols with asynchronous withdrawals (Ipor, Superform)
560
+ cannot be exited on demand. For those the backend sends the immediately
561
+ available portion straight away, then queues a redemption for the rest and
562
+ forwards the funds to the EOA once the protocol releases them — roughly a day
563
+ on Ipor, three on Superform.
564
+
565
+ The user has nothing else to call, but `withdrawFunds` returns as soon as the
566
+ immediate portion is sent, so its `txHash` does not cover the whole amount.
567
+ Track the remainder through `getPortfolio`:
568
+
569
+ ```typescript
570
+ await sdk.withdrawFunds(userAddress, 8453);
571
+
572
+ const { portfolio } = await sdk.getPortfolio(userAddress);
573
+ portfolio.pendingAsyncWithdrawals
574
+ ?.filter((w) => w.status === "REQUESTED" || w.status === "CLAIMABLE")
575
+ .forEach((w) => {
576
+ console.log(`${w.amount} ${w.token?.symbol} from ${w.protocol?.name}`);
577
+ console.log(`Expected to be claimable around ${w.estimatedClaimAt}`);
578
+ });
579
+ ```
580
+
581
+ Once requested, that amount can no longer be withdrawn: it is gone from both
582
+ the position snapshot and the Safe balance, so a second `withdrawFunds` call
583
+ silently returns only what is left. It is also missing from
584
+ `portfolioByAssetType` while in flight, so validate user-entered amounts
585
+ against that field rather than the total — see [Total balance](#total-balance).
586
+
501
587
  ### 6. Get Available Protocols
502
588
 
503
589
  Retrieve all available DeFi protocols and pools for a specific chain:
@@ -562,6 +648,86 @@ portfolio.positions?.forEach((slot) => {
562
648
  **Note**: Portfolio balances are live; earnings used for the fee may come from a
563
649
  snapshot, so net values can differ slightly from a fully live calculation.
564
650
 
651
+ #### Total balance
652
+
653
+ `portfolioByAssetType` is **not** the user's total balance. The backend builds
654
+ it from exactly two sources: the underlying amount of every deployed position,
655
+ and the idle balances sitting in the Safe. Anything that is in neither place is
656
+ missing from it.
657
+
658
+ That gap is real under the `yieldmaxxing` strategy. When the agent requests a
659
+ redemption from a delayed-withdrawal protocol, the position leaves the snapshot
660
+ immediately while the funds stay in the vault for a day or three. During that
661
+ window they are in no balance field — only in `pendingAsyncWithdrawals`.
662
+
663
+ So you need **two different numbers**, and showing one where the other belongs
664
+ is the most common mistake:
665
+
666
+ | Number | Formula | Use it for |
667
+ | --- | --- | --- |
668
+ | **Total balance** | `portfolioByAssetType` + in-flight | "You have X" — the user still owns the in-flight funds |
669
+ | **Requestable** | `portfolioByAssetType` only | Any withdraw form, max button, or amount validation |
670
+
671
+ An in-flight amount is **no longer withdrawable**. A `withdrawFunds` call only
672
+ reaches positions in the current snapshot and idle Safe balances, and the
673
+ in-flight amount is in neither — calling it again will not pull those funds out
674
+ any faster, nor will it fail with an error. They land on the user's EOA on
675
+ their own once the protocol releases them, so the right UI is to show them as
676
+ pending with their `estimatedClaimAt`, never to offer them for withdrawal.
677
+
678
+ Note the `?? "0x0"` below: when every position of an asset is in flight, the
679
+ backend drops the asset key from `portfolioByAssetType` altogether rather than
680
+ reporting a zero balance, and `portfolioByAssetType` itself can be `{}`.
681
+ `amount` is hex-encoded least units like every other balance, so read it with
682
+ `BigInt`, never `parseInt`.
683
+
684
+ ```typescript
685
+ const { portfolio } = await sdk.getPortfolio(userAddress);
686
+
687
+ const IN_FLIGHT = ["REQUESTED", "CLAIMABLE"];
688
+
689
+ const balancesFor = (assetType: string, tokenSymbol: string) => {
690
+ // Everything a withdrawal can still act on.
691
+ const requestable = BigInt(
692
+ portfolio.portfolioByAssetType?.[assetType]?.balance ?? "0x0"
693
+ );
694
+
695
+ // Owned, but locked in a redemption until the protocol releases it.
696
+ const inFlight = (portfolio.pendingAsyncWithdrawals ?? [])
697
+ .filter((w) => IN_FLIGHT.includes(w.status) && w.token?.symbol === tokenSymbol)
698
+ .reduce((sum, w) => sum + BigInt(w.amount), 0n);
699
+
700
+ return { requestable, inFlight, total: requestable + inFlight };
701
+ };
702
+ ```
703
+
704
+ `requestable` is what a withdrawal can still be asked on, **not** what arrives
705
+ immediately: it also covers async positions the user currently holds, and
706
+ withdrawing those turns them into a new in-flight redemption. Cap the amount a
707
+ user can enter at `requestable`, never at `total` — asking for more does not
708
+ fail loudly, the backend transfers what it can right away and queues a
709
+ redemption for the shortfall.
710
+
711
+ Two ways to get this wrong:
712
+
713
+ - **Do not add `staleBalances`.** They are the same idle Safe balances that
714
+ `portfolioByAssetType` already counts, exposed as a per-chain view for
715
+ surfacing funds waiting to be deployed. Adding them double-counts.
716
+ - **Do not add every `pendingAsyncWithdrawals` entry.** The array also keeps
717
+ `CLAIMED` requests for 24 hours so you can show a recent history. Those funds
718
+ are already back in the Safe and therefore already counted. Filter on
719
+ `REQUESTED` and `CLAIMABLE`.
720
+
721
+ Each in-flight entry carries the information needed to show progress:
722
+ `status`, `amount` (in the token's least units — apply `token.decimals`),
723
+ `protocol.name`, `pool`, `estimatedClaimAt`, and `statusMessage` when the
724
+ protocol is temporarily refusing claims. A `FAILED` status is not a loss: the
725
+ position is restored and the request is retried on the next cycle.
726
+
727
+ `pauseMessageByToken` is a companion field holding user-facing copy when
728
+ deposits are paused for a token (tokenized stocks over the weekend, for
729
+ example), keyed by token symbol.
730
+
565
731
  ### 8. Analytics & Data Endpoints
566
732
 
567
733
  The SDK provides access to various analytics and data endpoints:
@@ -576,7 +742,7 @@ const user = await sdk.getUserDetails();
576
742
  console.log("Smart Wallet:", user.user.smartWallet);
577
743
  console.log("Active Chains:", user.user.chains);
578
744
  console.log("Active Protocols:", user.user.protocols);
579
- console.log("Strategy:", user.user.strategy); // "conservative" | "aggressive"
745
+ console.log("Strategy:", user.user.strategy); // "conservative" | "aggressive" | "yieldmaxxing"
580
746
  console.log("Has Active Session:", user.user.hasActiveSessionKey);
581
747
 
582
748
  // Feature flags
@@ -597,7 +763,7 @@ console.log("Wallet Type:", user.user.walletType);
597
763
 
598
764
  **Available Fields:**
599
765
  - **Core Info**: `id`, `address`, `smartWallet`, `chains`, `protocols`
600
- - **Strategy**: `strategy` (conservative or aggressive)
766
+ - **Strategy**: `strategy` (conservative, aggressive or yieldmaxxing)
601
767
  - **Session**: `hasActiveSessionKey` (boolean)
602
768
  - **Features**: `autocompounding`, `autoSelectProtocols`, `omniAccount`, `crosschainStrategy`, `executorProxy`, `splitting`, `minSplits`
603
769
  - **Optional**: `email`, `telegramId`, `agentName`, `walletType`, `customization`, `registered`
@@ -845,6 +1011,34 @@ aggressiveOpps.data.forEach((o) => {
845
1011
  });
846
1012
  ```
847
1013
 
1014
+ #### Get Yieldmaxxing Opportunities (Delayed Withdrawals)
1015
+
1016
+ ```typescript
1017
+ const asyncOpps = await sdk.getAsyncOpportunities(8453);
1018
+ asyncOpps.data.forEach((o) => {
1019
+ console.log(`${o.protocolName} - ${o.poolName}: ${o.apy}% APY`);
1020
+ });
1021
+ ```
1022
+
1023
+ #### Strategies
1024
+
1025
+ Every method that takes a `strategy` accepts one of three values. Each tier is a
1026
+ superset of the previous one: an aggressive user also gets conservative pools,
1027
+ and a yieldmaxxing user gets everything.
1028
+
1029
+ | Strategy | Backend value | Pools unlocked |
1030
+ | --- | --- | --- |
1031
+ | `conservative` (default) | `safe_strategy` | Low-risk pools only |
1032
+ | `aggressive` | `degen_strategy` | Conservative + higher-risk pools |
1033
+ | `yieldmaxxing` | `async_strategy` | Aggressive + pools with **delayed withdrawals** |
1034
+
1035
+ `yieldmaxxing` is the only strategy that changes how withdrawals behave. It
1036
+ unlocks protocols (Ipor, Superform) that cannot be exited on demand: a
1037
+ redemption has to be requested, then claimed once the protocol releases the
1038
+ funds — roughly a day on Ipor, three on Superform. The agent handles both steps,
1039
+ but the funds are in flight in between. See
1040
+ [Withdraw Funds](#5-withdraw-funds) and [Total balance](#total-balance).
1041
+
848
1042
  ### 11. APY Per Strategy
849
1043
 
850
1044
  #### Get APY Per Strategy
@@ -1148,10 +1342,88 @@ If `withdrawFunds` returns without a `txHash`, the withdrawal is being processed
1148
1342
 
1149
1343
  Some Data API endpoints may require server-side CORS configuration. If you see CORS errors for endpoints like `onchain-earnings`, `calculate-onchain-earnings`, or `opportunities`, contact Zyfai support to ensure your origin is whitelisted.
1150
1344
 
1345
+ ## Integration testing
1346
+
1347
+ 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.
1348
+
1349
+ 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.
1350
+
1351
+ ### Setup
1352
+
1353
+ ```bash
1354
+ cd zyfai-sdk
1355
+ cp .env.test.example .env.test # once — fill ZYFAI_API_KEY and PRIVATE_KEY (gitignored)
1356
+ ```
1357
+
1358
+ Vitest loads `.env.test` automatically (`vitest.config.ts`). Start the local API from the workspace parent:
1359
+
1360
+ ```bash
1361
+ cd .. # zyfai-workspace root
1362
+ pnpm dev
1363
+ ```
1364
+
1365
+ ### Run tests
1366
+
1367
+ ```bash
1368
+ npm run test:integration # all integration tests
1369
+ npm run test:integration -- get-protocols # one file by name
1370
+ npm run test:integration -- src/integration/get-protocols.integration.test.ts
1371
+ npm run test:integration -- -t "returns a protocol list" # by test/describe name
1372
+ npx vitest get-protocols # watch mode while iterating
1373
+ ```
1374
+
1375
+ Tests call `describe.skipIf(!integrationEnvReady())` and skip cleanly when `.env.test` is missing or invalid.
1376
+
1377
+ ### Add a test for a new feature
1378
+
1379
+ 1. Implement the API change in `zyfai-api` and expose it via a public SDK method (if new surface).
1380
+ 2. Add `examples/<feature>.ts` for manual smoke.
1381
+ 3. Add `src/integration/<feature-id>.integration.test.ts`:
1382
+
1383
+ ```typescript
1384
+ import { describe, expect, it } from "vitest";
1385
+ import { LOCAL_EXECUTION_API_BASE_URL } from "../config/endpoints";
1386
+ import { integrationEnvReady } from "./utils";
1387
+
1388
+ describe.skipIf(!integrationEnvReady())("<feature-id>", { timeout: 180_000 }, () => {
1389
+ it("verifies the contract", async () => {
1390
+ const { ZyfaiSDK } = await import("../core/ZyfaiSDK");
1391
+
1392
+ const sdk = new ZyfaiSDK({
1393
+ apiKey: process.env.ZYFAI_API_KEY!,
1394
+ executionApiUrl: LOCAL_EXECUTION_API_BASE_URL, // http://localhost:3000
1395
+ });
1396
+
1397
+ await sdk.connectAccount(process.env.PRIVATE_KEY!, 8453);
1398
+ // public SDK calls + expect(); poll async terminal state when needed
1399
+ });
1400
+ });
1401
+ ```
1402
+
1403
+ Conventions:
1404
+
1405
+ - Target local API via `LOCAL_EXECUTION_API_BASE_URL` from `src/config/endpoints.ts` — never production in integration tests.
1406
+ - Import `ZyfaiSDK` from `../core/ZyfaiSDK` (working tree), not a published npm build.
1407
+ - Use only public SDK methods; hardcode chain id and amounts per test file.
1408
+ - Set `{ timeout: 180_000 }` on `describe` for async flows (deposits, handover, polling).
1409
+
1410
+ See `src/integration/get-protocols.integration.test.ts` for a minimal example.
1411
+
1412
+ ### Cross-repo features
1413
+
1414
+ 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.
1415
+
1416
+ | Command | What it runs |
1417
+ | --- | --- |
1418
+ | `npm run check` | typecheck + unit tests + build (every PR) |
1419
+ | `npm run test:integration` | opt-in tests against local stack (feature work) |
1420
+
1151
1421
  ## Contributing
1152
1422
 
1153
1423
  Contributions are welcome! Please open an issue or submit a pull request.
1154
1424
 
1425
+ PRs with user-facing SDK changes need a [changeset](docs/RELEASING.md) (`npm run changeset`).
1426
+
1155
1427
  ## License
1156
1428
 
1157
1429
  MIT