@owney/sdk 0.6.9-beta.5 → 0.6.9-beta.7

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,448 @@
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
+ async function fetchMorphoVaultStats(vaultAddress, chainId) {
178
+ try {
179
+ const res = await fetch(MORPHO_API_URL, {
180
+ method: "POST",
181
+ headers: { "Content-Type": "application/json" },
182
+ body: JSON.stringify({
183
+ query: VAULT_STATS_QUERY,
184
+ variables: { address: vaultAddress, chainId }
185
+ })
186
+ });
187
+ if (!res.ok) return null;
188
+ const json = await res.json();
189
+ if (json.errors) return null;
190
+ const vault = json.data?.vaultByAddress;
191
+ const tvlUsd = vault?.state?.totalAssetsUsd;
192
+ const liquidityUsd = vault?.liquidity?.usd;
193
+ if (typeof tvlUsd !== "number" || typeof liquidityUsd !== "number") {
194
+ return null;
195
+ }
196
+ const name = typeof vault?.name === "string" ? vault.name : null;
197
+ return { name, tvlUsd, liquidityUsd };
198
+ } catch (error) {
199
+ console.warn("surfliquid: Morpho vault stats fetch failed", {
200
+ vaultAddress,
201
+ chainId,
202
+ error
203
+ });
204
+ return null;
205
+ }
206
+ }
207
+ async function fetchMorphoStatsByVault(vaultAddresses, chainId) {
208
+ const unique = [...new Set(vaultAddresses.map((a) => a.toLowerCase()))];
209
+ const entries = await Promise.all(
210
+ unique.map(
211
+ async (address) => [address, await fetchMorphoVaultStats(address, chainId)]
212
+ )
213
+ );
214
+ const byVault = /* @__PURE__ */ new Map();
215
+ for (const [address, stats] of entries) {
216
+ if (stats) byVault.set(address, stats);
217
+ }
218
+ return byVault;
219
+ }
220
+
221
+ // src/agents/surfliquid/surfliquid.agent.ts
222
+ var APY_WINDOW_KEY2 = {
223
+ "7D": "apy7d",
224
+ "14D": "apy14d",
225
+ "30D": "apy30d"
226
+ };
227
+ var SurfLiquidAgent = class {
228
+ constructor(config) {
229
+ this.config = config;
230
+ }
231
+ config;
232
+ id = "surfliquid";
233
+ supportedChainIds = [SURFLIQUID_CHAIN_ID];
234
+ supportedAssets = SURFLIQUID_SUPPORTED_ASSETS;
235
+ surf = null;
236
+ connectedAddress = null;
237
+ // In-flight connect+auth, shared by concurrent callers to dedupe SIWE.
238
+ connectPromise = null;
239
+ ensureSurf() {
240
+ if (this.surf) return this.surf;
241
+ this.surf = SurfClient.create({
242
+ projectName: this.config.projectName,
243
+ appId: this.config.appId,
244
+ environment: "mainnet",
245
+ chainId: SURFLIQUID_CHAIN_ID,
246
+ apiBaseUrl: this.config.apiBaseUrl,
247
+ rpcUrl: this.config.rpcUrl,
248
+ // Let the SDK auto-approve USDC to the vault before depositing.
249
+ autoApprove: true
250
+ });
251
+ return this.surf;
252
+ }
253
+ /**
254
+ * Connects + authenticates the SurfClient against owney's provider. Skips the
255
+ * SIWE prompt when already authenticated for this wallet (cookie session).
256
+ */
257
+ async connect(state) {
258
+ const surf = this.ensureSurf();
259
+ const sameWallet = this.connectedAddress?.toLowerCase() === state.walletAddress.toLowerCase();
260
+ if (sameWallet && surf.getAuthState().authenticated) {
261
+ return surf;
262
+ }
263
+ if (this.connectPromise) return this.connectPromise;
264
+ this.connectPromise = (async () => {
265
+ surf.registerWalletAdapter(
266
+ "owney",
267
+ new OwneyWalletAdapter(state.provider)
268
+ );
269
+ await surf.connectWallet("owney");
270
+ await surf.authenticate();
271
+ this.connectedAddress = state.walletAddress;
272
+ return surf;
273
+ })();
274
+ try {
275
+ return await this.connectPromise;
276
+ } finally {
277
+ this.connectPromise = null;
278
+ }
279
+ }
280
+ /**
281
+ * Returns the user's vault address, deploying one on first use. SurfLiquid's
282
+ * deposit requires the vault to exist, so this must run before depositing.
283
+ * Existing vault → returned as-is; otherwise `deployVault()` is sent
284
+ * (user-pays) and the freshly deployed address is returned.
285
+ */
286
+ async resolveVaultAddress(surf, owner) {
287
+ const vault = await surf.getVault(owner).catch(() => null);
288
+ if (vault?.exists && vault.userVaultAddress) {
289
+ return vault.userVaultAddress;
290
+ }
291
+ const { vaultAddress } = await surf.deployVault();
292
+ return vaultAddress;
293
+ }
294
+ /**
295
+ * Grants the user's vault a standing USDC allowance so SurfLiquid's
296
+ * `autoApprove` has nothing to do — see {@link SURFLIQUID_APPROVAL_TARGET}
297
+ * for why one prompt per deposit is worth removing.
298
+ *
299
+ * Fails OPEN on a read error: if the allowance can't be checked we simply
300
+ * return and let SurfLiquid's own per-deposit approve run, because a flaky
301
+ * RPC must never block a deposit. A failed or rejected APPROVE does
302
+ * propagate — the user declined a transaction, and letting SurfLiquid
303
+ * immediately ask again for a smaller one is exactly the double prompt this
304
+ * removes.
305
+ */
306
+ async ensureVaultAllowance(state, vaultAddress, amount) {
307
+ const spender = vaultAddress;
308
+ const transport = custom(state.provider);
309
+ const publicClient = createPublicClient({ chain: base, transport });
310
+ let allowance;
311
+ try {
312
+ allowance = await publicClient.readContract({
313
+ address: SURFLIQUID_USDC_ADDRESS,
314
+ abi: ERC20_ALLOWANCE_ABI,
315
+ functionName: "allowance",
316
+ args: [state.walletAddress, spender]
317
+ });
318
+ } catch (error) {
319
+ console.warn(
320
+ "[owney-sdk] SurfLiquid allowance pre-check failed; deferring to its per-deposit approve:",
321
+ error instanceof Error ? error.message : String(error)
322
+ );
323
+ return;
324
+ }
325
+ if (allowance >= amount) return;
326
+ const target = amount > SURFLIQUID_APPROVAL_TARGET ? amount : SURFLIQUID_APPROVAL_TARGET;
327
+ const wallet = createWalletClient({
328
+ account: state.walletAddress,
329
+ chain: base,
330
+ transport
331
+ });
332
+ const hash = await wallet.writeContract({
333
+ address: SURFLIQUID_USDC_ADDRESS,
334
+ abi: ERC20_ALLOWANCE_ABI,
335
+ functionName: "approve",
336
+ args: [spender, target],
337
+ account: state.walletAddress,
338
+ chain: base
339
+ });
340
+ const receipt = await publicClient.waitForTransactionReceipt({
341
+ hash,
342
+ confirmations: 1
343
+ });
344
+ if (receipt.status !== "success") {
345
+ throw new Error(`SurfLiquid USDC approval reverted (tx ${hash})`);
346
+ }
347
+ }
348
+ // --- IAgent: lifecycle ---
349
+ async disconnect() {
350
+ if (this.surf) {
351
+ await this.surf.disconnectWallet();
352
+ }
353
+ this.connectedAddress = null;
354
+ }
355
+ async activateAgent(state) {
356
+ await this.connect(state);
357
+ }
358
+ // --- IAgent: funds (user-pays; asset is always USDC, callback ignored) ---
359
+ async deposit(state, _chainId, amount, _asset, _depositCallback) {
360
+ const surf = await this.connect(state);
361
+ const human = formatUnits(BigInt(amount), SURFLIQUID_USDC_DECIMALS);
362
+ const smartWallet = await this.resolveVaultAddress(
363
+ surf,
364
+ state.walletAddress
365
+ );
366
+ await this.ensureVaultAllowance(state, smartWallet, BigInt(amount));
367
+ const tx = await surf.deposit({
368
+ asset: SURFLIQUID_USDC_ADDRESS,
369
+ amount: human
370
+ });
371
+ await tx.wait();
372
+ return { txHash: tx.hash, smartWallet, amount };
373
+ }
374
+ async withdraw(state, _chainId, _token, amount) {
375
+ const surf = await this.connect(state);
376
+ const human = amount != null ? formatUnits(BigInt(amount), SURFLIQUID_USDC_DECIMALS) : void 0;
377
+ try {
378
+ const tx = await surf.withdraw({
379
+ asset: SURFLIQUID_USDC_ADDRESS,
380
+ amount: human
381
+ });
382
+ await tx.wait();
383
+ return {
384
+ txHash: tx.hash,
385
+ type: amount != null ? "partial" : "full",
386
+ amount: amount ?? "0"
387
+ };
388
+ } catch (error) {
389
+ throw new OwneyError(
390
+ "WITHDRAW_FAILED",
391
+ error instanceof Error ? error.message : "SurfLiquid withdraw failed.",
392
+ { chainId: SURFLIQUID_CHAIN_ID, amount },
393
+ this.id
394
+ );
395
+ }
396
+ }
397
+ // --- IAgent: portfolio reads ---
398
+ async getBalances(state, chainId) {
399
+ const surf = await this.connect(state);
400
+ const vault = await surf.getVault(state.walletAddress);
401
+ const morphoVaultAddresses = (vault.assets ?? []).filter((asset) => asset.assetSymbol === "USDC" && asset.chainId === chainId).map((asset) => asset.morphoVaultAddress).filter((address) => Boolean(address));
402
+ const morphoStats = await fetchMorphoStatsByVault(
403
+ morphoVaultAddresses,
404
+ chainId
405
+ );
406
+ return mapBalances(vault, chainId, morphoStats);
407
+ }
408
+ async getEarnings(state) {
409
+ const surf = await this.connect(state);
410
+ const vault = await surf.getVault(state.walletAddress);
411
+ return mapEarnings(vault, vault.userVaultAddress ?? state.walletAddress);
412
+ }
413
+ async getAccountApy(state, _chainId, days, _tokenSymbol) {
414
+ const surf = await this.connect(state);
415
+ const vault = await surf.getVault(state.walletAddress);
416
+ return mapAccountApy(vault, days);
417
+ }
418
+ async getHistory(state, chainId, options) {
419
+ const surf = await this.connect(state);
420
+ const page = options?.cursor ? Number(options.cursor) : 1;
421
+ const limit = options?.limit ?? 10;
422
+ const result = await surf.getAgentMessages(
423
+ state.walletAddress,
424
+ page,
425
+ limit,
426
+ options?.fromDate,
427
+ options?.toDate
428
+ );
429
+ return mapHistory(result, chainId);
430
+ }
431
+ async getUserProfile(state) {
432
+ const surf = await this.connect(state);
433
+ const vault = await surf.getVault(state.walletAddress);
434
+ return mapUserProfile(vault, state.walletAddress);
435
+ }
436
+ // --- IAgent: discovery (no wallet) ---
437
+ async getAgentApy(days, _options) {
438
+ const surf = this.ensureSurf();
439
+ const assets = await surf.getSupportedAssets(SURFLIQUID_CHAIN_ID);
440
+ const usdc = assets.find((asset) => asset.assetSymbol === "USDC");
441
+ if (!usdc) return { averageApy: 0 };
442
+ const windowed = usdc[APY_WINDOW_KEY2[days]];
443
+ return { averageApy: windowed != null ? windowed : usdc.currentAPY };
444
+ }
445
+ };
446
+ export {
447
+ SurfLiquidAgent
448
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owney/sdk",
3
- "version": "0.6.9-beta.5",
3
+ "version": "0.6.9-beta.7",
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.41",
28
+ "ethers": "^6.17.0",
27
29
  "siwe": "^3.0.0",
28
30
  "viem": "^2.48.1"
29
31
  },