@zyfai/sdk 0.2.57 → 0.3.1
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 +260 -71
- package/dist/index.d.mts +716 -122
- package/dist/index.d.ts +716 -122
- package/dist/index.js +1115 -275
- package/dist/index.mjs +1115 -275
- package/package.json +9 -4
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 `
|
|
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). `
|
|
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 `
|
|
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 `
|
|
415
|
-
- **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
|
|
416
416
|
- When `alreadyActive` is `true`, `sessionKeyAddress` and `signature` are not available in the response
|
|
417
417
|
|
|
418
|
-
### 4. Deposit
|
|
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
|
|
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
|
-
//
|
|
435
|
-
const
|
|
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.
|
|
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 (
|
|
446
|
-
console.log("Deposit
|
|
447
|
-
console.log("Transaction Hash:",
|
|
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 `"
|
|
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 `
|
|
457
|
-
-
|
|
458
|
-
-
|
|
459
|
-
-
|
|
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
|
-
####
|
|
481
|
+
#### Deposit With an External Wallet (Sponsored Transactions)
|
|
467
482
|
|
|
468
|
-
`
|
|
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
|
|
502
|
+
// Required before the deposit — same instance that will post log_deposit
|
|
483
503
|
await sdk.connectAccount(walletProviderOrPrivateKey, chainId);
|
|
484
504
|
|
|
485
|
-
|
|
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:
|
|
488
|
-
data:
|
|
513
|
+
to: intent.to,
|
|
514
|
+
data: intent.data,
|
|
489
515
|
});
|
|
490
516
|
|
|
491
|
-
//
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
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
|
-
|
|
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 `
|
|
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
|
-
|
|
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
|
|
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
|
|
@@ -936,16 +991,16 @@ const earnings = await sdk.getOnchainEarnings(walletAddress);
|
|
|
936
991
|
console.log("Total by token:", earnings.data.totalEarningsByToken);
|
|
937
992
|
// Per-chain totals (chain → token → amount): { "8453": { "USDC": "0.01" }, "42161": {...} }
|
|
938
993
|
console.log("Total by chain:", earnings.data.totalEarningsByChain);
|
|
939
|
-
// Net totals: lifetime + unrealized + current × 0.9
|
|
994
|
+
// Net totals: (lifetime + unrealized + current) × 0.9
|
|
940
995
|
console.log("Net by token:", earnings.data.totalEarningsByTokenWithFee);
|
|
941
996
|
console.log("Net by chain:", earnings.data.totalEarningsByChainWithFee);
|
|
942
997
|
```
|
|
943
998
|
|
|
944
999
|
**Fee formula for `*WithFee` earnings fields**
|
|
945
1000
|
|
|
946
|
-
- `totalWithFee = lifetime + unrealized + current × 0.9`
|
|
947
|
-
-
|
|
948
|
-
-
|
|
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`
|
|
949
1004
|
|
|
950
1005
|
#### Calculate Onchain Earnings (Refresh)
|
|
951
1006
|
|
|
@@ -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
|
|
@@ -1344,36 +1459,106 @@ Some Data API endpoints may require server-side CORS configuration. If you see C
|
|
|
1344
1459
|
|
|
1345
1460
|
## Integration testing
|
|
1346
1461
|
|
|
1347
|
-
Use opt-in Vitest integration tests to prove
|
|
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.
|
|
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.
|
|
1350
1463
|
|
|
1351
1464
|
### Setup
|
|
1352
1465
|
|
|
1353
1466
|
```bash
|
|
1354
1467
|
cd zyfai-sdk
|
|
1355
|
-
cp .env.test.example .env.test # once — fill
|
|
1468
|
+
cp .env.test.example .env.test # once — fill keys below (gitignored)
|
|
1356
1469
|
```
|
|
1357
1470
|
|
|
1358
|
-
Vitest loads `.env.test` automatically (`vitest.config.ts`).
|
|
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:
|
|
1359
1496
|
|
|
1360
1497
|
```bash
|
|
1498
|
+
cd ../zyfai-api && pnpm migration:up
|
|
1361
1499
|
cd .. # zyfai-workspace root
|
|
1362
1500
|
pnpm dev
|
|
1363
1501
|
```
|
|
1364
1502
|
|
|
1503
|
+
If the API starts before migrations run, deposit handover crons and `log_deposit` will fail with missing-column errors.
|
|
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
|
+
|
|
1365
1544
|
### Run tests
|
|
1366
1545
|
|
|
1367
1546
|
```bash
|
|
1368
|
-
npm run test:integration
|
|
1369
|
-
npm run test:integration --
|
|
1370
|
-
npm run test:integration --
|
|
1371
|
-
npm run test:integration -- -
|
|
1372
|
-
npx vitest get-protocols
|
|
1547
|
+
npm run test:integration # all integration tests (sequential)
|
|
1548
|
+
npm run test:integration -- deposit-withdraw # one file by feature id
|
|
1549
|
+
npm run test:integration -- get-protocols
|
|
1550
|
+
ZYFAI_ENV=staging npm run test:integration -- deposit-withdraw
|
|
1551
|
+
npx vitest src/integration/get-protocols.integration.test.ts --fileParallelism=false # watch mode
|
|
1373
1552
|
```
|
|
1374
1553
|
|
|
1554
|
+
`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.
|
|
1555
|
+
|
|
1375
1556
|
Tests call `describe.skipIf(!integrationEnvReady())` and skip cleanly when `.env.test` is missing or invalid.
|
|
1376
1557
|
|
|
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.
|
|
1561
|
+
|
|
1377
1562
|
### Add a test for a new feature
|
|
1378
1563
|
|
|
1379
1564
|
1. Implement the API change in `zyfai-api` and expose it via a public SDK method (if new surface).
|
|
@@ -1381,42 +1566,46 @@ Tests call `describe.skipIf(!integrationEnvReady())` and skip cleanly when `.env
|
|
|
1381
1566
|
3. Add `src/integration/<feature-id>.integration.test.ts`:
|
|
1382
1567
|
|
|
1383
1568
|
```typescript
|
|
1384
|
-
import {
|
|
1385
|
-
import {
|
|
1386
|
-
import {
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
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 */ });
|
|
1395
1586
|
});
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
// public SDK calls + expect(); poll async terminal state when needed
|
|
1399
|
-
});
|
|
1400
|
-
});
|
|
1587
|
+
},
|
|
1588
|
+
);
|
|
1401
1589
|
```
|
|
1402
1590
|
|
|
1403
1591
|
Conventions:
|
|
1404
1592
|
|
|
1405
|
-
-
|
|
1593
|
+
- Use `integrationSdkConfig()` so `ZYFAI_ENV` selects the API stack.
|
|
1406
1594
|
- Import `ZyfaiSDK` from `../core/ZyfaiSDK` (working tree), not a published npm build.
|
|
1407
|
-
- Use only public SDK methods; hardcode chain id and amounts
|
|
1408
|
-
- Set `{ timeout: 180_000 }` on `describe` for async flows
|
|
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.
|
|
1409
1598
|
|
|
1410
|
-
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.
|
|
1411
1600
|
|
|
1412
1601
|
### Cross-repo features
|
|
1413
1602
|
|
|
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)**
|
|
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)**.
|
|
1415
1604
|
|
|
1416
1605
|
| Command | What it runs |
|
|
1417
1606
|
| --- | --- |
|
|
1418
1607
|
| `npm run check` | typecheck + unit tests + build (every PR) |
|
|
1419
|
-
| `npm run test:integration` | opt-in tests
|
|
1608
|
+
| `npm run test:integration` | opt-in tests (`--fileParallelism=false`; `ZYFAI_ENV` selects API) |
|
|
1420
1609
|
|
|
1421
1610
|
## Contributing
|
|
1422
1611
|
|