@zyfai/sdk 0.2.57 → 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 CHANGED
@@ -325,7 +325,7 @@ Get the Smart Wallet (Safe) address for a user.
325
325
 
326
326
  ##### `deploySafe(userAddress: string, chainId: SupportedChainId, strategy?: Strategy): Promise<DeploySafeResponse>`
327
327
 
328
- > **Deprecated** for partner integrations. Prefer `depositFunds()` — predeployed Safes and session keys are handled on first deposit. This method remains available for legacy flows and emits a console warning when called.
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.
329
329
 
330
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.
331
331
 
@@ -353,7 +353,7 @@ Deploy a Safe smart wallet for a user. **Deployment is handled by the backend AP
353
353
 
354
354
  - User must be authenticated (automatically done via `connectAccount()`)
355
355
  - Backend handles all RPC calls, avoiding rate limiting
356
- - Protocol / asset patching runs in `deploySafe` (all paths). `depositFunds` still patches on the account's **first** deposit if USDC `chains` are empty (see Deposit Funds below)
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)
357
357
 
358
358
  ##### `addWalletToSdk(walletAddress: string): Promise<AddWalletToSdkResponse>`
359
359
 
@@ -380,7 +380,7 @@ Session keys enable delegated transaction execution without exposing the main pr
380
380
 
381
381
  #### Simple Usage (Legacy — deprecated)
382
382
 
383
- > **Deprecated** for partner integrations. Prefer `depositFunds()` — predeployed wallets already have the agent session enabled. This method remains available for legacy flows and emits a console warning when called.
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.
384
384
 
385
385
  The SDK automatically fetches optimal session configuration from Zyfai API:
386
386
 
@@ -411,61 +411,81 @@ console.log("User ID:", result.userId);
411
411
  - User must be authenticated (automatically done via `connectAccount()`)
412
412
  - The SDK proactively checks if the user already has an active session key and returns early without requiring any signature if one exists
413
413
  - The user record must have `smartWallet` and `chainId` set (predeployed assignment / first deposit)
414
- - Protocol selection is **not** touched by `createSessionKey` — it's set by `deploySafe` and on the first `depositFunds` call if USDC `chains` are still empty
415
- - **Deprecated**: prefer `depositFunds()` for partner onboarding; `createSessionKey` remains for legacy flows
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
416
416
  - When `alreadyActive` is `true`, `sessionKeyAddress` and `signature` are not available in the response
417
417
 
418
- ### 4. Deposit Funds
418
+ ### 4. Send a Deposit
419
419
 
420
420
  Transfer tokens to your Safe smart wallet. Token address is automatically selected based on chain and the requested asset (defaults to USDC):
421
421
 
422
422
  - **Ethereum Mainnet (1), Base (8453), Arbitrum (42161)**: USDC (default) or WETH
423
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)
424
425
 
425
426
  **Minimum portfolio balance (enforced on Safe balance + deposit amount):**
426
427
 
427
428
  - Ethereum Mainnet (1) / USDC or EURC: 10,000 units
428
429
  - Base (8453) and Arbitrum (42161) / USDC or EURC: 100 units
429
- - WETH: about **$10,000** of ETH on Ethereum Mainnet, **$100** on Base and Arbitrum, using the live USD price from Data API `GET /api/v2/price?token=eth` (same API key as the SDK)
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.
430
434
 
431
435
  Top-ups smaller than the minimum are allowed if the Safe already holds enough of the asset to meet it after the deposit.
432
436
 
433
437
  ```typescript
434
- // Deposit 10 USDC (6 decimals) to Safe on Base — no minimum on Base
435
- const result = await sdk.depositFunds(
438
+ // Send 10 USDC (6 decimals) to Safe on Base.
439
+ const sent = await sdk.sendDeposit(
436
440
  userAddress,
437
441
  8453, // Chain ID
438
442
  "10000000", // Amount: 10 USDC = 10 * 10^6
439
443
  "USDC"
440
444
  );
441
445
 
446
+ // Await custody credit only when this UI needs the completion state.
447
+ const credited = await sdk.waitForDepositCredit(sent.registration.id, 8453);
448
+
442
449
  // First deposit with aggressive strategy (protocol patching)
443
- await sdk.depositFunds(userAddress, 8453, "10000000", "USDC", "aggressive");
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);
444
458
 
445
- if (result.success) {
446
- console.log("Deposit successful!");
447
- console.log("Transaction Hash:", result.txHash);
459
+ if (credited.status === "credited") {
460
+ console.log("Deposit credited!");
461
+ console.log("Transaction Hash:", sent.txHash);
448
462
  }
449
463
  ```
450
464
 
451
465
  **Note:**
452
466
 
453
467
  - Amount must be in least decimal units. For USDC (6 decimals): 1 USDC = 1000000
454
- - `asset` is required (`"USDC"`, `"WETH"`, or `"EURC"` — EURC on Mainnet/Base only); token address is selected from that for the chain
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.
455
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.
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.
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.
460
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:
461
476
 
462
477
  ```typescript
463
478
  await sdk.updateUserProfile({ asset: "USDC", strategy: "yieldmaxxing" });
464
479
  ```
465
480
 
466
- #### Log External Deposit (For Sponsored Transactions)
481
+ #### Deposit With an External Wallet (Sponsored Transactions)
467
482
 
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.
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.
469
489
 
470
490
  **Authentication (required).** `log_deposit` is a **user** endpoint. You need both:
471
491
 
@@ -479,36 +499,45 @@ Calling `logDeposit()` **without** `connectAccount()` on the **same** SDK instan
479
499
  ```typescript
480
500
  const sdk = new ZyfaiSDK({ apiKey: process.env.ZYFAI_API_KEY! });
481
501
 
482
- // Required before logDeposit — same instance that will post log_deposit
502
+ // Required before the deposit — same instance that will post log_deposit
483
503
  await sdk.connectAccount(walletProviderOrPrivateKey, chainId);
484
504
 
485
- // 1. Execute deposit with your own wallet implementation (e.g., Privy, Bankr)
505
+ await sdk.ensureFirstDepositSetup("conservative");
506
+ const intent = await sdk.buildDepositTransfer({
507
+ userAddress,
508
+ chainId: 8453,
509
+ amount: "100000000",
510
+ asset: "USDC",
511
+ });
486
512
  const txHash = await privyWallet.sendTransaction({
487
- to: safeAddress,
488
- data: transferData, // ERC20 transfer encoded data
513
+ to: intent.to,
514
+ data: intent.data,
489
515
  });
490
516
 
491
- // 2. Register the deposit (must return success — do not treat tx confirmation alone as "subscribed")
492
- const result = await sdk.logDeposit(
493
- 8453, // chainId
494
- txHash, // transaction hash from your wallet
495
- "100000000" // 100 USDC (6 decimals)
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,
496
524
  );
525
+ await sdk.waitForDepositCredit(deposit.id, 8453);
497
526
 
498
- if (result.success) {
499
- console.log("Deposit logged successfully");
500
- }
527
+ console.log("Deposit credited:", deposit.id);
501
528
  ```
502
529
 
530
+ See the external deposit building-block API reference for full signatures.
531
+
503
532
  **When to use `logDeposit`:**
504
533
 
505
- - You did **not** call `depositFunds()` (it already logs the deposit for you)
534
+ - You did **not** call `sendDeposit()` (it already logs the deposit for you)
506
535
  - You use sponsored/gasless transactions (Privy, Biconomy, Gelato, etc.)
507
536
  - You have a custom wallet / frontend transfer
508
537
  - You need more control over transaction execution
509
538
  - You want to pay gas fees for your users
510
539
 
511
- **When to prefer `depositFunds()` instead:** one SDK instance, `connectAccount()` once, transfer + `log_deposit` in one call — fewer ways to miss the JWT.
540
+ `depositFunds()` retains its complete credit-waiting flow for existing integrations and still rejects on timeout so a resolved promise means credited balance.
512
541
 
513
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.
514
543
 
@@ -584,6 +613,32 @@ silently returns only what is left. It is also missing from
584
613
  `portfolioByAssetType` while in flight, so validate user-entered amounts
585
614
  against that field rather than the total — see [Total balance](#total-balance).
586
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
+
587
642
  ### 6. Get Available Protocols
588
643
 
589
644
  Retrieve all available DeFi protocols and pools for a specific chain:
@@ -788,7 +843,7 @@ console.log("Active protocols:", userDetails.user.protocols.length); // Should b
788
843
 
789
844
  **Note**:
790
845
  - User must be authenticated (automatically done via `connectAccount()`)
791
- - Clears protocols for USDC, WETH, and EURC
846
+ - Clears protocols for USDC, WETH, EURC, and NVDAc
792
847
  - To resume operations, call `resumeAgent()` or `updateUserProfile()` with the desired protocols
793
848
 
794
849
  #### Splitting Management
@@ -1039,6 +1094,66 @@ funds — roughly a day on Ipor, three on Superform. The agent handles both step
1039
1094
  but the funds are in flight in between. See
1040
1095
  [Withdraw Funds](#5-withdraw-funds) and [Total balance](#total-balance).
1041
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
+
1042
1157
  ### 11. APY Per Strategy
1043
1158
 
1044
1159
  #### Get APY Per Strategy
@@ -1355,25 +1470,31 @@ cd zyfai-sdk
1355
1470
  cp .env.test.example .env.test # once — fill ZYFAI_API_KEY and PRIVATE_KEY (gitignored)
1356
1471
  ```
1357
1472
 
1358
- Vitest loads `.env.test` automatically (`vitest.config.ts`). Start the local API from the workspace parent:
1473
+ Vitest loads `.env.test` automatically (`vitest.config.ts`). Apply API migrations, then start the local stack from the workspace parent:
1359
1474
 
1360
1475
  ```bash
1476
+ cd ../zyfai-api && pnpm migration:up # required for deposit lifecycle (eoa_deposit.lifecycle_status, …)
1361
1477
  cd .. # zyfai-workspace root
1362
1478
  pnpm dev
1363
1479
  ```
1364
1480
 
1481
+ If the API starts before migrations run, deposit handover crons and `log_deposit` will fail with missing-column errors.
1482
+
1365
1483
  ### Run tests
1366
1484
 
1367
1485
  ```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
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
1373
1490
  ```
1374
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
+
1375
1494
  Tests call `describe.skipIf(!integrationEnvReady())` and skip cleanly when `.env.test` is missing or invalid.
1376
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
+
1377
1498
  ### Add a test for a new feature
1378
1499
 
1379
1500
  1. Implement the API change in `zyfai-api` and expose it via a public SDK method (if new surface).
@@ -1416,7 +1537,7 @@ When a feature spans `zyfai-sdk`, `zyfai-api`, and optionally `predeployment-ser
1416
1537
  | Command | What it runs |
1417
1538
  | --- | --- |
1418
1539
  | `npm run check` | typecheck + unit tests + build (every PR) |
1419
- | `npm run test:integration` | opt-in tests against local stack (feature work) |
1540
+ | `npm run test:integration` | opt-in tests against local stack (`--fileParallelism=false`) |
1420
1541
 
1421
1542
  ## Contributing
1422
1543