@owney/sdk 0.6.8-beta.3 → 0.6.9-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.
package/dist/index.d.cts CHANGED
@@ -34,7 +34,7 @@ type OwneySupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];
34
34
  type OwneySupportedChains = (typeof SUPPORTED_CHAINS)[number];
35
35
  type OwneySupportedTokens = (typeof SUPPORTED_TOKENS)[number];
36
36
 
37
- type AgentId = "zyfai" | "sail";
37
+ type AgentId = "zyfai" | "sail" | "surfliquid";
38
38
  type Asset = string;
39
39
  type AgentSupportedAsset = {
40
40
  readonly symbol: string;
@@ -108,6 +108,12 @@ interface OwneyDepositResult {
108
108
  }
109
109
  interface OwneyMultiDepositResult {
110
110
  agentResults: Record<string, OwneyDepositResult>;
111
+ /**
112
+ * Per-agent failure messages for agents that errored during a diversified
113
+ * deposit. Present only when at least one (but not all) agents failed —
114
+ * the deposit is partial, not total. Omitted when every agent succeeded.
115
+ */
116
+ agentErrors?: Record<string, string>;
111
117
  }
112
118
  interface AgentWithdrawResult {
113
119
  txHash?: string;
@@ -430,6 +436,17 @@ declare class OwneySDK {
430
436
  private hasExistingBalance;
431
437
  private validateAssetSupport;
432
438
  private getEligibleAgents;
439
+ /**
440
+ * Agent ids the routing API provisioned for this org that support the given
441
+ * chain + asset, ordered by preference ({@link AGENT_ELIGIBILITY_ORDER},
442
+ * surfliquid first). Returns `[]` when the org has no compatible agent — never
443
+ * throws on an empty org. Loads agent keys on first call (apiKey only, no
444
+ * wallet), so the UI can resolve which agent to use before the user connects.
445
+ *
446
+ * This is the source of truth for agent availability: an agent appears here
447
+ * iff the routing API returned its key. No per-app feature flags.
448
+ */
449
+ getEligibleAgentIds(chainId: number, asset: string): Promise<AgentId[]>;
433
450
  /**
434
451
  * Withdraw funds from a specific agent, or all agents that support the active chain+asset if agentId is omitted.
435
452
  * Validates that the asset is supported by the target agent(s) on the active chain.
@@ -525,7 +542,7 @@ declare class OwneySDK {
525
542
  getAllocationApy({ agentId, }?: AllocationApyOptions): Promise<OwneyAllocationApy>;
526
543
  }
527
544
 
528
- type OwneyErrorCode = "NOT_CONNECTED" | "NO_ACTIVE_CHAIN" | "WALLET_NO_ACCOUNTS" | "WALLET_ADDRESS_REQUIRED" | "AGENT_NOT_FOUND" | "AGENT_CHAIN_INCOMPATIBLE" | "AGENT_EMPTY_LIST" | "AGENT_DISABLED" | "CHAIN_UNSUPPORTED" | "CHAIN_NO_COMPATIBLE_AGENTS" | "ASSET_UNSUPPORTED" | "ASSET_NO_COMPATIBLE_AGENTS" | "DEPOSIT_AMOUNT_BELOW_MINIMUM" | "DEPOSIT_CALLBACK_REQUIRED" | "DEPOSIT_CALLBACK_INVALID" | "DEPOSIT_NO_PERMITTED_TOKENS" | "DEPOSIT_INSUFFICIENT_BALANCE" | "WITHDRAW_NO_PERMITTED_TOKENS" | "WITHDRAW_INSUFFICIENT_BALANCE" | "WITHDRAW_ALL_FAILED" | "WITHDRAW_PARTIAL_FAILURE" | "WITHDRAW_FAILED" | "API_ROUTING_ERROR" | "API_ROUTING_FAILED" | "API_SAIL_ERROR" | "API_SAIL_TIMEOUT" | "API_NO_AGENTS" | "SPONSOR_REQUEST_FAILED" | "PERMIT2_APPROVAL_REQUIRED" | "BALANCE_ALL_FAILED" | "ALLOCATION_ALL_FAILED" | "VALIDATION_INVALID_DAYS";
545
+ type OwneyErrorCode = "NOT_CONNECTED" | "NO_ACTIVE_CHAIN" | "WALLET_NO_ACCOUNTS" | "WALLET_ADDRESS_REQUIRED" | "AGENT_NOT_FOUND" | "AGENT_CHAIN_INCOMPATIBLE" | "AGENT_EMPTY_LIST" | "AGENT_DISABLED" | "CHAIN_UNSUPPORTED" | "CHAIN_NO_COMPATIBLE_AGENTS" | "ASSET_UNSUPPORTED" | "ASSET_NO_COMPATIBLE_AGENTS" | "DEPOSIT_AMOUNT_BELOW_MINIMUM" | "DEPOSIT_CALLBACK_REQUIRED" | "DEPOSIT_CALLBACK_INVALID" | "DEPOSIT_NO_PERMITTED_TOKENS" | "DEPOSIT_ALL_FAILED" | "DEPOSIT_INSUFFICIENT_BALANCE" | "WITHDRAW_NO_PERMITTED_TOKENS" | "WITHDRAW_INSUFFICIENT_BALANCE" | "WITHDRAW_ALL_FAILED" | "WITHDRAW_PARTIAL_FAILURE" | "WITHDRAW_FAILED" | "API_ROUTING_ERROR" | "API_ROUTING_FAILED" | "API_SAIL_ERROR" | "API_SAIL_TIMEOUT" | "API_NO_AGENTS" | "SPONSOR_REQUEST_FAILED" | "PERMIT2_APPROVAL_REQUIRED" | "BALANCE_ALL_FAILED" | "ALLOCATION_ALL_FAILED" | "VALIDATION_INVALID_DAYS";
529
546
  declare class OwneyError extends Error {
530
547
  readonly code: OwneyErrorCode;
531
548
  readonly details?: Record<string, unknown>;
package/dist/index.d.ts CHANGED
@@ -34,7 +34,7 @@ type OwneySupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];
34
34
  type OwneySupportedChains = (typeof SUPPORTED_CHAINS)[number];
35
35
  type OwneySupportedTokens = (typeof SUPPORTED_TOKENS)[number];
36
36
 
37
- type AgentId = "zyfai" | "sail";
37
+ type AgentId = "zyfai" | "sail" | "surfliquid";
38
38
  type Asset = string;
39
39
  type AgentSupportedAsset = {
40
40
  readonly symbol: string;
@@ -108,6 +108,12 @@ interface OwneyDepositResult {
108
108
  }
109
109
  interface OwneyMultiDepositResult {
110
110
  agentResults: Record<string, OwneyDepositResult>;
111
+ /**
112
+ * Per-agent failure messages for agents that errored during a diversified
113
+ * deposit. Present only when at least one (but not all) agents failed —
114
+ * the deposit is partial, not total. Omitted when every agent succeeded.
115
+ */
116
+ agentErrors?: Record<string, string>;
111
117
  }
112
118
  interface AgentWithdrawResult {
113
119
  txHash?: string;
@@ -430,6 +436,17 @@ declare class OwneySDK {
430
436
  private hasExistingBalance;
431
437
  private validateAssetSupport;
432
438
  private getEligibleAgents;
439
+ /**
440
+ * Agent ids the routing API provisioned for this org that support the given
441
+ * chain + asset, ordered by preference ({@link AGENT_ELIGIBILITY_ORDER},
442
+ * surfliquid first). Returns `[]` when the org has no compatible agent — never
443
+ * throws on an empty org. Loads agent keys on first call (apiKey only, no
444
+ * wallet), so the UI can resolve which agent to use before the user connects.
445
+ *
446
+ * This is the source of truth for agent availability: an agent appears here
447
+ * iff the routing API returned its key. No per-app feature flags.
448
+ */
449
+ getEligibleAgentIds(chainId: number, asset: string): Promise<AgentId[]>;
433
450
  /**
434
451
  * Withdraw funds from a specific agent, or all agents that support the active chain+asset if agentId is omitted.
435
452
  * Validates that the asset is supported by the target agent(s) on the active chain.
@@ -525,7 +542,7 @@ declare class OwneySDK {
525
542
  getAllocationApy({ agentId, }?: AllocationApyOptions): Promise<OwneyAllocationApy>;
526
543
  }
527
544
 
528
- type OwneyErrorCode = "NOT_CONNECTED" | "NO_ACTIVE_CHAIN" | "WALLET_NO_ACCOUNTS" | "WALLET_ADDRESS_REQUIRED" | "AGENT_NOT_FOUND" | "AGENT_CHAIN_INCOMPATIBLE" | "AGENT_EMPTY_LIST" | "AGENT_DISABLED" | "CHAIN_UNSUPPORTED" | "CHAIN_NO_COMPATIBLE_AGENTS" | "ASSET_UNSUPPORTED" | "ASSET_NO_COMPATIBLE_AGENTS" | "DEPOSIT_AMOUNT_BELOW_MINIMUM" | "DEPOSIT_CALLBACK_REQUIRED" | "DEPOSIT_CALLBACK_INVALID" | "DEPOSIT_NO_PERMITTED_TOKENS" | "DEPOSIT_INSUFFICIENT_BALANCE" | "WITHDRAW_NO_PERMITTED_TOKENS" | "WITHDRAW_INSUFFICIENT_BALANCE" | "WITHDRAW_ALL_FAILED" | "WITHDRAW_PARTIAL_FAILURE" | "WITHDRAW_FAILED" | "API_ROUTING_ERROR" | "API_ROUTING_FAILED" | "API_SAIL_ERROR" | "API_SAIL_TIMEOUT" | "API_NO_AGENTS" | "SPONSOR_REQUEST_FAILED" | "PERMIT2_APPROVAL_REQUIRED" | "BALANCE_ALL_FAILED" | "ALLOCATION_ALL_FAILED" | "VALIDATION_INVALID_DAYS";
545
+ type OwneyErrorCode = "NOT_CONNECTED" | "NO_ACTIVE_CHAIN" | "WALLET_NO_ACCOUNTS" | "WALLET_ADDRESS_REQUIRED" | "AGENT_NOT_FOUND" | "AGENT_CHAIN_INCOMPATIBLE" | "AGENT_EMPTY_LIST" | "AGENT_DISABLED" | "CHAIN_UNSUPPORTED" | "CHAIN_NO_COMPATIBLE_AGENTS" | "ASSET_UNSUPPORTED" | "ASSET_NO_COMPATIBLE_AGENTS" | "DEPOSIT_AMOUNT_BELOW_MINIMUM" | "DEPOSIT_CALLBACK_REQUIRED" | "DEPOSIT_CALLBACK_INVALID" | "DEPOSIT_NO_PERMITTED_TOKENS" | "DEPOSIT_ALL_FAILED" | "DEPOSIT_INSUFFICIENT_BALANCE" | "WITHDRAW_NO_PERMITTED_TOKENS" | "WITHDRAW_INSUFFICIENT_BALANCE" | "WITHDRAW_ALL_FAILED" | "WITHDRAW_PARTIAL_FAILURE" | "WITHDRAW_FAILED" | "API_ROUTING_ERROR" | "API_ROUTING_FAILED" | "API_SAIL_ERROR" | "API_SAIL_TIMEOUT" | "API_NO_AGENTS" | "SPONSOR_REQUEST_FAILED" | "PERMIT2_APPROVAL_REQUIRED" | "BALANCE_ALL_FAILED" | "ALLOCATION_ALL_FAILED" | "VALIDATION_INVALID_DAYS";
529
546
  declare class OwneyError extends Error {
530
547
  readonly code: OwneyErrorCode;
531
548
  readonly details?: Record<string, unknown>;
package/dist/index.js CHANGED
@@ -1,3 +1,10 @@
1
+ import {
2
+ AgentChainIncompatibleError,
3
+ AgentNotFoundError,
4
+ NotConnectedError,
5
+ OwneyError
6
+ } from "./chunk-GMNQBWUB.js";
7
+
1
8
  // src/agents/zyfai/zyfai.agent.ts
2
9
  import { ZyfaiSDK } from "@zyfai/sdk";
3
10
  import { createPublicClient, http } from "viem";
@@ -56,55 +63,6 @@ var SupportedAssets = [
56
63
  }
57
64
  ];
58
65
 
59
- // src/errors.ts
60
- var OwneyError = class extends Error {
61
- code;
62
- details;
63
- agentId;
64
- constructor(code, message, details, agentId) {
65
- const prefix = agentId ? `[${code}][agent:${agentId}]` : `[${code}]`;
66
- super(`${prefix} ${message}`);
67
- this.name = "OwneyError";
68
- this.code = code;
69
- this.details = details;
70
- this.agentId = agentId;
71
- }
72
- };
73
- var AgentNotFoundError = class extends OwneyError {
74
- constructor(agentId, available) {
75
- super(
76
- "AGENT_NOT_FOUND",
77
- `Unknown agent "${agentId}". Available agents: ${available.join(", ")}`,
78
- { agentId, available },
79
- agentId
80
- );
81
- this.name = "AgentNotFoundError";
82
- }
83
- };
84
- var NotConnectedError = class extends OwneyError {
85
- constructor() {
86
- super("NOT_CONNECTED", "Not connected. Call sdk.connect(provider) first.");
87
- this.name = "NotConnectedError";
88
- }
89
- };
90
- var AgentChainIncompatibleError = class extends OwneyError {
91
- incompatibleAgents;
92
- connectedChainId;
93
- constructor(incompatibleAgents, connectedChainId) {
94
- const details = incompatibleAgents.map(
95
- ({ agentId, supportedChainIds }) => `"${agentId}" supports chains [${supportedChainIds.join(", ")}]`
96
- ).join("; ");
97
- super(
98
- "AGENT_CHAIN_INCOMPATIBLE",
99
- `Chain ${connectedChainId} is not supported by the following agents: ${details}`,
100
- { incompatibleAgents, connectedChainId }
101
- );
102
- this.name = "AgentChainIncompatibleError";
103
- this.incompatibleAgents = incompatibleAgents;
104
- this.connectedChainId = connectedChainId;
105
- }
106
- };
107
-
108
66
  // src/lib/utils.ts
109
67
  var isValidChainId = (chainId) => {
110
68
  if (!SUPPORTED_CHAIN_IDS.includes(chainId)) {
@@ -179,46 +137,46 @@ function resolveChainId(chain) {
179
137
  function mapBalances(raw, _chainId, smartWallet) {
180
138
  const portfolio = raw.portfolio;
181
139
  const portfolioByChain = portfolio.portfolioByChain ?? {};
140
+ const rawPositions = portfolio.positions ?? [];
141
+ const detailByKey = /* @__PURE__ */ new Map();
142
+ for (const p of rawPositions) {
143
+ const cid = resolveChainId(p.chain ?? "");
144
+ const symbol = (p.token_symbol ?? "").toUpperCase();
145
+ if (Number.isFinite(cid) && symbol) detailByKey.set(`${cid}:${symbol}`, p);
146
+ }
182
147
  let totalBalance = 0;
183
148
  const tokens = [];
149
+ const positions = [];
184
150
  for (const [chainIdKey, tokensBySymbol] of Object.entries(portfolioByChain)) {
185
151
  const positionChainId = Number(chainIdKey);
152
+ const chainName = CHAIN_ID_TO_NAME[positionChainId] ?? "BASE";
186
153
  for (const [symbol, { balance, decimals }] of Object.entries(
187
154
  tokensBySymbol ?? {}
188
155
  )) {
189
- const amount = hexToDecimal(balance || "0", decimals);
156
+ const amount = hexToDecimal(balance || "0", tokenDecimals(symbol, decimals));
190
157
  totalBalance += amount;
191
158
  tokens.push({
192
- chain: CHAIN_ID_TO_NAME[positionChainId] ?? "BASE",
159
+ chain: chainName,
193
160
  chainId: positionChainId,
194
161
  asset: symbol,
195
162
  amount: String(amount)
196
163
  });
164
+ const detail = detailByKey.get(`${positionChainId}:${symbol.toUpperCase()}`);
165
+ positions.push({
166
+ chain: chainName,
167
+ protocol: detail?.protocol_name ?? detail?.protocol_id ?? "",
168
+ protocolId: detail?.protocol_id,
169
+ pool: detail?.pool,
170
+ asset: symbol,
171
+ amount: String(amount),
172
+ apy: detail?.pool_apy,
173
+ tvl: detail?.pool_tvl,
174
+ // PositionSlot has no `liquidity` field yet; Zyfai will add it. Narrow
175
+ // structural read keeps it undefined today and auto-populates later.
176
+ liquidity: detail?.liquidity
177
+ });
197
178
  }
198
179
  }
199
- const positions = (portfolio.positions ?? []).map((p) => ({
200
- chain: p.chain ?? "",
201
- protocol: p.protocol_name ?? p.protocol_id ?? "",
202
- protocolId: p.protocol_id,
203
- pool: p.pool,
204
- asset: p.token_symbol ?? "",
205
- // Position amount is hex-encoded base units (like the token balances
206
- // above). `PositionSlot` doesn't type a `decimals` field, but runtime
207
- // getBalances payloads often carry one (e.g. 18 for WETH) — prefer that
208
- // when present, otherwise fall back to the per-symbol lookup so
209
- // non-6-decimal assets like WETH don't render 1e12 too large.
210
- amount: String(
211
- hexToDecimal(
212
- p.amount || "0",
213
- tokenDecimals(p.token_symbol, p.decimals)
214
- )
215
- ),
216
- apy: p.pool_apy,
217
- tvl: p.pool_tvl,
218
- // PositionSlot has no `liquidity` field yet; Zyfai will add it. Narrow
219
- // structural read keeps it undefined today and auto-populates later.
220
- liquidity: p.liquidity
221
- }));
222
180
  return {
223
181
  smartWallet,
224
182
  totalBalance: String(totalBalance),
@@ -1755,6 +1713,7 @@ var VIEM_CHAIN2 = {
1755
1713
  42161: arbitrum2,
1756
1714
  1: mainnet2
1757
1715
  };
1716
+ var AGENT_ELIGIBILITY_ORDER = ["surfliquid", "zyfai", "sail"];
1758
1717
  var SPONSORED_WETH_BY_CHAIN = {
1759
1718
  8453: "0x4200000000000000000000000000000000000006",
1760
1719
  42161: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
@@ -1949,8 +1908,8 @@ var OwneySDK = class {
1949
1908
  this.initializingAgentsPromise = (async () => {
1950
1909
  const agentKeys = await fetchAgentKeys(this.apiKey);
1951
1910
  this.disabledAgents.clear();
1952
- for (const { key, agent_type, is_enabled } of agentKeys) {
1953
- const agent = this.createAgent(agent_type, key);
1911
+ for (const { key, agent_type, project_name, is_enabled } of agentKeys) {
1912
+ const agent = await this.createAgent(agent_type, key, project_name);
1954
1913
  if (!agent) continue;
1955
1914
  this.agents.set(agent_type, agent);
1956
1915
  if (is_enabled === false) {
@@ -1971,10 +1930,15 @@ var OwneySDK = class {
1971
1930
  this.initializingAgentsPromise = null;
1972
1931
  }
1973
1932
  }
1974
- createAgent(agentId, key) {
1933
+ async createAgent(agentId, key, projectName) {
1975
1934
  if (agentId === "zyfai") {
1976
1935
  return new ZyfaiAgent(key, this.zyfaiRpcUrls, this.referralSource);
1977
1936
  }
1937
+ if (agentId === "surfliquid") {
1938
+ if (!projectName) return null;
1939
+ const { SurfLiquidAgent } = await import("./surfliquid.agent-OMOYXWLP.js");
1940
+ return new SurfLiquidAgent({ projectName, appId: key });
1941
+ }
1978
1942
  return null;
1979
1943
  }
1980
1944
  // --- Account lifecycle ---
@@ -2127,18 +2091,30 @@ var OwneySDK = class {
2127
2091
  );
2128
2092
  }
2129
2093
  const agentResults = {};
2094
+ const agentErrors = {};
2130
2095
  for (const { agent, amount: agentAmount } of agentAmounts) {
2131
- agentResults[agent.id] = await this.depositWithFallback(
2132
- agent,
2133
- state,
2134
- chainId,
2135
- agentAmount,
2136
- asset,
2137
- effectiveCallback,
2138
- depositCallback
2096
+ try {
2097
+ agentResults[agent.id] = await this.depositWithFallback(
2098
+ agent,
2099
+ state,
2100
+ chainId,
2101
+ agentAmount,
2102
+ asset,
2103
+ effectiveCallback,
2104
+ depositCallback
2105
+ );
2106
+ } catch (error) {
2107
+ agentErrors[agent.id] = error instanceof Error ? error.message : String(error);
2108
+ }
2109
+ }
2110
+ if (Object.keys(agentResults).length === 0) {
2111
+ throw new OwneyError(
2112
+ "DEPOSIT_ALL_FAILED",
2113
+ `All ${agentAmounts.length} agent deposit(s) failed.`,
2114
+ { agentErrors }
2139
2115
  );
2140
2116
  }
2141
- return { agentResults };
2117
+ return Object.keys(agentErrors).length > 0 ? { agentResults, agentErrors } : { agentResults };
2142
2118
  }
2143
2119
  /**
2144
2120
  * Invokes `agent.deposit` with the resolved sponsored callback, composing
@@ -2295,6 +2271,34 @@ var OwneySDK = class {
2295
2271
  }
2296
2272
  return eligible;
2297
2273
  }
2274
+ /**
2275
+ * Agent ids the routing API provisioned for this org that support the given
2276
+ * chain + asset, ordered by preference ({@link AGENT_ELIGIBILITY_ORDER},
2277
+ * surfliquid first). Returns `[]` when the org has no compatible agent — never
2278
+ * throws on an empty org. Loads agent keys on first call (apiKey only, no
2279
+ * wallet), so the UI can resolve which agent to use before the user connects.
2280
+ *
2281
+ * This is the source of truth for agent availability: an agent appears here
2282
+ * iff the routing API returned its key. No per-app feature flags.
2283
+ */
2284
+ async getEligibleAgentIds(chainId, asset) {
2285
+ try {
2286
+ await this.ensureAgentsInitialized();
2287
+ } catch (error) {
2288
+ if (error instanceof OwneyError && error.code === "API_NO_AGENTS") {
2289
+ return [];
2290
+ }
2291
+ throw error;
2292
+ }
2293
+ return [...this.agents.values()].filter((agent) => {
2294
+ const chainAssets = agent.supportedAssets.find(
2295
+ (sa) => sa.chainId === chainId
2296
+ );
2297
+ return chainAssets?.assets.some((a) => a.symbol === asset) ?? false;
2298
+ }).map((agent) => agent.id).sort(
2299
+ (a, b) => AGENT_ELIGIBILITY_ORDER.indexOf(a) - AGENT_ELIGIBILITY_ORDER.indexOf(b)
2300
+ );
2301
+ }
2298
2302
  // --- Fund operations ---
2299
2303
  /**
2300
2304
  * Withdraw funds from a specific agent, or all agents that support the active chain+asset if agentId is omitted.
@@ -2330,9 +2334,17 @@ var OwneySDK = class {
2330
2334
  }
2331
2335
  const eligibleAgents = this.getEligibleAgents(chainId, asset);
2332
2336
  if (!amount) {
2337
+ const aggregated2 = await this.getBalances();
2338
+ const funded = projectAgentBalancesForAsset(
2339
+ eligibleAgents,
2340
+ aggregated2.agentBalances,
2341
+ chainId,
2342
+ asset,
2343
+ assetInfo.decimals
2344
+ ).filter((b) => b.balance > 0n);
2333
2345
  const results2 = {};
2334
2346
  const agentErrors2 = {};
2335
- for (const agent of eligibleAgents) {
2347
+ for (const { agent } of funded) {
2336
2348
  try {
2337
2349
  results2[agent.id] = await agent.withdraw(state, chainId, token);
2338
2350
  } catch (err) {
@@ -2349,9 +2361,10 @@ var OwneySDK = class {
2349
2361
  { asset, agentErrors: agentErrors2 }
2350
2362
  );
2351
2363
  }
2364
+ const totalWithdrawn = funded.filter(({ agent }) => results2[agent.id] !== void 0).reduce((sum, { balance }) => sum + balance, 0n);
2352
2365
  return {
2353
2366
  agentResult: results2,
2354
- totalWithdrawn: sumWithdrawnAmount(results2).toString()
2367
+ totalWithdrawn: totalWithdrawn.toString()
2355
2368
  };
2356
2369
  }
2357
2370
  const requested = BigInt(amount);