@owney/sdk 0.7.9 → 0.7.10-beta.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.
@@ -0,0 +1,473 @@
1
+ import {
2
+ ERC20_ALLOWANCE_ABI,
3
+ OwneyError
4
+ } from "./chunk-PWIKIQOX.js";
5
+
6
+ // src/agents/surfliquid/surfliquid.agent.ts
7
+ import { SurfClient } from "@surf_liquid/core-sdk";
8
+ import {
9
+ createPublicClient,
10
+ createWalletClient,
11
+ custom,
12
+ formatUnits
13
+ } from "viem";
14
+ import { base } from "viem/chains";
15
+
16
+ // src/agents/surfliquid/surfliquid.constants.ts
17
+ var SURFLIQUID_CHAIN_ID = 8453;
18
+ var SURFLIQUID_CHAIN_NAME = "BASE";
19
+ var SURFLIQUID_USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
20
+ var SURFLIQUID_USDC_DECIMALS = 6;
21
+ var SURFLIQUID_MIN_DEPOSIT = "0";
22
+ var SURFLIQUID_APPROVAL_TARGET = 100000000000n;
23
+ var SURFLIQUID_SUPPORTED_ASSETS = [
24
+ {
25
+ chainId: SURFLIQUID_CHAIN_ID,
26
+ chain: SURFLIQUID_CHAIN_NAME,
27
+ assets: [{ symbol: "USDC", minDepositAmount: SURFLIQUID_MIN_DEPOSIT }]
28
+ }
29
+ ];
30
+ var SURFLIQUID_ACTION_MAP = {
31
+ // INITIAL_DEPOSIT is the user's real first deposit, so surface it like any
32
+ // other funding ("Top up"). The mini-app intentionally hides the "Deposit"
33
+ // action (it marks Zyfai's smart-account-creation event), which would
34
+ // otherwise drop a SurfLiquid user's only history row.
35
+ INITIAL_DEPOSIT: "Top up",
36
+ DEPOSIT: "Top up",
37
+ USER_DEPOSIT: "Top up",
38
+ WITHDRAWAL: "Withdraw",
39
+ USER_WITHDRAWAL: "Withdraw",
40
+ REBALANCE: "Rebalance",
41
+ REBALANCE_COMPLETED: "Rebalance",
42
+ CROSS_CHAIN_REBALANCE: "Rebalance",
43
+ MERKL_CLAIM: "Earned"
44
+ };
45
+
46
+ // src/agents/surfliquid/surfliquid.mapper.ts
47
+ function mapMessage(message) {
48
+ const action = SURFLIQUID_ACTION_MAP[message.transactionType];
49
+ if (!action) return null;
50
+ return {
51
+ agent: "surfliquid",
52
+ action,
53
+ date: message.timestamp,
54
+ oldApy: message.apyBefore != null ? String(message.apyBefore) : null,
55
+ newApy: message.apyAfter != null ? String(message.apyAfter) : null,
56
+ transactions: [
57
+ {
58
+ txHashes: [message.txHash],
59
+ chainId: message.chainId,
60
+ tokenSymbol: message.token ?? void 0,
61
+ amount: message.amount != null ? String(message.amount) : void 0
62
+ }
63
+ ],
64
+ rebalanceLog: []
65
+ };
66
+ }
67
+ function mapHistory(result, _chainId) {
68
+ const data = result.messages.map(mapMessage).filter((entry) => entry !== null);
69
+ const hasMore = result.page < result.pages;
70
+ return {
71
+ data,
72
+ hasMore,
73
+ nextCursor: hasMore ? String(result.page + 1) : void 0
74
+ };
75
+ }
76
+ function mapBalances(vault, chainId, morphoStats) {
77
+ const assets = (vault.assets ?? []).filter(
78
+ (asset) => asset.assetSymbol === "USDC" && asset.chainId === chainId
79
+ );
80
+ const tokens = assets.map((asset) => ({
81
+ chain: SURFLIQUID_CHAIN_NAME,
82
+ chainId: SURFLIQUID_CHAIN_ID,
83
+ asset: "USDC",
84
+ amount: String(asset.currentValueUSD)
85
+ }));
86
+ const positions = assets.map((asset) => {
87
+ const stats = morphoStats?.get(asset.morphoVaultAddress?.toLowerCase() ?? "");
88
+ return {
89
+ chain: SURFLIQUID_CHAIN_NAME,
90
+ protocol: "Morpho",
91
+ // The specific MetaMorpho vault (e.g. "Gauntlet USDC Frontier"), read from
92
+ // Morpho — renders as "Morpho <vault>" alongside zyfai's vault detail.
93
+ pool: stats?.name ?? void 0,
94
+ asset: "USDC",
95
+ amount: String(asset.currentValueUSD),
96
+ apy: asset.currentAPY,
97
+ // TVL + liquidity come straight from Morpho (SurfLiquid's API omits them).
98
+ tvl: stats?.tvlUsd,
99
+ liquidity: stats?.liquidityUsd
100
+ };
101
+ });
102
+ const total = assets.reduce(
103
+ (sum, asset) => sum + asset.currentValueUSD,
104
+ 0
105
+ );
106
+ return {
107
+ smartWallet: vault.userVaultAddress ?? void 0,
108
+ totalBalance: String(total),
109
+ totalBalanceAsset: "usdc",
110
+ tokens,
111
+ positions
112
+ };
113
+ }
114
+ var APY_WINDOW_KEY = {
115
+ "7D": "apy7d",
116
+ "14D": "apy14d",
117
+ "30D": "apy30d"
118
+ };
119
+ function mapAccountApy(vault, days) {
120
+ const breakdown = vault.apyBreakdown;
121
+ const windowed = breakdown ? breakdown[APY_WINDOW_KEY[days]] : void 0;
122
+ const apy = windowed != null ? windowed : breakdown?.currentAPY ?? 0;
123
+ return {
124
+ walletAddress: vault.walletAddress ?? "",
125
+ weightedApyAfterFee: apy,
126
+ apyByChainAndAsset: { [SURFLIQUID_CHAIN_ID]: { USDC: apy } },
127
+ // Parity with Sail: SurfLiquid's core-sdk exposes no daily net-APY series.
128
+ history: []
129
+ };
130
+ }
131
+ function mapEarnings(vault, vaultAddress) {
132
+ return {
133
+ smartWallet: vaultAddress,
134
+ lifetimeEarnings: vault.earned?.totalEarningsUSD ?? 0,
135
+ tokens: []
136
+ };
137
+ }
138
+ function mapUserProfile(vault, address) {
139
+ return {
140
+ address,
141
+ smartWallet: vault.userVaultAddress ?? "",
142
+ chains: [SURFLIQUID_CHAIN_ID],
143
+ // SurfLiquid uses cookie-based session auth — no session-key concept.
144
+ hasActiveSessionKey: false,
145
+ protocols: ["SurfLiquid"]
146
+ };
147
+ }
148
+
149
+ // src/agents/surfliquid/surfliquid.wallet-adapter.ts
150
+ import { BaseWalletAdapter } from "@surf_liquid/core-sdk";
151
+ var OwneyWalletAdapter = class extends BaseWalletAdapter {
152
+ constructor(eip1193Provider) {
153
+ super();
154
+ this.eip1193Provider = eip1193Provider;
155
+ }
156
+ eip1193Provider;
157
+ name = "owney";
158
+ get installed() {
159
+ return true;
160
+ }
161
+ resolveProvider() {
162
+ return this.eip1193Provider;
163
+ }
164
+ };
165
+
166
+ // src/agents/surfliquid/surfliquid.morpho.ts
167
+ var MORPHO_API_URL = "https://api.morpho.org/graphql";
168
+ var VAULT_STATS_QUERY = `
169
+ query VaultStats($address: String!, $chainId: Int!) {
170
+ vaultByAddress(address: $address, chainId: $chainId) {
171
+ name
172
+ state { totalAssetsUsd }
173
+ liquidity { usd }
174
+ }
175
+ }
176
+ `;
177
+ var VAULT_V2_STATS_QUERY = `
178
+ query VaultV2Stats($address: String!, $chainId: Int!) {
179
+ vaultV2ByAddress(address: $address, chainId: $chainId) {
180
+ name
181
+ totalAssetsUsd
182
+ liquidityUsd
183
+ }
184
+ }
185
+ `;
186
+ async function queryMorpho(query, vaultAddress, chainId) {
187
+ try {
188
+ const res = await fetch(MORPHO_API_URL, {
189
+ method: "POST",
190
+ headers: { "Content-Type": "application/json" },
191
+ body: JSON.stringify({
192
+ query,
193
+ variables: { address: vaultAddress, chainId }
194
+ })
195
+ });
196
+ if (!res.ok) return null;
197
+ const json = await res.json();
198
+ if (json.errors) return null;
199
+ return json.data ?? null;
200
+ } catch (error) {
201
+ console.warn("surfliquid: Morpho vault stats fetch failed", {
202
+ vaultAddress,
203
+ chainId,
204
+ error
205
+ });
206
+ return null;
207
+ }
208
+ }
209
+ function toStats(name, tvlUsd, liquidityUsd) {
210
+ if (typeof tvlUsd !== "number" || typeof liquidityUsd !== "number") {
211
+ return null;
212
+ }
213
+ return {
214
+ name: typeof name === "string" ? name : null,
215
+ tvlUsd,
216
+ liquidityUsd
217
+ };
218
+ }
219
+ async function fetchMorphoVaultStats(vaultAddress, chainId) {
220
+ const v1 = await queryMorpho(VAULT_STATS_QUERY, vaultAddress, chainId);
221
+ const vault = v1?.vaultByAddress;
222
+ const v1Stats = toStats(
223
+ vault?.name,
224
+ vault?.state?.totalAssetsUsd,
225
+ vault?.liquidity?.usd
226
+ );
227
+ if (v1Stats) return v1Stats;
228
+ const v2 = await queryMorpho(VAULT_V2_STATS_QUERY, vaultAddress, chainId);
229
+ const vaultV2 = v2?.vaultV2ByAddress;
230
+ return toStats(vaultV2?.name, vaultV2?.totalAssetsUsd, vaultV2?.liquidityUsd);
231
+ }
232
+ async function fetchMorphoStatsByVault(vaultAddresses, chainId) {
233
+ const unique = [...new Set(vaultAddresses.map((a) => a.toLowerCase()))];
234
+ const entries = await Promise.all(
235
+ unique.map(
236
+ async (address) => [address, await fetchMorphoVaultStats(address, chainId)]
237
+ )
238
+ );
239
+ const byVault = /* @__PURE__ */ new Map();
240
+ for (const [address, stats] of entries) {
241
+ if (stats) byVault.set(address, stats);
242
+ }
243
+ return byVault;
244
+ }
245
+
246
+ // src/agents/surfliquid/surfliquid.agent.ts
247
+ var APY_WINDOW_KEY2 = {
248
+ "7D": "apy7d",
249
+ "14D": "apy14d",
250
+ "30D": "apy30d"
251
+ };
252
+ var SurfLiquidAgent = class {
253
+ constructor(config) {
254
+ this.config = config;
255
+ }
256
+ config;
257
+ id = "surfliquid";
258
+ supportedChainIds = [SURFLIQUID_CHAIN_ID];
259
+ supportedAssets = SURFLIQUID_SUPPORTED_ASSETS;
260
+ surf = null;
261
+ connectedAddress = null;
262
+ // In-flight connect+auth, shared by concurrent callers to dedupe SIWE.
263
+ connectPromise = null;
264
+ ensureSurf() {
265
+ if (this.surf) return this.surf;
266
+ this.surf = SurfClient.create({
267
+ projectName: this.config.projectName,
268
+ appId: this.config.appId,
269
+ environment: "mainnet",
270
+ chainId: SURFLIQUID_CHAIN_ID,
271
+ apiBaseUrl: this.config.apiBaseUrl,
272
+ rpcUrl: this.config.rpcUrl,
273
+ // Let the SDK auto-approve USDC to the vault before depositing.
274
+ autoApprove: true
275
+ });
276
+ return this.surf;
277
+ }
278
+ /**
279
+ * Connects + authenticates the SurfClient against owney's provider. Skips the
280
+ * SIWE prompt when already authenticated for this wallet (cookie session).
281
+ */
282
+ async connect(state) {
283
+ const surf = this.ensureSurf();
284
+ const sameWallet = this.connectedAddress?.toLowerCase() === state.walletAddress.toLowerCase();
285
+ if (sameWallet && surf.getAuthState().authenticated) {
286
+ return surf;
287
+ }
288
+ if (this.connectPromise) return this.connectPromise;
289
+ this.connectPromise = (async () => {
290
+ surf.registerWalletAdapter(
291
+ "owney",
292
+ new OwneyWalletAdapter(state.provider)
293
+ );
294
+ await surf.connectWallet("owney");
295
+ await surf.authenticate();
296
+ this.connectedAddress = state.walletAddress;
297
+ return surf;
298
+ })();
299
+ try {
300
+ return await this.connectPromise;
301
+ } finally {
302
+ this.connectPromise = null;
303
+ }
304
+ }
305
+ /**
306
+ * Returns the user's vault address, deploying one on first use. SurfLiquid's
307
+ * deposit requires the vault to exist, so this must run before depositing.
308
+ * Existing vault → returned as-is; otherwise `deployVault()` is sent
309
+ * (user-pays) and the freshly deployed address is returned.
310
+ */
311
+ async resolveVaultAddress(surf, owner) {
312
+ const vault = await surf.getVault(owner).catch(() => null);
313
+ if (vault?.exists && vault.userVaultAddress) {
314
+ return vault.userVaultAddress;
315
+ }
316
+ const { vaultAddress } = await surf.deployVault();
317
+ return vaultAddress;
318
+ }
319
+ /**
320
+ * Grants the user's vault a standing USDC allowance so SurfLiquid's
321
+ * `autoApprove` has nothing to do — see {@link SURFLIQUID_APPROVAL_TARGET}
322
+ * for why one prompt per deposit is worth removing.
323
+ *
324
+ * Fails OPEN on a read error: if the allowance can't be checked we simply
325
+ * return and let SurfLiquid's own per-deposit approve run, because a flaky
326
+ * RPC must never block a deposit. A failed or rejected APPROVE does
327
+ * propagate — the user declined a transaction, and letting SurfLiquid
328
+ * immediately ask again for a smaller one is exactly the double prompt this
329
+ * removes.
330
+ */
331
+ async ensureVaultAllowance(state, vaultAddress, amount) {
332
+ const spender = vaultAddress;
333
+ const transport = custom(state.provider);
334
+ const publicClient = createPublicClient({ chain: base, transport });
335
+ let allowance;
336
+ try {
337
+ allowance = await publicClient.readContract({
338
+ address: SURFLIQUID_USDC_ADDRESS,
339
+ abi: ERC20_ALLOWANCE_ABI,
340
+ functionName: "allowance",
341
+ args: [state.walletAddress, spender]
342
+ });
343
+ } catch (error) {
344
+ console.warn(
345
+ "[owney-sdk] SurfLiquid allowance pre-check failed; deferring to its per-deposit approve:",
346
+ error instanceof Error ? error.message : String(error)
347
+ );
348
+ return;
349
+ }
350
+ if (allowance >= amount) return;
351
+ const target = amount > SURFLIQUID_APPROVAL_TARGET ? amount : SURFLIQUID_APPROVAL_TARGET;
352
+ const wallet = createWalletClient({
353
+ account: state.walletAddress,
354
+ chain: base,
355
+ transport
356
+ });
357
+ const hash = await wallet.writeContract({
358
+ address: SURFLIQUID_USDC_ADDRESS,
359
+ abi: ERC20_ALLOWANCE_ABI,
360
+ functionName: "approve",
361
+ args: [spender, target],
362
+ account: state.walletAddress,
363
+ chain: base
364
+ });
365
+ const receipt = await publicClient.waitForTransactionReceipt({
366
+ hash,
367
+ confirmations: 1
368
+ });
369
+ if (receipt.status !== "success") {
370
+ throw new Error(`SurfLiquid USDC approval reverted (tx ${hash})`);
371
+ }
372
+ }
373
+ // --- IAgent: lifecycle ---
374
+ async disconnect() {
375
+ if (this.surf) {
376
+ await this.surf.disconnectWallet();
377
+ }
378
+ this.connectedAddress = null;
379
+ }
380
+ async activateAgent(state) {
381
+ await this.connect(state);
382
+ }
383
+ // --- IAgent: funds (user-pays; asset is always USDC, callback ignored) ---
384
+ async deposit(state, _chainId, amount, _asset, _depositCallback) {
385
+ const surf = await this.connect(state);
386
+ const human = formatUnits(BigInt(amount), SURFLIQUID_USDC_DECIMALS);
387
+ const smartWallet = await this.resolveVaultAddress(
388
+ surf,
389
+ state.walletAddress
390
+ );
391
+ await this.ensureVaultAllowance(state, smartWallet, BigInt(amount));
392
+ const tx = await surf.deposit({
393
+ asset: SURFLIQUID_USDC_ADDRESS,
394
+ amount: human
395
+ });
396
+ await tx.wait();
397
+ return { txHash: tx.hash, smartWallet, amount };
398
+ }
399
+ async withdraw(state, _chainId, _token, amount) {
400
+ const surf = await this.connect(state);
401
+ const human = amount != null ? formatUnits(BigInt(amount), SURFLIQUID_USDC_DECIMALS) : void 0;
402
+ try {
403
+ const tx = await surf.withdraw({
404
+ asset: SURFLIQUID_USDC_ADDRESS,
405
+ amount: human
406
+ });
407
+ await tx.wait();
408
+ return {
409
+ txHash: tx.hash,
410
+ type: amount != null ? "partial" : "full",
411
+ amount: amount ?? "0"
412
+ };
413
+ } catch (error) {
414
+ throw new OwneyError(
415
+ "WITHDRAW_FAILED",
416
+ error instanceof Error ? error.message : "SurfLiquid withdraw failed.",
417
+ { chainId: SURFLIQUID_CHAIN_ID, amount },
418
+ this.id
419
+ );
420
+ }
421
+ }
422
+ // --- IAgent: portfolio reads ---
423
+ async getBalances(state, chainId) {
424
+ const surf = await this.connect(state);
425
+ const vault = await surf.getVault(state.walletAddress);
426
+ const morphoVaultAddresses = (vault.assets ?? []).filter((asset) => asset.assetSymbol === "USDC" && asset.chainId === chainId).map((asset) => asset.morphoVaultAddress).filter((address) => Boolean(address));
427
+ const morphoStats = await fetchMorphoStatsByVault(
428
+ morphoVaultAddresses,
429
+ chainId
430
+ );
431
+ return mapBalances(vault, chainId, morphoStats);
432
+ }
433
+ async getEarnings(state) {
434
+ const surf = await this.connect(state);
435
+ const vault = await surf.getVault(state.walletAddress);
436
+ return mapEarnings(vault, vault.userVaultAddress ?? state.walletAddress);
437
+ }
438
+ async getAccountApy(state, _chainId, days, _tokenSymbol) {
439
+ const surf = await this.connect(state);
440
+ const vault = await surf.getVault(state.walletAddress);
441
+ return mapAccountApy(vault, days);
442
+ }
443
+ async getHistory(state, chainId, options) {
444
+ const surf = await this.connect(state);
445
+ const page = options?.cursor ? Number(options.cursor) : 1;
446
+ const limit = options?.limit ?? 10;
447
+ const result = await surf.getAgentMessages(
448
+ state.walletAddress,
449
+ page,
450
+ limit,
451
+ options?.fromDate,
452
+ options?.toDate
453
+ );
454
+ return mapHistory(result, chainId);
455
+ }
456
+ async getUserProfile(state) {
457
+ const surf = await this.connect(state);
458
+ const vault = await surf.getVault(state.walletAddress);
459
+ return mapUserProfile(vault, state.walletAddress);
460
+ }
461
+ // --- IAgent: discovery (no wallet) ---
462
+ async getAgentApy(days, _options) {
463
+ const surf = this.ensureSurf();
464
+ const assets = await surf.getSupportedAssets(SURFLIQUID_CHAIN_ID);
465
+ const usdc = assets.find((asset) => asset.assetSymbol === "USDC");
466
+ if (!usdc) return { averageApy: 0 };
467
+ const windowed = usdc[APY_WINDOW_KEY2[days]];
468
+ return { averageApy: windowed != null ? windowed : usdc.currentAPY };
469
+ }
470
+ };
471
+ export {
472
+ SurfLiquidAgent
473
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owney/sdk",
3
- "version": "0.7.9",
3
+ "version": "0.7.10-beta.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.js",
@@ -23,7 +23,9 @@
23
23
  "test:watch": "vitest"
24
24
  },
25
25
  "dependencies": {
26
+ "@surf_liquid/core-sdk": "^0.4.0",
26
27
  "@zyfai/sdk": "0.2.48",
28
+ "ethers": "^6.17.0",
27
29
  "siwe": "^3.0.0",
28
30
  "viem": "^2.48.1"
29
31
  },