@zyfai/sdk 0.2.56 → 0.3.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 +426 -33
- package/dist/index.d.mts +367 -65
- package/dist/index.d.ts +367 -65
- package/dist/index.js +900 -260
- package/dist/index.mjs +885 -260
- package/package.json +13 -4
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
|
|
|
@@ -295,7 +325,7 @@ Get the Smart Wallet (Safe) address for a user.
|
|
|
295
325
|
|
|
296
326
|
##### `deploySafe(userAddress: string, chainId: SupportedChainId, strategy?: Strategy): Promise<DeploySafeResponse>`
|
|
297
327
|
|
|
298
|
-
> **Deprecated** for partner integrations. Prefer `
|
|
328
|
+
> **Deprecated** for partner integrations. Prefer `sendDeposit()` — predeployed Safes and session keys are handled on first deposit. This method remains available for legacy flows and emits a console warning when called.
|
|
299
329
|
|
|
300
330
|
Deploy a Safe smart wallet for a user. **Deployment is handled by the backend API**, which manages all RPC calls and bundler interactions. This avoids rate limiting issues.
|
|
301
331
|
|
|
@@ -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
|
|
|
@@ -322,7 +353,7 @@ Deploy a Safe smart wallet for a user. **Deployment is handled by the backend AP
|
|
|
322
353
|
|
|
323
354
|
- User must be authenticated (automatically done via `connectAccount()`)
|
|
324
355
|
- Backend handles all RPC calls, avoiding rate limiting
|
|
325
|
-
- Protocol / asset patching runs in `deploySafe` (all paths). `
|
|
356
|
+
- Protocol / asset patching runs in `deploySafe` (all paths). `sendDeposit` still patches on the account's **first** deposit if USDC `chains` are empty (see Send a Deposit below)
|
|
326
357
|
|
|
327
358
|
##### `addWalletToSdk(walletAddress: string): Promise<AddWalletToSdkResponse>`
|
|
328
359
|
|
|
@@ -349,7 +380,7 @@ Session keys enable delegated transaction execution without exposing the main pr
|
|
|
349
380
|
|
|
350
381
|
#### Simple Usage (Legacy — deprecated)
|
|
351
382
|
|
|
352
|
-
> **Deprecated** for partner integrations. Prefer `
|
|
383
|
+
> **Deprecated** for partner integrations. Prefer `sendDeposit()` — predeployed wallets already have the agent session enabled. This method remains available for legacy flows and emits a console warning when called.
|
|
353
384
|
|
|
354
385
|
The SDK automatically fetches optimal session configuration from Zyfai API:
|
|
355
386
|
|
|
@@ -380,82 +411,136 @@ console.log("User ID:", result.userId);
|
|
|
380
411
|
- User must be authenticated (automatically done via `connectAccount()`)
|
|
381
412
|
- The SDK proactively checks if the user already has an active session key and returns early without requiring any signature if one exists
|
|
382
413
|
- The user record must have `smartWallet` and `chainId` set (predeployed assignment / first deposit)
|
|
383
|
-
- Protocol selection is **not** touched by `createSessionKey` — it's set by `deploySafe` and on the first `
|
|
384
|
-
- **Deprecated**: prefer `
|
|
414
|
+
- Protocol selection is **not** touched by `createSessionKey` — it's set by `deploySafe` and on the first `sendDeposit` call if USDC `chains` are still empty
|
|
415
|
+
- **Deprecated**: prefer `sendDeposit()` for partner onboarding; `createSessionKey` remains for legacy flows
|
|
385
416
|
- When `alreadyActive` is `true`, `sessionKeyAddress` and `signature` are not available in the response
|
|
386
417
|
|
|
387
|
-
### 4. Deposit
|
|
418
|
+
### 4. Send a Deposit
|
|
388
419
|
|
|
389
420
|
Transfer tokens to your Safe smart wallet. Token address is automatically selected based on chain and the requested asset (defaults to USDC):
|
|
390
421
|
|
|
391
422
|
- **Ethereum Mainnet (1), Base (8453), Arbitrum (42161)**: USDC (default) or WETH
|
|
392
423
|
- **Ethereum Mainnet (1), Base (8453)**: EURC (6 decimals; not available on Arbitrum)
|
|
424
|
+
- **Base (8453) only**: NVDAc (8 decimals) — tokenized NVIDIA equity, see [Tokenized equities](#tokenized-equities-nvdac)
|
|
393
425
|
|
|
394
426
|
**Minimum portfolio balance (enforced on Safe balance + deposit amount):**
|
|
395
427
|
|
|
396
428
|
- Ethereum Mainnet (1) / USDC or EURC: 10,000 units
|
|
397
429
|
- Base (8453) and Arbitrum (42161) / USDC or EURC: 100 units
|
|
398
|
-
- WETH: about **$10,000** of ETH on Ethereum Mainnet, **$100** on Base and Arbitrum
|
|
430
|
+
- WETH: about **$10,000** of ETH on Ethereum Mainnet, **$100** on Base and Arbitrum
|
|
431
|
+
- NVDAc: about **$100** on Base
|
|
432
|
+
|
|
433
|
+
Minimums for WETH and NVDAc are quoted in dollars and converted at deposit time from the live USD price (Data API `GET /api/v2/price?token=eth` and `?token=nvdac`, same API key as the SDK), so the on-chain threshold moves with the market.
|
|
399
434
|
|
|
400
435
|
Top-ups smaller than the minimum are allowed if the Safe already holds enough of the asset to meet it after the deposit.
|
|
401
436
|
|
|
402
437
|
```typescript
|
|
403
|
-
//
|
|
404
|
-
const
|
|
438
|
+
// Send 10 USDC (6 decimals) to Safe on Base.
|
|
439
|
+
const sent = await sdk.sendDeposit(
|
|
405
440
|
userAddress,
|
|
406
441
|
8453, // Chain ID
|
|
407
442
|
"10000000", // Amount: 10 USDC = 10 * 10^6
|
|
408
443
|
"USDC"
|
|
409
444
|
);
|
|
410
445
|
|
|
446
|
+
// Await custody credit only when this UI needs the completion state.
|
|
447
|
+
const credited = await sdk.waitForDepositCredit(sent.registration.id, 8453);
|
|
448
|
+
|
|
411
449
|
// First deposit with aggressive strategy (protocol patching)
|
|
412
|
-
await sdk.
|
|
450
|
+
const aggressiveSent = await sdk.sendDeposit(
|
|
451
|
+
userAddress,
|
|
452
|
+
8453,
|
|
453
|
+
"10000000",
|
|
454
|
+
"USDC",
|
|
455
|
+
"aggressive",
|
|
456
|
+
);
|
|
457
|
+
await sdk.waitForDepositCredit(aggressiveSent.registration.id, 8453);
|
|
413
458
|
|
|
414
|
-
if (
|
|
415
|
-
console.log("Deposit
|
|
416
|
-
console.log("Transaction Hash:",
|
|
459
|
+
if (credited.status === "credited") {
|
|
460
|
+
console.log("Deposit credited!");
|
|
461
|
+
console.log("Transaction Hash:", sent.txHash);
|
|
417
462
|
}
|
|
418
463
|
```
|
|
419
464
|
|
|
420
465
|
**Note:**
|
|
421
466
|
|
|
422
467
|
- Amount must be in least decimal units. For USDC (6 decimals): 1 USDC = 1000000
|
|
423
|
-
- `asset` is required (`"USDC"`, `"WETH"`, or `"
|
|
468
|
+
- `asset` is required (`"USDC"`, `"WETH"`, `"EURC"`, or `"NVDAc"` — EURC on Mainnet/Base only, NVDAc on Base only); token address is selected from that for the chain. Depositing an asset on a chain where it does not exist throws before any transfer.
|
|
424
469
|
- 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
|
-
-
|
|
426
|
-
-
|
|
470
|
+
- Call `connectAccount()` on the **same** `ZyfaiSDK` instance before `sendDeposit()`. The method uses that session's JWT when it calls `log_deposit` after the transfer.
|
|
471
|
+
- `sendDeposit()` confirms the ERC-20 transaction and registers its lifecycle, then returns its ID. Call `waitForDepositCredit()` only when the UI needs to wait for custody credit; otherwise track it later with `getDepositStatus()`.
|
|
472
|
+
- `depositFunds()` remains a compatibility wrapper that calls both steps and waits through the normal completion window; it **rejects** if credit is not confirmed in that window (track in-flight deposits with `getDepositStatus()` or call `waitForDepositCredit()` with a longer `timeoutMs`).
|
|
473
|
+
- If first-deposit protocol patching fails, the transfer still runs. `sendDeposit()` throws if deposit registration is not accepted; retry `logDeposit()` after `connectAccount()`.
|
|
474
|
+
- **First deposit only** (before transfer + `log_deposit`): if the USDC profile has no `chains` yet, the SDK patches protocols for **USDC, WETH, EURC, and NVDAc**, each across the chains it exists on (EURC on Mainnet/Base, NVDAc on Base → `assetTypeSettings.[usdc|eth|eurc|nvdac]`). Pass optional `strategy` (`"conservative"` default, `"aggressive"` or `"yieldmaxxing"`) — same role as the former `deploySafe` strategy argument. Later deposits skip this.
|
|
475
|
+
- **`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:
|
|
476
|
+
|
|
477
|
+
```typescript
|
|
478
|
+
await sdk.updateUserProfile({ asset: "USDC", strategy: "yieldmaxxing" });
|
|
479
|
+
```
|
|
480
|
+
|
|
481
|
+
#### Deposit With an External Wallet (Sponsored Transactions)
|
|
482
|
+
|
|
483
|
+
`sendDeposit()` already calls `logDeposit` after the transfer. For a new
|
|
484
|
+
sponsored or custom-wallet deposit, compose `ensureFirstDepositSetup()`,
|
|
485
|
+
`buildDepositTransfer()`, and `logDeposit()` yourself. If you have already sent
|
|
486
|
+
a transfer independently, call `logDeposit` to register it — otherwise the
|
|
487
|
+
backend never sees the deposit: a reserved pool wallet stays reserved (no
|
|
488
|
+
ownership rotation), and yield/agent tracking does not start.
|
|
427
489
|
|
|
428
|
-
|
|
490
|
+
**Authentication (required).** `log_deposit` is a **user** endpoint. You need both:
|
|
429
491
|
|
|
430
|
-
|
|
492
|
+
| Credential | Purpose |
|
|
493
|
+
| ---------- | ------- |
|
|
494
|
+
| `X-API-Key` | Identifies your SDK integration (set when constructing `ZyfaiSDK`) |
|
|
495
|
+
| `Authorization: Bearer <jwt>` | Proves which user deposited (from `connectAccount()` → SIWE) |
|
|
496
|
+
|
|
497
|
+
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.
|
|
431
498
|
|
|
432
499
|
```typescript
|
|
433
|
-
|
|
500
|
+
const sdk = new ZyfaiSDK({ apiKey: process.env.ZYFAI_API_KEY! });
|
|
501
|
+
|
|
502
|
+
// Required before the deposit — same instance that will post log_deposit
|
|
503
|
+
await sdk.connectAccount(walletProviderOrPrivateKey, chainId);
|
|
504
|
+
|
|
505
|
+
await sdk.ensureFirstDepositSetup("conservative");
|
|
506
|
+
const intent = await sdk.buildDepositTransfer({
|
|
507
|
+
userAddress,
|
|
508
|
+
chainId: 8453,
|
|
509
|
+
amount: "100000000",
|
|
510
|
+
asset: "USDC",
|
|
511
|
+
});
|
|
434
512
|
const txHash = await privyWallet.sendTransaction({
|
|
435
|
-
to:
|
|
436
|
-
data:
|
|
513
|
+
to: intent.to,
|
|
514
|
+
data: intent.data,
|
|
437
515
|
});
|
|
438
516
|
|
|
439
|
-
//
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
517
|
+
// Confirm the external transaction before registering it.
|
|
518
|
+
await publicClient.waitForTransactionReceipt({ hash: txHash });
|
|
519
|
+
const { deposit } = await sdk.logDeposit(
|
|
520
|
+
8453,
|
|
521
|
+
txHash,
|
|
522
|
+
"100000000",
|
|
523
|
+
intent.tokenAddress,
|
|
444
524
|
);
|
|
525
|
+
await sdk.waitForDepositCredit(deposit.id, 8453);
|
|
445
526
|
|
|
446
|
-
|
|
447
|
-
console.log("Deposit logged successfully");
|
|
448
|
-
}
|
|
527
|
+
console.log("Deposit credited:", deposit.id);
|
|
449
528
|
```
|
|
450
529
|
|
|
530
|
+
See the external deposit building-block API reference for full signatures.
|
|
531
|
+
|
|
451
532
|
**When to use `logDeposit`:**
|
|
452
533
|
|
|
453
|
-
- You did **not** call `
|
|
534
|
+
- You did **not** call `sendDeposit()` (it already logs the deposit for you)
|
|
454
535
|
- You use sponsored/gasless transactions (Privy, Biconomy, Gelato, etc.)
|
|
455
536
|
- You have a custom wallet / frontend transfer
|
|
456
537
|
- You need more control over transaction execution
|
|
457
538
|
- You want to pay gas fees for your users
|
|
458
539
|
|
|
540
|
+
`depositFunds()` retains its complete credit-waiting flow for existing integrations and still rejects on timeout so a resolved promise means credited balance.
|
|
541
|
+
|
|
542
|
+
**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.
|
|
543
|
+
|
|
459
544
|
**Parameters:**
|
|
460
545
|
|
|
461
546
|
- `chainId`: Chain ID where the deposit was made
|
|
@@ -498,6 +583,62 @@ if (result.success) {
|
|
|
498
583
|
- Check the `message` field for the withdrawal status
|
|
499
584
|
- Use `getHistory()` to track the withdrawal transaction once it's processed
|
|
500
585
|
|
|
586
|
+
**Delayed withdrawals (`yieldmaxxing` strategy)**
|
|
587
|
+
|
|
588
|
+
Positions held in protocols with asynchronous withdrawals (Ipor, Superform)
|
|
589
|
+
cannot be exited on demand. For those the backend sends the immediately
|
|
590
|
+
available portion straight away, then queues a redemption for the rest and
|
|
591
|
+
forwards the funds to the EOA once the protocol releases them — roughly a day
|
|
592
|
+
on Ipor, three on Superform.
|
|
593
|
+
|
|
594
|
+
The user has nothing else to call, but `withdrawFunds` returns as soon as the
|
|
595
|
+
immediate portion is sent, so its `txHash` does not cover the whole amount.
|
|
596
|
+
Track the remainder through `getPortfolio`:
|
|
597
|
+
|
|
598
|
+
```typescript
|
|
599
|
+
await sdk.withdrawFunds(userAddress, 8453);
|
|
600
|
+
|
|
601
|
+
const { portfolio } = await sdk.getPortfolio(userAddress);
|
|
602
|
+
portfolio.pendingAsyncWithdrawals
|
|
603
|
+
?.filter((w) => w.status === "REQUESTED" || w.status === "CLAIMABLE")
|
|
604
|
+
.forEach((w) => {
|
|
605
|
+
console.log(`${w.amount} ${w.token?.symbol} from ${w.protocol?.name}`);
|
|
606
|
+
console.log(`Expected to be claimable around ${w.estimatedClaimAt}`);
|
|
607
|
+
});
|
|
608
|
+
```
|
|
609
|
+
|
|
610
|
+
Once requested, that amount can no longer be withdrawn: it is gone from both
|
|
611
|
+
the position snapshot and the Safe balance, so a second `withdrawFunds` call
|
|
612
|
+
silently returns only what is left. It is also missing from
|
|
613
|
+
`portfolioByAssetType` while in flight, so validate user-entered amounts
|
|
614
|
+
against that field rather than the total — see [Total balance](#total-balance).
|
|
615
|
+
|
|
616
|
+
**Only one redemption per pool can be in flight.** While an entry for a pool is
|
|
617
|
+
`REQUESTED` or `CLAIMABLE`, the backend drops a further withdrawal aimed at that
|
|
618
|
+
same pool, because the protocols behind it (ERC-7540) hold a single request slot
|
|
619
|
+
per user — and it still answers `success: true`. `withdrawFunds` therefore
|
|
620
|
+
throws rather than returning that no-op:
|
|
621
|
+
|
|
622
|
+
```
|
|
623
|
+
Withdrawal failed: A redemption is already in flight for NVDAc on NVDAC
|
|
624
|
+
(status REQUESTED), and async pools allow only one at a time. Wait for it to
|
|
625
|
+
reach CLAIMED before withdrawing the rest. Estimated settlement: 2026-09-24T13:59:05.543Z.
|
|
626
|
+
```
|
|
627
|
+
|
|
628
|
+
It only throws when nothing the call could reach is withdrawable. Another pool,
|
|
629
|
+
another asset or an idle Safe balance still goes through, partially. To grey out
|
|
630
|
+
the action before the user tries, read `pendingAsyncWithdrawals`:
|
|
631
|
+
|
|
632
|
+
```typescript
|
|
633
|
+
const { portfolio } = await sdk.getPortfolio(userAddress);
|
|
634
|
+
|
|
635
|
+
const redeeming = (portfolio.pendingAsyncWithdrawals ?? []).some(
|
|
636
|
+
(w) =>
|
|
637
|
+
w.token?.symbol === "NVDAc" &&
|
|
638
|
+
(w.status === "REQUESTED" || w.status === "CLAIMABLE")
|
|
639
|
+
);
|
|
640
|
+
```
|
|
641
|
+
|
|
501
642
|
### 6. Get Available Protocols
|
|
502
643
|
|
|
503
644
|
Retrieve all available DeFi protocols and pools for a specific chain:
|
|
@@ -562,6 +703,86 @@ portfolio.positions?.forEach((slot) => {
|
|
|
562
703
|
**Note**: Portfolio balances are live; earnings used for the fee may come from a
|
|
563
704
|
snapshot, so net values can differ slightly from a fully live calculation.
|
|
564
705
|
|
|
706
|
+
#### Total balance
|
|
707
|
+
|
|
708
|
+
`portfolioByAssetType` is **not** the user's total balance. The backend builds
|
|
709
|
+
it from exactly two sources: the underlying amount of every deployed position,
|
|
710
|
+
and the idle balances sitting in the Safe. Anything that is in neither place is
|
|
711
|
+
missing from it.
|
|
712
|
+
|
|
713
|
+
That gap is real under the `yieldmaxxing` strategy. When the agent requests a
|
|
714
|
+
redemption from a delayed-withdrawal protocol, the position leaves the snapshot
|
|
715
|
+
immediately while the funds stay in the vault for a day or three. During that
|
|
716
|
+
window they are in no balance field — only in `pendingAsyncWithdrawals`.
|
|
717
|
+
|
|
718
|
+
So you need **two different numbers**, and showing one where the other belongs
|
|
719
|
+
is the most common mistake:
|
|
720
|
+
|
|
721
|
+
| Number | Formula | Use it for |
|
|
722
|
+
| --- | --- | --- |
|
|
723
|
+
| **Total balance** | `portfolioByAssetType` + in-flight | "You have X" — the user still owns the in-flight funds |
|
|
724
|
+
| **Requestable** | `portfolioByAssetType` only | Any withdraw form, max button, or amount validation |
|
|
725
|
+
|
|
726
|
+
An in-flight amount is **no longer withdrawable**. A `withdrawFunds` call only
|
|
727
|
+
reaches positions in the current snapshot and idle Safe balances, and the
|
|
728
|
+
in-flight amount is in neither — calling it again will not pull those funds out
|
|
729
|
+
any faster, nor will it fail with an error. They land on the user's EOA on
|
|
730
|
+
their own once the protocol releases them, so the right UI is to show them as
|
|
731
|
+
pending with their `estimatedClaimAt`, never to offer them for withdrawal.
|
|
732
|
+
|
|
733
|
+
Note the `?? "0x0"` below: when every position of an asset is in flight, the
|
|
734
|
+
backend drops the asset key from `portfolioByAssetType` altogether rather than
|
|
735
|
+
reporting a zero balance, and `portfolioByAssetType` itself can be `{}`.
|
|
736
|
+
`amount` is hex-encoded least units like every other balance, so read it with
|
|
737
|
+
`BigInt`, never `parseInt`.
|
|
738
|
+
|
|
739
|
+
```typescript
|
|
740
|
+
const { portfolio } = await sdk.getPortfolio(userAddress);
|
|
741
|
+
|
|
742
|
+
const IN_FLIGHT = ["REQUESTED", "CLAIMABLE"];
|
|
743
|
+
|
|
744
|
+
const balancesFor = (assetType: string, tokenSymbol: string) => {
|
|
745
|
+
// Everything a withdrawal can still act on.
|
|
746
|
+
const requestable = BigInt(
|
|
747
|
+
portfolio.portfolioByAssetType?.[assetType]?.balance ?? "0x0"
|
|
748
|
+
);
|
|
749
|
+
|
|
750
|
+
// Owned, but locked in a redemption until the protocol releases it.
|
|
751
|
+
const inFlight = (portfolio.pendingAsyncWithdrawals ?? [])
|
|
752
|
+
.filter((w) => IN_FLIGHT.includes(w.status) && w.token?.symbol === tokenSymbol)
|
|
753
|
+
.reduce((sum, w) => sum + BigInt(w.amount), 0n);
|
|
754
|
+
|
|
755
|
+
return { requestable, inFlight, total: requestable + inFlight };
|
|
756
|
+
};
|
|
757
|
+
```
|
|
758
|
+
|
|
759
|
+
`requestable` is what a withdrawal can still be asked on, **not** what arrives
|
|
760
|
+
immediately: it also covers async positions the user currently holds, and
|
|
761
|
+
withdrawing those turns them into a new in-flight redemption. Cap the amount a
|
|
762
|
+
user can enter at `requestable`, never at `total` — asking for more does not
|
|
763
|
+
fail loudly, the backend transfers what it can right away and queues a
|
|
764
|
+
redemption for the shortfall.
|
|
765
|
+
|
|
766
|
+
Two ways to get this wrong:
|
|
767
|
+
|
|
768
|
+
- **Do not add `staleBalances`.** They are the same idle Safe balances that
|
|
769
|
+
`portfolioByAssetType` already counts, exposed as a per-chain view for
|
|
770
|
+
surfacing funds waiting to be deployed. Adding them double-counts.
|
|
771
|
+
- **Do not add every `pendingAsyncWithdrawals` entry.** The array also keeps
|
|
772
|
+
`CLAIMED` requests for 24 hours so you can show a recent history. Those funds
|
|
773
|
+
are already back in the Safe and therefore already counted. Filter on
|
|
774
|
+
`REQUESTED` and `CLAIMABLE`.
|
|
775
|
+
|
|
776
|
+
Each in-flight entry carries the information needed to show progress:
|
|
777
|
+
`status`, `amount` (in the token's least units — apply `token.decimals`),
|
|
778
|
+
`protocol.name`, `pool`, `estimatedClaimAt`, and `statusMessage` when the
|
|
779
|
+
protocol is temporarily refusing claims. A `FAILED` status is not a loss: the
|
|
780
|
+
position is restored and the request is retried on the next cycle.
|
|
781
|
+
|
|
782
|
+
`pauseMessageByToken` is a companion field holding user-facing copy when
|
|
783
|
+
deposits are paused for a token (tokenized stocks over the weekend, for
|
|
784
|
+
example), keyed by token symbol.
|
|
785
|
+
|
|
565
786
|
### 8. Analytics & Data Endpoints
|
|
566
787
|
|
|
567
788
|
The SDK provides access to various analytics and data endpoints:
|
|
@@ -576,7 +797,7 @@ const user = await sdk.getUserDetails();
|
|
|
576
797
|
console.log("Smart Wallet:", user.user.smartWallet);
|
|
577
798
|
console.log("Active Chains:", user.user.chains);
|
|
578
799
|
console.log("Active Protocols:", user.user.protocols);
|
|
579
|
-
console.log("Strategy:", user.user.strategy); // "conservative" | "aggressive"
|
|
800
|
+
console.log("Strategy:", user.user.strategy); // "conservative" | "aggressive" | "yieldmaxxing"
|
|
580
801
|
console.log("Has Active Session:", user.user.hasActiveSessionKey);
|
|
581
802
|
|
|
582
803
|
// Feature flags
|
|
@@ -597,7 +818,7 @@ console.log("Wallet Type:", user.user.walletType);
|
|
|
597
818
|
|
|
598
819
|
**Available Fields:**
|
|
599
820
|
- **Core Info**: `id`, `address`, `smartWallet`, `chains`, `protocols`
|
|
600
|
-
- **Strategy**: `strategy` (conservative or
|
|
821
|
+
- **Strategy**: `strategy` (conservative, aggressive or yieldmaxxing)
|
|
601
822
|
- **Session**: `hasActiveSessionKey` (boolean)
|
|
602
823
|
- **Features**: `autocompounding`, `autoSelectProtocols`, `omniAccount`, `crosschainStrategy`, `executorProxy`, `splitting`, `minSplits`
|
|
603
824
|
- **Optional**: `email`, `telegramId`, `agentName`, `walletType`, `customization`, `registered`
|
|
@@ -622,7 +843,7 @@ console.log("Active protocols:", userDetails.user.protocols.length); // Should b
|
|
|
622
843
|
|
|
623
844
|
**Note**:
|
|
624
845
|
- User must be authenticated (automatically done via `connectAccount()`)
|
|
625
|
-
- Clears protocols for USDC, WETH, and
|
|
846
|
+
- Clears protocols for USDC, WETH, EURC, and NVDAc
|
|
626
847
|
- To resume operations, call `resumeAgent()` or `updateUserProfile()` with the desired protocols
|
|
627
848
|
|
|
628
849
|
#### Splitting Management
|
|
@@ -845,6 +1066,94 @@ aggressiveOpps.data.forEach((o) => {
|
|
|
845
1066
|
});
|
|
846
1067
|
```
|
|
847
1068
|
|
|
1069
|
+
#### Get Yieldmaxxing Opportunities (Delayed Withdrawals)
|
|
1070
|
+
|
|
1071
|
+
```typescript
|
|
1072
|
+
const asyncOpps = await sdk.getAsyncOpportunities(8453);
|
|
1073
|
+
asyncOpps.data.forEach((o) => {
|
|
1074
|
+
console.log(`${o.protocolName} - ${o.poolName}: ${o.apy}% APY`);
|
|
1075
|
+
});
|
|
1076
|
+
```
|
|
1077
|
+
|
|
1078
|
+
#### Strategies
|
|
1079
|
+
|
|
1080
|
+
Every method that takes a `strategy` accepts one of three values. Each tier is a
|
|
1081
|
+
superset of the previous one: an aggressive user also gets conservative pools,
|
|
1082
|
+
and a yieldmaxxing user gets everything.
|
|
1083
|
+
|
|
1084
|
+
| Strategy | Backend value | Pools unlocked |
|
|
1085
|
+
| --- | --- | --- |
|
|
1086
|
+
| `conservative` (default) | `safe_strategy` | Low-risk pools only |
|
|
1087
|
+
| `aggressive` | `degen_strategy` | Conservative + higher-risk pools |
|
|
1088
|
+
| `yieldmaxxing` | `async_strategy` | Aggressive + pools with **delayed withdrawals** |
|
|
1089
|
+
|
|
1090
|
+
`yieldmaxxing` is the only strategy that changes how withdrawals behave. It
|
|
1091
|
+
unlocks protocols (Ipor, Superform) that cannot be exited on demand: a
|
|
1092
|
+
redemption has to be requested, then claimed once the protocol releases the
|
|
1093
|
+
funds — roughly a day on Ipor, three on Superform. The agent handles both steps,
|
|
1094
|
+
but the funds are in flight in between. See
|
|
1095
|
+
[Withdraw Funds](#5-withdraw-funds) and [Total balance](#total-balance).
|
|
1096
|
+
|
|
1097
|
+
#### Set an asset's strategy
|
|
1098
|
+
|
|
1099
|
+
`updateUserProfile({ asset, strategy })` stores a strategy but does **not**
|
|
1100
|
+
compute the protocol list that goes with it, so on its own it leaves the asset
|
|
1101
|
+
with nothing to deploy into. `setAssetStrategy` does both in one call:
|
|
1102
|
+
|
|
1103
|
+
```typescript
|
|
1104
|
+
const profile = await sdk.setAssetStrategy({
|
|
1105
|
+
asset: "NVDAc",
|
|
1106
|
+
strategy: "yieldmaxxing",
|
|
1107
|
+
});
|
|
1108
|
+
console.log(profile.protocols); // Ipor + Superform
|
|
1109
|
+
```
|
|
1110
|
+
|
|
1111
|
+
| Parameter | Default | Notes |
|
|
1112
|
+
| --- | --- | --- |
|
|
1113
|
+
| `asset` | — | Required |
|
|
1114
|
+
| `strategy` | the asset's current one | Omit it to recompute the protocol list without changing strategy |
|
|
1115
|
+
| `chains` | every chain the asset exists on | **Additive** — chains already enabled are kept, so this cannot disable one |
|
|
1116
|
+
|
|
1117
|
+
This is the method to reach for when changing an existing account's strategy,
|
|
1118
|
+
since `sendDeposit` ignores its `strategy` argument after the first deposit.
|
|
1119
|
+
`resumeAgent` does the same thing for all four assets at once and is meant for
|
|
1120
|
+
resuming after `pauseAgent`.
|
|
1121
|
+
|
|
1122
|
+
#### Tokenized equities (NVDAc)
|
|
1123
|
+
|
|
1124
|
+
`NVDAc` is Coinbase's tokenized NVIDIA share (`0xb20000000000000000000078ee7ce2fE4908108C`),
|
|
1125
|
+
**8 decimals, Base only**. It behaves like any other asset — same `sendDeposit`,
|
|
1126
|
+
`withdrawFunds` and `getPortfolio` — with three differences worth planning for.
|
|
1127
|
+
|
|
1128
|
+
**It only exists under `yieldmaxxing`.** The two protocols that hold it, Ipor
|
|
1129
|
+
and Superform, are both async-only, so a `conservative` or `aggressive` profile
|
|
1130
|
+
resolves to zero protocols for NVDAc and the agent has nothing to deploy into.
|
|
1131
|
+
Every NVDAc withdrawal is therefore a delayed one — read
|
|
1132
|
+
[Total balance](#total-balance) before showing a balance.
|
|
1133
|
+
|
|
1134
|
+
**The minimum deposit is $100 of NVDAc, not 100 NVDAc.** It is converted from
|
|
1135
|
+
the live price at deposit time, so the threshold in token units moves daily
|
|
1136
|
+
(around `0.44` NVDAc at $225/share).
|
|
1137
|
+
|
|
1138
|
+
**Deposits pause when the market is closed**, typically over the weekend. Funds
|
|
1139
|
+
stay idle in the Safe and are deployed at the next open; other assets are
|
|
1140
|
+
unaffected. `getPortfolio` returns ready-to-display copy in
|
|
1141
|
+
`pauseMessageByToken["NVDAc"]` when that happens.
|
|
1142
|
+
|
|
1143
|
+
```typescript
|
|
1144
|
+
// Existing account: one call sets the strategy and selects the protocols.
|
|
1145
|
+
// Chains default to Base, the only one NVDAc exists on.
|
|
1146
|
+
await sdk.setAssetStrategy({ asset: "NVDAc", strategy: "yieldmaxxing" });
|
|
1147
|
+
|
|
1148
|
+
// 1 NVDAc = 100000000 (8 decimals). Must leave at least ~$100 in the Safe.
|
|
1149
|
+
const sentNvda = await sdk.sendDeposit(userAddress, 8453, "100000000", "NVDAc");
|
|
1150
|
+
await sdk.waitForDepositCredit(sentNvda.registration.id, 8453);
|
|
1151
|
+
```
|
|
1152
|
+
|
|
1153
|
+
Use `setAssetStrategy` rather than `updateUserProfile` here: the latter stores
|
|
1154
|
+
a strategy but does not compute a protocol list, which would leave NVDAc with
|
|
1155
|
+
nothing to deploy into. See [Set an asset's strategy](#set-an-assets-strategy).
|
|
1156
|
+
|
|
848
1157
|
### 11. APY Per Strategy
|
|
849
1158
|
|
|
850
1159
|
#### Get APY Per Strategy
|
|
@@ -1148,10 +1457,94 @@ If `withdrawFunds` returns without a `txHash`, the withdrawal is being processed
|
|
|
1148
1457
|
|
|
1149
1458
|
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
1459
|
|
|
1460
|
+
## Integration testing
|
|
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.
|
|
1465
|
+
|
|
1466
|
+
### Setup
|
|
1467
|
+
|
|
1468
|
+
```bash
|
|
1469
|
+
cd zyfai-sdk
|
|
1470
|
+
cp .env.test.example .env.test # once — fill ZYFAI_API_KEY and PRIVATE_KEY (gitignored)
|
|
1471
|
+
```
|
|
1472
|
+
|
|
1473
|
+
Vitest loads `.env.test` automatically (`vitest.config.ts`). Apply API migrations, then start the local stack from the workspace parent:
|
|
1474
|
+
|
|
1475
|
+
```bash
|
|
1476
|
+
cd ../zyfai-api && pnpm migration:up # required for deposit lifecycle (eoa_deposit.lifecycle_status, …)
|
|
1477
|
+
cd .. # zyfai-workspace root
|
|
1478
|
+
pnpm dev
|
|
1479
|
+
```
|
|
1480
|
+
|
|
1481
|
+
If the API starts before migrations run, deposit handover crons and `log_deposit` will fail with missing-column errors.
|
|
1482
|
+
|
|
1483
|
+
### Run tests
|
|
1484
|
+
|
|
1485
|
+
```bash
|
|
1486
|
+
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
|
|
1488
|
+
npm run test:integration -- get-protocols
|
|
1489
|
+
npx vitest src/integration/get-protocols.integration.test.ts --fileParallelism=false # watch mode
|
|
1490
|
+
```
|
|
1491
|
+
|
|
1492
|
+
`test:integration` always passes `--fileParallelism=false` so on-chain tests that fund ephemeral users from a shared `PRIVATE_KEY` wallet do not collide on nonce (`replacement transaction underpriced`). Pass a **feature id** (filename without `.integration.test.ts`) after `--` to run a single file.
|
|
1493
|
+
|
|
1494
|
+
Tests call `describe.skipIf(!integrationEnvReady())` and skip cleanly when `.env.test` is missing or invalid.
|
|
1495
|
+
|
|
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.
|
|
1497
|
+
|
|
1498
|
+
### Add a test for a new feature
|
|
1499
|
+
|
|
1500
|
+
1. Implement the API change in `zyfai-api` and expose it via a public SDK method (if new surface).
|
|
1501
|
+
2. Add `examples/<feature>.ts` for manual smoke.
|
|
1502
|
+
3. Add `src/integration/<feature-id>.integration.test.ts`:
|
|
1503
|
+
|
|
1504
|
+
```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
|
|
1516
|
+
});
|
|
1517
|
+
|
|
1518
|
+
await sdk.connectAccount(process.env.PRIVATE_KEY!, 8453);
|
|
1519
|
+
// public SDK calls + expect(); poll async terminal state when needed
|
|
1520
|
+
});
|
|
1521
|
+
});
|
|
1522
|
+
```
|
|
1523
|
+
|
|
1524
|
+
Conventions:
|
|
1525
|
+
|
|
1526
|
+
- Target local API via `LOCAL_EXECUTION_API_BASE_URL` from `src/config/endpoints.ts` — never production in integration tests.
|
|
1527
|
+
- 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).
|
|
1530
|
+
|
|
1531
|
+
See `src/integration/get-protocols.integration.test.ts` for a minimal example.
|
|
1532
|
+
|
|
1533
|
+
### Cross-repo features
|
|
1534
|
+
|
|
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.
|
|
1536
|
+
|
|
1537
|
+
| Command | What it runs |
|
|
1538
|
+
| --- | --- |
|
|
1539
|
+
| `npm run check` | typecheck + unit tests + build (every PR) |
|
|
1540
|
+
| `npm run test:integration` | opt-in tests against local stack (`--fileParallelism=false`) |
|
|
1541
|
+
|
|
1151
1542
|
## Contributing
|
|
1152
1543
|
|
|
1153
1544
|
Contributions are welcome! Please open an issue or submit a pull request.
|
|
1154
1545
|
|
|
1546
|
+
PRs with user-facing SDK changes need a [changeset](docs/RELEASING.md) (`npm run changeset`).
|
|
1547
|
+
|
|
1155
1548
|
## License
|
|
1156
1549
|
|
|
1157
1550
|
MIT
|