@zyfai/sdk 0.10.0 → 0.12.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 +51 -1
- package/dist/index.d.mts +424 -25
- package/dist/index.d.ts +424 -25
- package/dist/index.js +889 -27
- package/dist/index.mjs +890 -27
- package/package.json +2 -1
package/dist/index.mjs
CHANGED
|
@@ -54,10 +54,15 @@ var ENDPOINTS = {
|
|
|
54
54
|
USER_WITHDRAW: "/users/withdraw/v2",
|
|
55
55
|
PARTIAL_WITHDRAW: "/users/partial-withdraw/v2",
|
|
56
56
|
LOG_DEPOSIT: "/users/log_deposit/v2",
|
|
57
|
+
FUNDING_ORDERS: "/users/me/funding-orders",
|
|
58
|
+
FUNDING_ORDER: (orderId) => `/users/me/funding-orders/${encodeURIComponent(orderId)}`,
|
|
59
|
+
FUNDING_ORDER_QUOTE: (orderId) => `/users/me/funding-orders/${encodeURIComponent(orderId)}/quote`,
|
|
60
|
+
FUNDING_ORDER_EXECUTION: (orderId) => `/users/me/funding-orders/${encodeURIComponent(orderId)}/execution`,
|
|
57
61
|
DEPOSIT_STATUS: (depositId) => `/users/deposits/${depositId}/v2`,
|
|
58
62
|
WITHDRAW_STATUS: (withdrawalId) => `/users/withdrawals/${withdrawalId}`,
|
|
59
63
|
// Safe Deployment (single endpoint)
|
|
60
64
|
SAFE_DEPLOY: "/users/safe-deploy",
|
|
65
|
+
RZFI_CLAIM: "/users/rzfi-claim",
|
|
61
66
|
// Multichain deploy for predeployed (pool) wallets — deploys + rotates the
|
|
62
67
|
// same address on the requested chains (sponsored, no user signature).
|
|
63
68
|
DEPLOY_CHAINS: "/users/deploy-chains",
|
|
@@ -109,6 +114,8 @@ var ENDPOINTS = {
|
|
|
109
114
|
CUSTOMIZATION_SELECTED_POOLS: (protocolId, chainId) => `/customization/selected-pools?protocolId=${protocolId}&chainId=${chainId}`
|
|
110
115
|
};
|
|
111
116
|
var DATA_ENDPOINTS = {
|
|
117
|
+
// Merkl incentive campaigns
|
|
118
|
+
MERKL_CAMPAIGN_INFO: (campaign) => `/merkl/${campaign}/campaign-info`,
|
|
112
119
|
// User Initialization
|
|
113
120
|
USER_INITIALIZE: "/api/earnings/initialize",
|
|
114
121
|
// Earnings
|
|
@@ -485,6 +492,15 @@ var ERC20_ABI = [
|
|
|
485
492
|
outputs: [{ name: "", type: "uint256" }]
|
|
486
493
|
}
|
|
487
494
|
];
|
|
495
|
+
var WETH_DEPOSIT_ABI = [
|
|
496
|
+
{
|
|
497
|
+
name: "deposit",
|
|
498
|
+
type: "function",
|
|
499
|
+
stateMutability: "payable",
|
|
500
|
+
inputs: [],
|
|
501
|
+
outputs: []
|
|
502
|
+
}
|
|
503
|
+
];
|
|
488
504
|
var ERC20_TRANSFER_LEGACY_ABI = [
|
|
489
505
|
{
|
|
490
506
|
name: "transfer",
|
|
@@ -679,9 +695,9 @@ function nextWithdrawCompleteDeadline(startedAt, previousDeadline, estimatedClai
|
|
|
679
695
|
var AGENT_DEPOSIT_INTENT_INTERVAL_MS = 1500;
|
|
680
696
|
var AGENT_DEPOSIT_INTENT_TIMEOUT_MS = 30 * 60 * 1e3;
|
|
681
697
|
var formatMinPortfolioLabel = (raw, decimals, symbol) => {
|
|
682
|
-
const
|
|
683
|
-
const whole = raw /
|
|
684
|
-
const fraction = raw %
|
|
698
|
+
const base3 = 10n ** BigInt(decimals);
|
|
699
|
+
const whole = raw / base3;
|
|
700
|
+
const fraction = raw % base3;
|
|
685
701
|
if (fraction === 0n) {
|
|
686
702
|
return `${whole.toString()} ${symbol}`;
|
|
687
703
|
}
|
|
@@ -740,8 +756,10 @@ import {
|
|
|
740
756
|
custom,
|
|
741
757
|
http as http2,
|
|
742
758
|
getAddress as getAddress2,
|
|
743
|
-
encodeFunctionData
|
|
759
|
+
encodeFunctionData,
|
|
760
|
+
defineChain
|
|
744
761
|
} from "viem";
|
|
762
|
+
import { execute } from "@relayprotocol/relay-sdk";
|
|
745
763
|
|
|
746
764
|
// src/config/chains.ts
|
|
747
765
|
import { createPublicClient, http } from "viem";
|
|
@@ -936,6 +954,233 @@ var getSupportedChainIds = () => {
|
|
|
936
954
|
return Object.keys(CHAINS).map(Number);
|
|
937
955
|
};
|
|
938
956
|
|
|
957
|
+
// src/deposits/deposit-route.ts
|
|
958
|
+
var NATIVE_CURRENCY = "0x0000000000000000000000000000000000000000";
|
|
959
|
+
var RELAY_DESTINATION_ASSETS = [
|
|
960
|
+
"USDC",
|
|
961
|
+
"WETH",
|
|
962
|
+
"CBBTC",
|
|
963
|
+
"WBTC",
|
|
964
|
+
"EURC",
|
|
965
|
+
"USDT",
|
|
966
|
+
"PYUSD",
|
|
967
|
+
"NVDAC",
|
|
968
|
+
"GOOGLC",
|
|
969
|
+
"AAPLC",
|
|
970
|
+
"METAC"
|
|
971
|
+
];
|
|
972
|
+
var lookupCollateral = (asset) => Object.keys(ASSET_CONFIGS).find(
|
|
973
|
+
(key) => key.toLowerCase() === asset.toLowerCase()
|
|
974
|
+
) ?? null;
|
|
975
|
+
var toRelayDestinationAsset = (asset) => asset.trim().toUpperCase();
|
|
976
|
+
var isNativeSpendToken = (token) => {
|
|
977
|
+
const value = token.trim().toLowerCase();
|
|
978
|
+
return value === "eth" || value === "native" || value === NATIVE_CURRENCY;
|
|
979
|
+
};
|
|
980
|
+
var isSameCollateralToken = (spend, collateral, chainId) => {
|
|
981
|
+
if (spend.toLowerCase() === collateral.toLowerCase()) return true;
|
|
982
|
+
const address = ASSET_CONFIGS[collateral]?.addresses?.[chainId];
|
|
983
|
+
return !!address && spend.toLowerCase() === address.toLowerCase();
|
|
984
|
+
};
|
|
985
|
+
var originCurrencyForSpend = (spend, chainId) => {
|
|
986
|
+
if (isNativeSpendToken(spend)) return NATIVE_CURRENCY;
|
|
987
|
+
if (/^0x[0-9a-fA-F]{40}$/.test(spend)) return spend;
|
|
988
|
+
const collateral = lookupCollateral(spend);
|
|
989
|
+
if (!collateral) {
|
|
990
|
+
throw new Error(
|
|
991
|
+
`spendToken must be a collateral symbol or a token contract address. Received "${spend}".`
|
|
992
|
+
);
|
|
993
|
+
}
|
|
994
|
+
const address = ASSET_CONFIGS[collateral]?.addresses?.[chainId];
|
|
995
|
+
if (!address) {
|
|
996
|
+
throw new Error(`${collateral} is not available on chain ${chainId}.`);
|
|
997
|
+
}
|
|
998
|
+
return address;
|
|
999
|
+
};
|
|
1000
|
+
var resolveDepositRoute = (input) => {
|
|
1001
|
+
const asset = input.asset?.trim();
|
|
1002
|
+
if (!asset) throw new Error("Asset is required");
|
|
1003
|
+
const spendChainId = input.spendChainId ?? input.chainId;
|
|
1004
|
+
const collateral = lookupCollateral(asset);
|
|
1005
|
+
const spend = input.spendToken?.trim();
|
|
1006
|
+
const holdsDestinationCollateral = !spend || spendChainId === input.chainId && !!collateral && isSameCollateralToken(spend, collateral, input.chainId);
|
|
1007
|
+
if (holdsDestinationCollateral) {
|
|
1008
|
+
if (!collateral) {
|
|
1009
|
+
throw new Error(
|
|
1010
|
+
`${asset} cannot be transferred directly. Pass spendToken to swap another token into it.`
|
|
1011
|
+
);
|
|
1012
|
+
}
|
|
1013
|
+
const chains = getAssetChainIds(collateral);
|
|
1014
|
+
if (!chains.includes(input.chainId)) {
|
|
1015
|
+
throw new Error(
|
|
1016
|
+
`${collateral} is not available on chain ${input.chainId}. Supported chains: ${chains.join(", ")}.`
|
|
1017
|
+
);
|
|
1018
|
+
}
|
|
1019
|
+
return { kind: "direct", asset: collateral };
|
|
1020
|
+
}
|
|
1021
|
+
if (collateral === "WETH" && spendChainId === input.chainId && spend && isNativeSpendToken(spend)) {
|
|
1022
|
+
return { kind: "wrap", asset: "WETH" };
|
|
1023
|
+
}
|
|
1024
|
+
const destinationAsset = toRelayDestinationAsset(asset);
|
|
1025
|
+
if (!RELAY_DESTINATION_ASSETS.includes(
|
|
1026
|
+
destinationAsset
|
|
1027
|
+
)) {
|
|
1028
|
+
throw new Error(
|
|
1029
|
+
`${asset} is not a collateral Relay can deliver. Supported: ${RELAY_DESTINATION_ASSETS.join(", ")}.`
|
|
1030
|
+
);
|
|
1031
|
+
}
|
|
1032
|
+
return {
|
|
1033
|
+
kind: "swap",
|
|
1034
|
+
originChainId: spendChainId,
|
|
1035
|
+
originCurrency: originCurrencyForSpend(spend, spendChainId),
|
|
1036
|
+
destinationAsset
|
|
1037
|
+
};
|
|
1038
|
+
};
|
|
1039
|
+
|
|
1040
|
+
// src/deposits/funding-order-route.ts
|
|
1041
|
+
var sameText = (left, right) => typeof left === "string" && left.trim().toLowerCase() === right.trim().toLowerCase();
|
|
1042
|
+
var assertStoredFundingOrderRoute = (order, requested) => {
|
|
1043
|
+
const mismatches = [];
|
|
1044
|
+
if (order.originChainId !== requested.originChainId) {
|
|
1045
|
+
mismatches.push(
|
|
1046
|
+
`originChainId caller ${requested.originChainId}, stored ${order.originChainId}`
|
|
1047
|
+
);
|
|
1048
|
+
}
|
|
1049
|
+
if (!sameText(order.originCurrency, requested.originCurrency)) {
|
|
1050
|
+
mismatches.push(
|
|
1051
|
+
`originCurrency caller ${requested.originCurrency}, stored ${order.originCurrency}`
|
|
1052
|
+
);
|
|
1053
|
+
}
|
|
1054
|
+
if (order.destinationChainId !== requested.destinationChainId) {
|
|
1055
|
+
mismatches.push(
|
|
1056
|
+
`destinationChainId caller ${requested.destinationChainId}, stored ${order.destinationChainId}`
|
|
1057
|
+
);
|
|
1058
|
+
}
|
|
1059
|
+
if (!sameText(order.destinationAsset, requested.destinationAsset)) {
|
|
1060
|
+
mismatches.push(
|
|
1061
|
+
`destinationAsset caller ${requested.destinationAsset}, stored ${order.destinationAsset}`
|
|
1062
|
+
);
|
|
1063
|
+
}
|
|
1064
|
+
if (mismatches.length === 0) return;
|
|
1065
|
+
throw new Error(
|
|
1066
|
+
`Funding order ${order.id} does not match this swap: ${mismatches.join("; ")}`
|
|
1067
|
+
);
|
|
1068
|
+
};
|
|
1069
|
+
|
|
1070
|
+
// src/deposits/collateral-minimum.ts
|
|
1071
|
+
var positiveUnits = (value) => {
|
|
1072
|
+
if (!value || value === "0") return null;
|
|
1073
|
+
return value;
|
|
1074
|
+
};
|
|
1075
|
+
var resolveCollateralMinimum = (storedMinimum, quote) => positiveUnits(storedMinimum) ?? positiveUnits(quote.details?.currencyOut?.minimumAmount) ?? positiveUnits(quote.details?.currencyOut?.amount) ?? "0";
|
|
1076
|
+
|
|
1077
|
+
// src/deposits/relay-slippage.ts
|
|
1078
|
+
var DEFAULT_RELAY_SLIPPAGE_BPS = 200;
|
|
1079
|
+
var MAX_RELAY_SLIPPAGE_BPS = 500;
|
|
1080
|
+
var RELAY_SLIPPAGE_PRESETS_BPS = [50, 200, 500];
|
|
1081
|
+
var resolveRelaySlippageBps = (clientBps) => {
|
|
1082
|
+
if (clientBps == null || !Number.isFinite(clientBps)) {
|
|
1083
|
+
return DEFAULT_RELAY_SLIPPAGE_BPS;
|
|
1084
|
+
}
|
|
1085
|
+
return Math.min(
|
|
1086
|
+
Math.max(1, Math.trunc(clientBps)),
|
|
1087
|
+
MAX_RELAY_SLIPPAGE_BPS
|
|
1088
|
+
);
|
|
1089
|
+
};
|
|
1090
|
+
|
|
1091
|
+
// src/deposits/relay-client.ts
|
|
1092
|
+
import {
|
|
1093
|
+
MAINNET_RELAY_API,
|
|
1094
|
+
convertViemChainToRelayChain,
|
|
1095
|
+
createClient,
|
|
1096
|
+
getClient
|
|
1097
|
+
} from "@relayprotocol/relay-sdk";
|
|
1098
|
+
import { arbitrum as arbitrum2, base as base2, mainnet as mainnet2 } from "viem/chains";
|
|
1099
|
+
var RELAY_FUNDING_CHAIN_IDS = [mainnet2.id, base2.id, arbitrum2.id];
|
|
1100
|
+
var clientHasFundingChains = () => {
|
|
1101
|
+
const client = getClient();
|
|
1102
|
+
if (!client?.baseApiUrl) return false;
|
|
1103
|
+
return RELAY_FUNDING_CHAIN_IDS.every(
|
|
1104
|
+
(chainId) => client.chains.some((chain) => chain.id === chainId)
|
|
1105
|
+
);
|
|
1106
|
+
};
|
|
1107
|
+
var ensureRelaySdkClient = () => {
|
|
1108
|
+
if (clientHasFundingChains()) return;
|
|
1109
|
+
createClient({
|
|
1110
|
+
baseApiUrl: MAINNET_RELAY_API,
|
|
1111
|
+
source: "zyf.ai",
|
|
1112
|
+
chains: [mainnet2, base2, arbitrum2].map(convertViemChainToRelayChain)
|
|
1113
|
+
});
|
|
1114
|
+
};
|
|
1115
|
+
|
|
1116
|
+
// src/deposits/relay-fill.ts
|
|
1117
|
+
var TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
|
|
1118
|
+
var collectTxHashes = (execution) => {
|
|
1119
|
+
const out = [];
|
|
1120
|
+
for (const step of execution.steps ?? []) {
|
|
1121
|
+
for (const item of step.items ?? []) {
|
|
1122
|
+
for (const row of item.txHashes ?? []) {
|
|
1123
|
+
if (row.txHash) out.push(row);
|
|
1124
|
+
}
|
|
1125
|
+
for (const row of item.internalTxHashes ?? []) {
|
|
1126
|
+
if (row.txHash) out.push(row);
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
return out;
|
|
1131
|
+
};
|
|
1132
|
+
var collectRelaySourceTxHashes = (execution, originChainId) => {
|
|
1133
|
+
const hashes = /* @__PURE__ */ new Set();
|
|
1134
|
+
for (const row of collectTxHashes(execution)) {
|
|
1135
|
+
if (row.chainId === originChainId) hashes.add(row.txHash);
|
|
1136
|
+
}
|
|
1137
|
+
return [...hashes];
|
|
1138
|
+
};
|
|
1139
|
+
var collectRelayDestinationTxHashes = (execution, destinationChainId) => {
|
|
1140
|
+
const hashes = /* @__PURE__ */ new Set();
|
|
1141
|
+
for (const row of collectTxHashes(execution)) {
|
|
1142
|
+
if (row.chainId === destinationChainId && row.txHash) {
|
|
1143
|
+
hashes.add(row.txHash);
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
return [...hashes];
|
|
1147
|
+
};
|
|
1148
|
+
var transferAmountTo = (logs, token, recipient) => {
|
|
1149
|
+
const tokenAddr = token.toLowerCase();
|
|
1150
|
+
const recipientAddr = recipient.toLowerCase();
|
|
1151
|
+
let total = 0n;
|
|
1152
|
+
for (const log of logs) {
|
|
1153
|
+
if (log.address.toLowerCase() !== tokenAddr) continue;
|
|
1154
|
+
if (log.topics[0]?.toLowerCase() !== TRANSFER_TOPIC) continue;
|
|
1155
|
+
const toTopic = log.topics[2];
|
|
1156
|
+
if (!toTopic) continue;
|
|
1157
|
+
const to = `0x${toTopic.slice(-40)}`.toLowerCase();
|
|
1158
|
+
if (to !== recipientAddr) continue;
|
|
1159
|
+
try {
|
|
1160
|
+
const value = BigInt(log.data);
|
|
1161
|
+
if (value > 0n) total += value;
|
|
1162
|
+
} catch {
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
return total;
|
|
1166
|
+
};
|
|
1167
|
+
var receiptTransfersTokenTo = (logs, token, recipient) => transferAmountTo(logs, token, recipient) > 0n;
|
|
1168
|
+
var selectRelayCreditTxHash = (params) => {
|
|
1169
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1170
|
+
for (const hash of params.candidates) {
|
|
1171
|
+
if (!hash) continue;
|
|
1172
|
+
const key = hash.toLowerCase();
|
|
1173
|
+
if (seen.has(key)) continue;
|
|
1174
|
+
seen.add(key);
|
|
1175
|
+
const receipt = params.receipts.get(key);
|
|
1176
|
+
if (!receipt || receipt.status !== "success") continue;
|
|
1177
|
+
if (receiptTransfersTokenTo(receipt.logs, params.token, params.recipient)) {
|
|
1178
|
+
return hash;
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
return null;
|
|
1182
|
+
};
|
|
1183
|
+
|
|
939
1184
|
// src/config/managed-assets.ts
|
|
940
1185
|
var MANAGED_ASSET_ORDER = [
|
|
941
1186
|
"USDC",
|
|
@@ -1764,6 +2009,13 @@ var AgentDepositIntentTimeoutError = class extends Error {
|
|
|
1764
2009
|
this.name = "AgentDepositIntentTimeoutError";
|
|
1765
2010
|
}
|
|
1766
2011
|
};
|
|
2012
|
+
var thrownMessage = (error) => {
|
|
2013
|
+
if (error instanceof Error) return error.message;
|
|
2014
|
+
if (error && typeof error === "object" && "message" in error && typeof error.message === "string") {
|
|
2015
|
+
return error.message;
|
|
2016
|
+
}
|
|
2017
|
+
return String(error);
|
|
2018
|
+
};
|
|
1767
2019
|
var _ZyfaiSDK = class _ZyfaiSDK {
|
|
1768
2020
|
/**
|
|
1769
2021
|
* Create an SDK instance bound to a partner API key.
|
|
@@ -2950,14 +3202,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2950
3202
|
effectiveChains,
|
|
2951
3203
|
withPools,
|
|
2952
3204
|
strategy,
|
|
2953
|
-
mandateChainId
|
|
3205
|
+
mandateChainId,
|
|
3206
|
+
existingChains
|
|
2954
3207
|
);
|
|
2955
3208
|
}
|
|
2956
3209
|
/**
|
|
2957
3210
|
* Persist protocol discovery for one asset (user PATCH or agent deposit-setup).
|
|
2958
3211
|
* @internal
|
|
2959
3212
|
*/
|
|
2960
|
-
async persistDiscoveredAssetProfile(asset, effectiveChains, withPools, strategy, agentDepositChainId) {
|
|
3213
|
+
async persistDiscoveredAssetProfile(asset, effectiveChains, withPools, strategy, agentDepositChainId, existingChains = []) {
|
|
2961
3214
|
const internalAsset = convertAssetInternally(asset);
|
|
2962
3215
|
const assetSettings = {
|
|
2963
3216
|
chains: effectiveChains,
|
|
@@ -2966,9 +3219,18 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2966
3219
|
if (strategy !== void 0) {
|
|
2967
3220
|
assetSettings.rebalanceStrategy = toInternalStrategy(strategy);
|
|
2968
3221
|
}
|
|
3222
|
+
const configureProfile = () => this.updateUserProfile({
|
|
3223
|
+
asset,
|
|
3224
|
+
protocols: withPools,
|
|
3225
|
+
chains: effectiveChains,
|
|
3226
|
+
...strategy !== void 0 && { strategy }
|
|
3227
|
+
});
|
|
2969
3228
|
if (this.sessionChannel === "agent") {
|
|
2970
3229
|
const chainId = agentDepositChainId ?? effectiveChains[effectiveChains.length - 1] ?? effectiveChains[0];
|
|
2971
|
-
|
|
3230
|
+
if (existingChains.includes(chainId)) {
|
|
3231
|
+
return await configureProfile();
|
|
3232
|
+
}
|
|
3233
|
+
const setupResult = await this.httpClient.post(
|
|
2972
3234
|
ENDPOINTS.AGENT_DEPOSIT_SETUP,
|
|
2973
3235
|
{
|
|
2974
3236
|
asset,
|
|
@@ -2979,14 +3241,14 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2979
3241
|
}
|
|
2980
3242
|
}
|
|
2981
3243
|
);
|
|
3244
|
+
if (!setupResult.applied) {
|
|
3245
|
+
throw new Error(
|
|
3246
|
+
`Agent deposit setup did not apply for ${asset} on chain ${chainId}.`
|
|
3247
|
+
);
|
|
3248
|
+
}
|
|
2982
3249
|
return await this.getUserDetails(asset);
|
|
2983
3250
|
}
|
|
2984
|
-
return await
|
|
2985
|
-
asset,
|
|
2986
|
-
protocols: withPools,
|
|
2987
|
-
chains: effectiveChains,
|
|
2988
|
-
...strategy !== void 0 && { strategy }
|
|
2989
|
-
});
|
|
3251
|
+
return await configureProfile();
|
|
2990
3252
|
}
|
|
2991
3253
|
/**
|
|
2992
3254
|
* Switch one asset to a strategy and select the protocols that go with it.
|
|
@@ -3221,14 +3483,14 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3221
3483
|
return this.httpClient.post(ENDPOINTS.DEPLOY_CHAINS, { chainIds });
|
|
3222
3484
|
}
|
|
3223
3485
|
/**
|
|
3224
|
-
* Transfer
|
|
3486
|
+
* Transfer a collateral token the wallet already holds into the Safe.
|
|
3225
3487
|
*
|
|
3226
3488
|
* @remarks
|
|
3227
|
-
*
|
|
3228
|
-
* {@link ZyfaiSDK.
|
|
3229
|
-
*
|
|
3230
|
-
* {@link ZyfaiSDK.logDeposit}, {@link ZyfaiSDK.getDepositStatus}.
|
|
3489
|
+
* Use this when the connected wallet holds the strategy collateral on the
|
|
3490
|
+
* deposit chain. {@link ZyfaiSDK.sendDeposit} calls this automatically in
|
|
3491
|
+
* that case. A different token uses {@link ZyfaiSDK.sendSwapDeposit}.
|
|
3231
3492
|
*
|
|
3493
|
+
* Confirms the ERC-20 `transfer`, then calls {@link ZyfaiSDK.logDeposit}.
|
|
3232
3494
|
* Requires {@link ZyfaiSDK.connectAccount}. Pass the **EOA** as `userAddress`.
|
|
3233
3495
|
*
|
|
3234
3496
|
* @group Deposits and withdrawals
|
|
@@ -3236,20 +3498,22 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3236
3498
|
* @param userAddress - Owner EOA (not the Safe)
|
|
3237
3499
|
* @param chainId - Chain for the transfer
|
|
3238
3500
|
* @param amount - Amount in least units (string integer)
|
|
3239
|
-
* @param asset -
|
|
3501
|
+
* @param asset - Collateral symbol (`USDC`, `WETH`, `EURC`, `NVDAc`)
|
|
3240
3502
|
* @param strategy - Optional first-deposit {@link Strategy}
|
|
3241
|
-
* @returns Transfer receipt and deposit registration
|
|
3503
|
+
* @returns Transfer receipt and deposit registration
|
|
3242
3504
|
*
|
|
3243
|
-
* @throws If validation fails, minimum portfolio is not met, Safe is unavailable, or transfer/register fails
|
|
3505
|
+
* @throws If validation fails, the minimum portfolio is not met, the Safe is unavailable, or transfer/register fails
|
|
3506
|
+
*
|
|
3507
|
+
* @see {@link ZyfaiSDK.sendDeposit}
|
|
3244
3508
|
*
|
|
3245
3509
|
* @example
|
|
3246
3510
|
* ```typescript
|
|
3247
3511
|
* await sdk.connectAccount(provider);
|
|
3248
|
-
* const sent = await sdk.
|
|
3249
|
-
* await sdk.
|
|
3512
|
+
* const sent = await sdk.sendDirectDeposit(eoa, 8453, "10000000", "USDC", "conservative");
|
|
3513
|
+
* await sdk.waitForDepositPosition(sent.registration.id, 8453);
|
|
3250
3514
|
* ```
|
|
3251
3515
|
*/
|
|
3252
|
-
async
|
|
3516
|
+
async sendDirectDeposit(userAddress, chainId, amount, asset, strategy) {
|
|
3253
3517
|
try {
|
|
3254
3518
|
if (!userAddress) {
|
|
3255
3519
|
throw new Error("User address is required");
|
|
@@ -3366,12 +3630,489 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3366
3630
|
txHash,
|
|
3367
3631
|
smartWallet: safeAddress,
|
|
3368
3632
|
amount: amountBigInt.toString(),
|
|
3633
|
+
route: "direct",
|
|
3369
3634
|
registration
|
|
3370
3635
|
};
|
|
3371
3636
|
} catch (error) {
|
|
3372
3637
|
throw new Error(`Deposit failed: ${error.message}`);
|
|
3373
3638
|
}
|
|
3374
3639
|
}
|
|
3640
|
+
async sendDeposit(userAddressOrParams, chainId, amount, asset, strategy) {
|
|
3641
|
+
if (typeof userAddressOrParams !== "string") {
|
|
3642
|
+
return this.sendRoutedDeposit(userAddressOrParams);
|
|
3643
|
+
}
|
|
3644
|
+
if (chainId === void 0 || amount === void 0 || asset === void 0) {
|
|
3645
|
+
throw new Error(
|
|
3646
|
+
"Deposit failed: chainId, amount, and asset are required"
|
|
3647
|
+
);
|
|
3648
|
+
}
|
|
3649
|
+
return this.sendDirectDeposit(
|
|
3650
|
+
userAddressOrParams,
|
|
3651
|
+
chainId,
|
|
3652
|
+
amount,
|
|
3653
|
+
asset,
|
|
3654
|
+
strategy
|
|
3655
|
+
);
|
|
3656
|
+
}
|
|
3657
|
+
/**
|
|
3658
|
+
* Resolve a deposit without signing.
|
|
3659
|
+
*
|
|
3660
|
+
* @remarks
|
|
3661
|
+
* A collateral the wallet already holds on `chainId` returns `route: "direct"`.
|
|
3662
|
+
* Same-chain native ETH into WETH returns `route: "wrap"`. Any other spend
|
|
3663
|
+
* token returns a Relay review quote (`route: "swap"`). Nothing is signed.
|
|
3664
|
+
* Optional `slippageBps` (default 200, max 500) is stored on that funding
|
|
3665
|
+
* order and reused when the quote is refreshed for signing.
|
|
3666
|
+
*
|
|
3667
|
+
* @group Deposits and withdrawals
|
|
3668
|
+
*
|
|
3669
|
+
* @param params - Destination collateral and optional spend token
|
|
3670
|
+
* @returns The route, and a review quote when a swap is required
|
|
3671
|
+
*
|
|
3672
|
+
* @throws If the spend token or destination collateral is not supported
|
|
3673
|
+
*/
|
|
3674
|
+
async quoteDeposit(params) {
|
|
3675
|
+
if (!params.userAddress) throw new Error("User address is required");
|
|
3676
|
+
if (!isSupportedChain(params.chainId)) {
|
|
3677
|
+
throw new Error(`Unsupported chain ID: ${params.chainId}`);
|
|
3678
|
+
}
|
|
3679
|
+
if (!params.amount || BigInt(params.amount) <= 0n) {
|
|
3680
|
+
throw new Error("Valid amount is required");
|
|
3681
|
+
}
|
|
3682
|
+
const route = resolveDepositRoute(params);
|
|
3683
|
+
if (route.kind === "direct" || route.kind === "wrap") {
|
|
3684
|
+
return {
|
|
3685
|
+
route: route.kind,
|
|
3686
|
+
asset: route.asset,
|
|
3687
|
+
chainId: params.chainId,
|
|
3688
|
+
amount: params.amount
|
|
3689
|
+
};
|
|
3690
|
+
}
|
|
3691
|
+
const quote = await this.quoteSwapDeposit({
|
|
3692
|
+
userAddress: params.userAddress,
|
|
3693
|
+
originChainId: route.originChainId,
|
|
3694
|
+
originCurrency: route.originCurrency,
|
|
3695
|
+
originAmount: params.amount,
|
|
3696
|
+
destinationChainId: params.chainId,
|
|
3697
|
+
destinationAsset: route.destinationAsset,
|
|
3698
|
+
strategy: params.strategy,
|
|
3699
|
+
slippageBps: params.slippageBps
|
|
3700
|
+
});
|
|
3701
|
+
return { route: "swap", ...quote };
|
|
3702
|
+
}
|
|
3703
|
+
/**
|
|
3704
|
+
* Quote a Relay swap that delivers a collateral token to the Safe.
|
|
3705
|
+
*
|
|
3706
|
+
* @remarks
|
|
3707
|
+
* Creates a funding order on the execution API. The connected wallet does
|
|
3708
|
+
* not sign. Pass `orderId` to {@link ZyfaiSDK.sendSwapDeposit} to sign the
|
|
3709
|
+
* refreshed quote, or call {@link ZyfaiSDK.sendDeposit} to quote and sign
|
|
3710
|
+
* in one step.
|
|
3711
|
+
*
|
|
3712
|
+
* Same-chain native ETH into WETH is rejected here. Use {@link ZyfaiSDK.sendDeposit}
|
|
3713
|
+
* with `spendToken: "ETH"`, which wraps in the wallet.
|
|
3714
|
+
*
|
|
3715
|
+
* Optional `slippageBps` defaults to 200 (max 500) and is fixed when this
|
|
3716
|
+
* funding order is created. Sign-time refresh reuses the stored value.
|
|
3717
|
+
*
|
|
3718
|
+
* @group Deposits and withdrawals
|
|
3719
|
+
*
|
|
3720
|
+
* @param params - Origin token, destination collateral, and funding wallet
|
|
3721
|
+
* @returns Review quote. Not yet signed.
|
|
3722
|
+
*
|
|
3723
|
+
* @throws If the server rejects the pair, the amount, or the quote
|
|
3724
|
+
*/
|
|
3725
|
+
async quoteSwapDeposit(params) {
|
|
3726
|
+
this.assertSwapDepositParams(params);
|
|
3727
|
+
await this.authenticateUser();
|
|
3728
|
+
const created = await this.httpClient.post(
|
|
3729
|
+
ENDPOINTS.FUNDING_ORDERS,
|
|
3730
|
+
{
|
|
3731
|
+
originChainId: params.originChainId,
|
|
3732
|
+
destinationChainId: params.destinationChainId,
|
|
3733
|
+
originCurrency: params.originCurrency,
|
|
3734
|
+
originAmount: params.originAmount,
|
|
3735
|
+
destinationAsset: params.destinationAsset.toUpperCase(),
|
|
3736
|
+
fundingWallet: params.userAddress,
|
|
3737
|
+
...params.slippageBps != null ? { slippageBps: resolveRelaySlippageBps(params.slippageBps) } : {}
|
|
3738
|
+
}
|
|
3739
|
+
);
|
|
3740
|
+
return {
|
|
3741
|
+
orderId: created.orderId,
|
|
3742
|
+
status: created.status,
|
|
3743
|
+
spend: created.spend,
|
|
3744
|
+
expectedOutput: created.expectedOutput,
|
|
3745
|
+
minimumOutput: created.minimumOutput,
|
|
3746
|
+
destinationChainId: created.destinationChainId,
|
|
3747
|
+
destinationCurrency: created.destinationCurrency,
|
|
3748
|
+
destinationAsset: params.destinationAsset.toUpperCase(),
|
|
3749
|
+
fees: created.fees ?? [],
|
|
3750
|
+
investEligible: created.investEligible,
|
|
3751
|
+
expiresAt: created.expiresAt ?? null,
|
|
3752
|
+
timeEstimate: created.timeEstimate ?? null
|
|
3753
|
+
};
|
|
3754
|
+
}
|
|
3755
|
+
/**
|
|
3756
|
+
* Read a Relay funding order, including a linked deposit once credit starts.
|
|
3757
|
+
*
|
|
3758
|
+
* @group Deposits and withdrawals
|
|
3759
|
+
*
|
|
3760
|
+
* @param orderId - Id from {@link ZyfaiSDK.quoteSwapDeposit}
|
|
3761
|
+
* @returns Stored order
|
|
3762
|
+
*
|
|
3763
|
+
* @throws If `orderId` is missing
|
|
3764
|
+
*/
|
|
3765
|
+
async getSwapDeposit(orderId) {
|
|
3766
|
+
if (!orderId) throw new Error("Funding order id is required");
|
|
3767
|
+
await this.authenticateUser();
|
|
3768
|
+
return this.httpClient.get(ENDPOINTS.FUNDING_ORDER(orderId));
|
|
3769
|
+
}
|
|
3770
|
+
/**
|
|
3771
|
+
* Swap or bridge a token into a Zyfai collateral, then register the deposit.
|
|
3772
|
+
*
|
|
3773
|
+
* @remarks
|
|
3774
|
+
* The execution API quotes Relay with the Safe as recipient. This method
|
|
3775
|
+
* refreshes that quote, signs the steps with the connected wallet, waits
|
|
3776
|
+
* for the collateral transfer into the Safe, and calls {@link ZyfaiSDK.logDeposit}.
|
|
3777
|
+
* Credit still requires that verified transfer. A refund or failed fill does
|
|
3778
|
+
* not register a deposit.
|
|
3779
|
+
*
|
|
3780
|
+
* Requires {@link ZyfaiSDK.connectAccount}. Origin chains other than
|
|
3781
|
+
* Ethereum, Base, and Arbitrum need an EIP-1193 wallet that can sign there.
|
|
3782
|
+
*
|
|
3783
|
+
* Optional `slippageBps` defaults to 200 (max 500) and is fixed when the
|
|
3784
|
+
* funding order is created. A later call that passes `orderId` ignores
|
|
3785
|
+
* `slippageBps` and signs the stored order.
|
|
3786
|
+
*
|
|
3787
|
+
* @group Deposits and withdrawals
|
|
3788
|
+
*
|
|
3789
|
+
* @param params - Origin token and destination collateral
|
|
3790
|
+
* @returns Destination transfer and deposit registration
|
|
3791
|
+
*
|
|
3792
|
+
* @throws If the quote, signature, fill, or registration fails, or if
|
|
3793
|
+
* `orderId` names a funding order whose origin or destination differs from
|
|
3794
|
+
* this call
|
|
3795
|
+
*
|
|
3796
|
+
* @see {@link ZyfaiSDK.sendDeposit}
|
|
3797
|
+
*
|
|
3798
|
+
* @example
|
|
3799
|
+
* ```typescript
|
|
3800
|
+
* await sdk.connectAccount(provider);
|
|
3801
|
+
* const sent = await sdk.sendSwapDeposit({
|
|
3802
|
+
* userAddress: eoa,
|
|
3803
|
+
* originChainId: 42161,
|
|
3804
|
+
* originCurrency: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
|
|
3805
|
+
* originAmount: "10000000",
|
|
3806
|
+
* destinationChainId: 8453,
|
|
3807
|
+
* destinationAsset: "WETH",
|
|
3808
|
+
* });
|
|
3809
|
+
* ```
|
|
3810
|
+
*/
|
|
3811
|
+
async sendSwapDeposit(params) {
|
|
3812
|
+
try {
|
|
3813
|
+
this.assertSwapDepositParams(params);
|
|
3814
|
+
await this.authenticateUser();
|
|
3815
|
+
await this.prepareFirstDeposit(params.strategy);
|
|
3816
|
+
let orderId;
|
|
3817
|
+
let destinationCurrency;
|
|
3818
|
+
let storedMinimum;
|
|
3819
|
+
if (params.orderId) {
|
|
3820
|
+
const existing = await this.getSwapDeposit(params.orderId);
|
|
3821
|
+
assertStoredFundingOrderRoute(existing, params);
|
|
3822
|
+
orderId = existing.id;
|
|
3823
|
+
destinationCurrency = existing.destinationCurrency;
|
|
3824
|
+
storedMinimum = existing.minimumOutput;
|
|
3825
|
+
} else {
|
|
3826
|
+
const created = await this.quoteSwapDeposit(params);
|
|
3827
|
+
orderId = created.orderId;
|
|
3828
|
+
destinationCurrency = created.destinationCurrency;
|
|
3829
|
+
storedMinimum = created.minimumOutput;
|
|
3830
|
+
}
|
|
3831
|
+
const signQuote = await this.httpClient.post(ENDPOINTS.FUNDING_ORDER_QUOTE(orderId));
|
|
3832
|
+
if (!signQuote.quote) {
|
|
3833
|
+
throw new Error("Relay funding quote is missing from the server response");
|
|
3834
|
+
}
|
|
3835
|
+
const minimumOutput = resolveCollateralMinimum(
|
|
3836
|
+
storedMinimum,
|
|
3837
|
+
signQuote.quote
|
|
3838
|
+
);
|
|
3839
|
+
await this.assertCollateralMinimum(
|
|
3840
|
+
params.userAddress,
|
|
3841
|
+
params.destinationChainId,
|
|
3842
|
+
params.destinationAsset,
|
|
3843
|
+
BigInt(minimumOutput)
|
|
3844
|
+
);
|
|
3845
|
+
ensureRelaySdkClient();
|
|
3846
|
+
const walletClient = await this.walletClientForOrigin(params.originChainId);
|
|
3847
|
+
const { data: execution } = await execute({
|
|
3848
|
+
quote: signQuote.quote,
|
|
3849
|
+
wallet: walletClient
|
|
3850
|
+
});
|
|
3851
|
+
const sourceTxHashes = collectRelaySourceTxHashes(
|
|
3852
|
+
execution,
|
|
3853
|
+
params.originChainId
|
|
3854
|
+
);
|
|
3855
|
+
const destinationFromExecution = collectRelayDestinationTxHashes(
|
|
3856
|
+
execution,
|
|
3857
|
+
params.destinationChainId
|
|
3858
|
+
);
|
|
3859
|
+
await this.httpClient.post(ENDPOINTS.FUNDING_ORDER_EXECUTION(orderId), {
|
|
3860
|
+
sourceTxHashes: sourceTxHashes.length ? sourceTxHashes : void 0,
|
|
3861
|
+
stepStatus: "submitted"
|
|
3862
|
+
});
|
|
3863
|
+
await this.hydrateSessionWallet();
|
|
3864
|
+
const safeAddress = await this.getSafeAddressFor(
|
|
3865
|
+
params.userAddress,
|
|
3866
|
+
params.destinationChainId
|
|
3867
|
+
);
|
|
3868
|
+
if (!safeAddress) {
|
|
3869
|
+
throw new Error("Smart wallet address is not available");
|
|
3870
|
+
}
|
|
3871
|
+
const filled = await this.waitForRelayCreditTx({
|
|
3872
|
+
orderId,
|
|
3873
|
+
destinationChainId: params.destinationChainId,
|
|
3874
|
+
destinationToken: destinationCurrency,
|
|
3875
|
+
recipientSafe: safeAddress,
|
|
3876
|
+
initialCandidates: destinationFromExecution
|
|
3877
|
+
});
|
|
3878
|
+
const creditAmount = filled.amount.toString();
|
|
3879
|
+
const registration = await this.registerDeposit(
|
|
3880
|
+
params.destinationChainId,
|
|
3881
|
+
filled.hash,
|
|
3882
|
+
creditAmount,
|
|
3883
|
+
destinationCurrency
|
|
3884
|
+
);
|
|
3885
|
+
return {
|
|
3886
|
+
success: true,
|
|
3887
|
+
txHash: filled.hash,
|
|
3888
|
+
smartWallet: safeAddress,
|
|
3889
|
+
amount: creditAmount,
|
|
3890
|
+
route: "swap",
|
|
3891
|
+
orderId,
|
|
3892
|
+
registration
|
|
3893
|
+
};
|
|
3894
|
+
} catch (error) {
|
|
3895
|
+
const message = thrownMessage(error);
|
|
3896
|
+
throw new Error(
|
|
3897
|
+
message.startsWith("Deposit failed:") ? message : `Deposit failed: ${message}`
|
|
3898
|
+
);
|
|
3899
|
+
}
|
|
3900
|
+
}
|
|
3901
|
+
async sendRoutedDeposit(params) {
|
|
3902
|
+
try {
|
|
3903
|
+
if (!params.userAddress) throw new Error("User address is required");
|
|
3904
|
+
if (!isSupportedChain(params.chainId)) {
|
|
3905
|
+
throw new Error(`Unsupported chain ID: ${params.chainId}`);
|
|
3906
|
+
}
|
|
3907
|
+
if (!params.amount || BigInt(params.amount) <= 0n) {
|
|
3908
|
+
throw new Error("Valid amount is required");
|
|
3909
|
+
}
|
|
3910
|
+
const route = resolveDepositRoute(params);
|
|
3911
|
+
if (route.kind === "direct") {
|
|
3912
|
+
return this.sendDirectDeposit(
|
|
3913
|
+
params.userAddress,
|
|
3914
|
+
params.chainId,
|
|
3915
|
+
params.amount,
|
|
3916
|
+
route.asset,
|
|
3917
|
+
params.strategy
|
|
3918
|
+
);
|
|
3919
|
+
}
|
|
3920
|
+
if (route.kind === "wrap") {
|
|
3921
|
+
await this.assertCollateralMinimum(
|
|
3922
|
+
params.userAddress,
|
|
3923
|
+
params.chainId,
|
|
3924
|
+
"WETH",
|
|
3925
|
+
BigInt(params.amount)
|
|
3926
|
+
);
|
|
3927
|
+
await this.wrapNativeEth(params.chainId, params.amount);
|
|
3928
|
+
const sent = await this.sendDirectDeposit(
|
|
3929
|
+
params.userAddress,
|
|
3930
|
+
params.chainId,
|
|
3931
|
+
params.amount,
|
|
3932
|
+
"WETH",
|
|
3933
|
+
params.strategy
|
|
3934
|
+
);
|
|
3935
|
+
return { ...sent, route: "wrap" };
|
|
3936
|
+
}
|
|
3937
|
+
return this.sendSwapDeposit({
|
|
3938
|
+
userAddress: params.userAddress,
|
|
3939
|
+
originChainId: route.originChainId,
|
|
3940
|
+
originCurrency: route.originCurrency,
|
|
3941
|
+
originAmount: params.amount,
|
|
3942
|
+
destinationChainId: params.chainId,
|
|
3943
|
+
destinationAsset: route.destinationAsset,
|
|
3944
|
+
strategy: params.strategy,
|
|
3945
|
+
slippageBps: params.slippageBps
|
|
3946
|
+
});
|
|
3947
|
+
} catch (error) {
|
|
3948
|
+
const message = thrownMessage(error);
|
|
3949
|
+
throw new Error(
|
|
3950
|
+
message.startsWith("Deposit failed:") ? message : `Deposit failed: ${message}`
|
|
3951
|
+
);
|
|
3952
|
+
}
|
|
3953
|
+
}
|
|
3954
|
+
/** Portfolio floor used by a direct deposit, applied before a wrap or swap spends. */
|
|
3955
|
+
async assertCollateralMinimum(userAddress, chainId, asset, amount) {
|
|
3956
|
+
const symbol = Object.keys(ASSET_CONFIGS).find(
|
|
3957
|
+
(key) => key.toLowerCase() === asset.toLowerCase()
|
|
3958
|
+
);
|
|
3959
|
+
if (!symbol || !getAssetChainIds(symbol).includes(chainId)) return;
|
|
3960
|
+
await this.hydrateSessionWallet();
|
|
3961
|
+
const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
|
|
3962
|
+
if (!safeAddress) {
|
|
3963
|
+
throw new Error("Smart wallet address is not available");
|
|
3964
|
+
}
|
|
3965
|
+
await this.enforceMinimumPortfolioBalance(
|
|
3966
|
+
chainId,
|
|
3967
|
+
symbol,
|
|
3968
|
+
amount,
|
|
3969
|
+
safeAddress,
|
|
3970
|
+
userAddress
|
|
3971
|
+
);
|
|
3972
|
+
}
|
|
3973
|
+
assertSwapDepositParams(params) {
|
|
3974
|
+
if (!params.userAddress) throw new Error("User address is required");
|
|
3975
|
+
if (!params.originAmount || BigInt(params.originAmount) <= 0n) {
|
|
3976
|
+
throw new Error("Valid origin amount is required");
|
|
3977
|
+
}
|
|
3978
|
+
if (!Number.isInteger(params.originChainId) || params.originChainId <= 0) {
|
|
3979
|
+
throw new Error("Valid origin chain is required");
|
|
3980
|
+
}
|
|
3981
|
+
if (!isSupportedChain(params.destinationChainId)) {
|
|
3982
|
+
throw new Error(`Unsupported chain ID: ${params.destinationChainId}`);
|
|
3983
|
+
}
|
|
3984
|
+
if (!params.originCurrency) throw new Error("Origin token is required");
|
|
3985
|
+
if (!params.destinationAsset) throw new Error("Destination asset is required");
|
|
3986
|
+
if (params.slippageBps != null) {
|
|
3987
|
+
if (!Number.isInteger(params.slippageBps) || params.slippageBps < 1 || params.slippageBps > MAX_RELAY_SLIPPAGE_BPS) {
|
|
3988
|
+
throw new Error(
|
|
3989
|
+
`slippageBps must be an integer from 1 to ${MAX_RELAY_SLIPPAGE_BPS}. Received ${params.slippageBps}.`
|
|
3990
|
+
);
|
|
3991
|
+
}
|
|
3992
|
+
}
|
|
3993
|
+
if (params.destinationAsset.toUpperCase() === "WETH" && params.originChainId === params.destinationChainId && isNativeSpendToken(params.originCurrency)) {
|
|
3994
|
+
throw new Error(
|
|
3995
|
+
'Same-chain ETH to WETH is a wrap, not a Relay swap. Call sendDeposit with spendToken "ETH".'
|
|
3996
|
+
);
|
|
3997
|
+
}
|
|
3998
|
+
}
|
|
3999
|
+
async walletClientForOrigin(originChainId) {
|
|
4000
|
+
if (this.signer) {
|
|
4001
|
+
if (!isSupportedChain(originChainId)) {
|
|
4002
|
+
throw new Error(
|
|
4003
|
+
`Cannot sign a swap from chain ${originChainId} with a private key. Connect an EIP-1193 wallet, or spend from Ethereum, Base, or Arbitrum.`
|
|
4004
|
+
);
|
|
4005
|
+
}
|
|
4006
|
+
return this.getWalletClient(originChainId);
|
|
4007
|
+
}
|
|
4008
|
+
if (!this.walletClient?.account) {
|
|
4009
|
+
throw new Error("No account connected. Call connectAccount() first");
|
|
4010
|
+
}
|
|
4011
|
+
if (!this.currentProvider?.request) {
|
|
4012
|
+
if (this.walletClient.chain?.id === originChainId) return this.walletClient;
|
|
4013
|
+
throw new Error(
|
|
4014
|
+
`Wallet is on chain ${this.walletClient.chain?.id ?? "unknown"}. Switch it to chain ${originChainId} before this swap.`
|
|
4015
|
+
);
|
|
4016
|
+
}
|
|
4017
|
+
await this.currentProvider.request({
|
|
4018
|
+
method: "wallet_switchEthereumChain",
|
|
4019
|
+
params: [{ chainId: `0x${originChainId.toString(16)}` }]
|
|
4020
|
+
});
|
|
4021
|
+
const chain = isSupportedChain(originChainId) ? getChainConfig(originChainId, this.rpcUrls).chain : defineChain({
|
|
4022
|
+
id: originChainId,
|
|
4023
|
+
name: `Chain ${originChainId}`,
|
|
4024
|
+
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
|
|
4025
|
+
rpcUrls: { default: { http: ["http://127.0.0.1"] } }
|
|
4026
|
+
});
|
|
4027
|
+
this.walletClient = createWalletClient({
|
|
4028
|
+
account: this.walletClient.account,
|
|
4029
|
+
chain,
|
|
4030
|
+
transport: custom(this.currentProvider)
|
|
4031
|
+
});
|
|
4032
|
+
if (isSupportedChain(originChainId)) {
|
|
4033
|
+
this.currentChainId = originChainId;
|
|
4034
|
+
}
|
|
4035
|
+
return this.walletClient;
|
|
4036
|
+
}
|
|
4037
|
+
async wrapNativeEth(chainId, amount) {
|
|
4038
|
+
const token = getDefaultTokenAddress(chainId, "WETH");
|
|
4039
|
+
const walletClient = this.getWalletClient(chainId);
|
|
4040
|
+
const chainConfig = getChainConfig(chainId, this.rpcUrls);
|
|
4041
|
+
const hash = await walletClient.writeContract({
|
|
4042
|
+
address: token,
|
|
4043
|
+
abi: WETH_DEPOSIT_ABI,
|
|
4044
|
+
functionName: "deposit",
|
|
4045
|
+
value: BigInt(amount),
|
|
4046
|
+
chain: chainConfig.chain,
|
|
4047
|
+
account: walletClient.account
|
|
4048
|
+
});
|
|
4049
|
+
const receipt = await chainConfig.publicClient.waitForTransactionReceipt({
|
|
4050
|
+
hash
|
|
4051
|
+
});
|
|
4052
|
+
if (receipt.status !== "success") {
|
|
4053
|
+
throw new Error("ETH wrap failed");
|
|
4054
|
+
}
|
|
4055
|
+
}
|
|
4056
|
+
async waitForRelayCreditTx(params) {
|
|
4057
|
+
const chainConfig = getChainConfig(params.destinationChainId, this.rpcUrls);
|
|
4058
|
+
const receipts = /* @__PURE__ */ new Map();
|
|
4059
|
+
const maxAttempts = 120;
|
|
4060
|
+
const intervalMs = 5e3;
|
|
4061
|
+
const loadReceipt = async (hash) => {
|
|
4062
|
+
const key = hash.toLowerCase();
|
|
4063
|
+
if (receipts.has(key)) return;
|
|
4064
|
+
try {
|
|
4065
|
+
const receipt = await chainConfig.publicClient.getTransactionReceipt({
|
|
4066
|
+
hash
|
|
4067
|
+
});
|
|
4068
|
+
receipts.set(key, {
|
|
4069
|
+
status: receipt.status,
|
|
4070
|
+
logs: receipt.logs.map((log) => ({
|
|
4071
|
+
address: log.address,
|
|
4072
|
+
topics: log.topics,
|
|
4073
|
+
data: log.data
|
|
4074
|
+
}))
|
|
4075
|
+
});
|
|
4076
|
+
} catch {
|
|
4077
|
+
}
|
|
4078
|
+
};
|
|
4079
|
+
const pick = async (candidates) => {
|
|
4080
|
+
for (const hash2 of candidates) {
|
|
4081
|
+
if (hash2) await loadReceipt(hash2);
|
|
4082
|
+
}
|
|
4083
|
+
const hash = selectRelayCreditTxHash({
|
|
4084
|
+
candidates,
|
|
4085
|
+
receipts,
|
|
4086
|
+
token: params.destinationToken,
|
|
4087
|
+
recipient: params.recipientSafe
|
|
4088
|
+
});
|
|
4089
|
+
if (!hash) return null;
|
|
4090
|
+
const receipt = receipts.get(hash.toLowerCase());
|
|
4091
|
+
return {
|
|
4092
|
+
hash,
|
|
4093
|
+
amount: receipt ? transferAmountTo(
|
|
4094
|
+
receipt.logs,
|
|
4095
|
+
params.destinationToken,
|
|
4096
|
+
params.recipientSafe
|
|
4097
|
+
) : 0n
|
|
4098
|
+
};
|
|
4099
|
+
};
|
|
4100
|
+
const immediate = await pick(params.initialCandidates);
|
|
4101
|
+
if (immediate) return immediate;
|
|
4102
|
+
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
|
4103
|
+
const order = await this.getSwapDeposit(params.orderId);
|
|
4104
|
+
if (order.status === "refunded" || order.status === "failed") {
|
|
4105
|
+
throw new Error(`Relay funding ${order.status}`);
|
|
4106
|
+
}
|
|
4107
|
+
const match = await pick([
|
|
4108
|
+
...params.initialCandidates,
|
|
4109
|
+
...order.destinationTxHashes ?? []
|
|
4110
|
+
]);
|
|
4111
|
+
if (match) return match;
|
|
4112
|
+
await sleep(intervalMs);
|
|
4113
|
+
}
|
|
4114
|
+
throw new Error("Relay funding is still converting");
|
|
4115
|
+
}
|
|
3375
4116
|
/**
|
|
3376
4117
|
* @deprecated Compatibility convenience method. Prefer {@link ZyfaiSDK.sendDeposit} followed by
|
|
3377
4118
|
* {@link ZyfaiSDK.waitForDepositCredit} when the caller owns the completion UX.
|
|
@@ -3470,6 +4211,57 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3470
4211
|
value: "0"
|
|
3471
4212
|
};
|
|
3472
4213
|
}
|
|
4214
|
+
/**
|
|
4215
|
+
* Prepare a gas-sponsored rZFI claim into the user's Safe on Base.
|
|
4216
|
+
*
|
|
4217
|
+
* @remarks
|
|
4218
|
+
* The SDK never signs. Sign `userOpHashToSign` with the owner EOA as a
|
|
4219
|
+
* personal_sign of the raw 32-byte hash (viem:
|
|
4220
|
+
* `signMessage({ message: { raw: userOpHashToSign } })`), then pass the
|
|
4221
|
+
* signature to {@link ZyfaiSDK.submitRzfiClaim} within 5 minutes.
|
|
4222
|
+
* Requires an authenticated user session.
|
|
4223
|
+
*
|
|
4224
|
+
* @group Rewards
|
|
4225
|
+
*
|
|
4226
|
+
* @param userAddress - Owner EOA
|
|
4227
|
+
* @returns `status: "pending"` with the hash to sign and the amount
|
|
4228
|
+
*
|
|
4229
|
+
* @throws If there is no rZFI to claim, or the reward tree is updating (retry later)
|
|
4230
|
+
*/
|
|
4231
|
+
async prepareRzfiClaim(userAddress) {
|
|
4232
|
+
this.assertRzfiClaimUser(userAddress);
|
|
4233
|
+
await this.authenticateUser();
|
|
4234
|
+
return this.httpClient.post(ENDPOINTS.RZFI_CLAIM, {});
|
|
4235
|
+
}
|
|
4236
|
+
/**
|
|
4237
|
+
* Submit the owner-signed rZFI claim prepared by {@link ZyfaiSDK.prepareRzfiClaim}.
|
|
4238
|
+
*
|
|
4239
|
+
* @group Rewards
|
|
4240
|
+
*
|
|
4241
|
+
* @param userAddress - Owner EOA
|
|
4242
|
+
* @param userOpSignature - Owner EOA signature over `userOpHashToSign`
|
|
4243
|
+
* @returns `status: "claimed"` with the on-chain `txHash`
|
|
4244
|
+
*
|
|
4245
|
+
* @throws If the signature is not the owner's, the claim expired, or it reverted
|
|
4246
|
+
*/
|
|
4247
|
+
async submitRzfiClaim(userAddress, userOpSignature) {
|
|
4248
|
+
this.assertRzfiClaimUser(userAddress);
|
|
4249
|
+
if (!userOpSignature?.startsWith("0x")) {
|
|
4250
|
+
throw new Error("A 0x-prefixed userOpSignature is required");
|
|
4251
|
+
}
|
|
4252
|
+
await this.authenticateUser();
|
|
4253
|
+
return this.httpClient.post(ENDPOINTS.RZFI_CLAIM, {
|
|
4254
|
+
userOpSignature
|
|
4255
|
+
});
|
|
4256
|
+
}
|
|
4257
|
+
assertRzfiClaimUser(userAddress) {
|
|
4258
|
+
if (!userAddress) {
|
|
4259
|
+
throw new Error("A user address is required");
|
|
4260
|
+
}
|
|
4261
|
+
if (this.sessionEoa && getAddress2(userAddress) !== this.sessionEoa) {
|
|
4262
|
+
throw new Error("userAddress does not match authenticated session EOA");
|
|
4263
|
+
}
|
|
4264
|
+
}
|
|
3473
4265
|
/** Apply the same per-asset minimum portfolio rule as sendDeposit. */
|
|
3474
4266
|
async enforceMinimumPortfolioBalance(chainId, asset, amount, safeAddress, userAddress) {
|
|
3475
4267
|
if (this.bypassMinPortfolio || isMainnetMinPortfolioExempt(chainId, userAddress, safeAddress)) {
|
|
@@ -3537,7 +4329,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3537
4329
|
}
|
|
3538
4330
|
await this.authenticateUser();
|
|
3539
4331
|
const usdcDetails = await this.getUserDetails("USDC");
|
|
3540
|
-
|
|
4332
|
+
const usdcChainsConfigured = (usdcDetails.chains?.length ?? 0) > 0;
|
|
4333
|
+
const usdcProtocolsConfigured = (usdcDetails.protocols?.length ?? 0) > 0;
|
|
4334
|
+
if (usdcChainsConfigured && usdcProtocolsConfigured) {
|
|
3541
4335
|
return { applied: false };
|
|
3542
4336
|
}
|
|
3543
4337
|
await this.updateUserProtocols(strategy, { strict: true });
|
|
@@ -3547,6 +4341,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3547
4341
|
"First-deposit setup did not persist USDC chain configuration."
|
|
3548
4342
|
);
|
|
3549
4343
|
}
|
|
4344
|
+
if ((usdcAfterSetup.protocols?.length ?? 0) === 0) {
|
|
4345
|
+
throw new Error(
|
|
4346
|
+
"First-deposit setup did not persist USDC protocol configuration."
|
|
4347
|
+
);
|
|
4348
|
+
}
|
|
3550
4349
|
return { applied: true };
|
|
3551
4350
|
}
|
|
3552
4351
|
/**
|
|
@@ -3563,7 +4362,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3563
4362
|
}
|
|
3564
4363
|
await this.authenticateUser();
|
|
3565
4364
|
const details = await this.getUserDetails(asset);
|
|
3566
|
-
|
|
4365
|
+
const chainConfigured = details.chains?.includes(chainId) ?? false;
|
|
4366
|
+
const protocolsConfigured = (details.protocols?.length ?? 0) > 0;
|
|
4367
|
+
if (chainConfigured && protocolsConfigured) {
|
|
3567
4368
|
return { applied: false };
|
|
3568
4369
|
}
|
|
3569
4370
|
const allProtocols = await this.httpClient.get(
|
|
@@ -3581,8 +4382,20 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3581
4382
|
`First-deposit setup did not persist ${asset} chain ${chainId} configuration.`
|
|
3582
4383
|
);
|
|
3583
4384
|
}
|
|
4385
|
+
if ((afterSetup.protocols?.length ?? 0) === 0) {
|
|
4386
|
+
throw new Error(
|
|
4387
|
+
`First-deposit setup did not persist ${asset} protocol configuration.`
|
|
4388
|
+
);
|
|
4389
|
+
}
|
|
3584
4390
|
return { applied: true };
|
|
3585
4391
|
}
|
|
4392
|
+
/**
|
|
4393
|
+
* Persist the deposit asset on one chain before a signing page runs the transfer or swap.
|
|
4394
|
+
* Does not build calldata and does not check the portfolio minimum.
|
|
4395
|
+
*/
|
|
4396
|
+
async ensureDepositAssetOnChain(params) {
|
|
4397
|
+
return this.ensureDepositProfileForPrepare(params);
|
|
4398
|
+
}
|
|
3586
4399
|
/**
|
|
3587
4400
|
* Prepare a deposit: persist first-deposit profile when needed and return
|
|
3588
4401
|
* ERC-20 transfer calldata for the user to sign (does not broadcast).
|
|
@@ -4314,6 +5127,51 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
4314
5127
|
// ============================================================================
|
|
4315
5128
|
// TVL & Volume Methods
|
|
4316
5129
|
// ============================================================================
|
|
5130
|
+
/**
|
|
5131
|
+
* Get Zyfai's Merkl incentive campaigns on Base with their current APR.
|
|
5132
|
+
*
|
|
5133
|
+
* @group Analytics and opportunities
|
|
5134
|
+
*
|
|
5135
|
+
* @remarks Data API. Partner API key only; SIWE not required.
|
|
5136
|
+
*
|
|
5137
|
+
* @returns One entry per campaign slot (rZFI, new TVL, season campaign)
|
|
5138
|
+
*
|
|
5139
|
+
* @example
|
|
5140
|
+
* ```typescript
|
|
5141
|
+
* const campaigns = await sdk.getBaseMerklCampaigns();
|
|
5142
|
+
* for (const c of campaigns.filter((c) => c.isActive)) {
|
|
5143
|
+
* console.log(c.name, `${(c.apr * 100).toFixed(2)}%`);
|
|
5144
|
+
* }
|
|
5145
|
+
* ```
|
|
5146
|
+
*/
|
|
5147
|
+
async getBaseMerklCampaigns() {
|
|
5148
|
+
const ids = ["base/rzfi", "base-new-tvl", "base"];
|
|
5149
|
+
try {
|
|
5150
|
+
const now = Date.now();
|
|
5151
|
+
return await Promise.all(
|
|
5152
|
+
ids.map(async (id) => {
|
|
5153
|
+
const { campaign, currentStats } = await this.httpClient.dataGet(DATA_ENDPOINTS.MERKL_CAMPAIGN_INFO(id));
|
|
5154
|
+
return {
|
|
5155
|
+
id,
|
|
5156
|
+
name: campaign.name,
|
|
5157
|
+
apr: Number(currentStats.currentAPR),
|
|
5158
|
+
tvlUsd: currentStats.totalTVL,
|
|
5159
|
+
activeWallets: currentStats.activeWallets,
|
|
5160
|
+
rewardToken: campaign.rewardToken,
|
|
5161
|
+
totalRewards: campaign.totalRewards,
|
|
5162
|
+
dailyRewardAmount: campaign.dailyRewardAmount,
|
|
5163
|
+
startDate: campaign.startDate,
|
|
5164
|
+
endDate: campaign.endDate,
|
|
5165
|
+
isActive: now >= Date.parse(campaign.startDate) && now < Date.parse(campaign.endDate)
|
|
5166
|
+
};
|
|
5167
|
+
})
|
|
5168
|
+
);
|
|
5169
|
+
} catch (error) {
|
|
5170
|
+
throw new Error(
|
|
5171
|
+
`Failed to get Base Merkl campaigns: ${error.message}`
|
|
5172
|
+
);
|
|
5173
|
+
}
|
|
5174
|
+
}
|
|
4317
5175
|
/**
|
|
4318
5176
|
* Get total value locked (TVL) across all Zyfai accounts.
|
|
4319
5177
|
*
|
|
@@ -6204,6 +7062,7 @@ export {
|
|
|
6204
7062
|
API_ENDPOINT,
|
|
6205
7063
|
DATA_API_BASE_URLS,
|
|
6206
7064
|
DATA_API_ENDPOINT,
|
|
7065
|
+
DEFAULT_RELAY_SLIPPAGE_BPS,
|
|
6207
7066
|
DEFAULT_TOKEN_ADDRESSES,
|
|
6208
7067
|
ERC7579_LAUNCHPAD_ADDRESS,
|
|
6209
7068
|
EXECUTION_API_BASE_URLS,
|
|
@@ -6212,9 +7071,11 @@ export {
|
|
|
6212
7071
|
LOCAL_DATA_API_BASE_URL,
|
|
6213
7072
|
LOCAL_EXECUTION_API_BASE_URL,
|
|
6214
7073
|
LOCAL_WS_URL,
|
|
7074
|
+
MAX_RELAY_SLIPPAGE_BPS,
|
|
6215
7075
|
OWNABLE_VALIDATOR,
|
|
6216
7076
|
POOL_MODULE_ADDRESSES,
|
|
6217
7077
|
PROXY_EXECUTOR,
|
|
7078
|
+
RELAY_SLIPPAGE_PRESETS_BPS,
|
|
6218
7079
|
SAFE_7579_ADDRESS,
|
|
6219
7080
|
SMART_SESSIONS_FALLBACK,
|
|
6220
7081
|
SMART_SESSIONS_VALIDATOR,
|
|
@@ -6233,5 +7094,7 @@ export {
|
|
|
6233
7094
|
getManagedAssets,
|
|
6234
7095
|
getSupportedChainIds,
|
|
6235
7096
|
getWsUrl,
|
|
6236
|
-
isSupportedChain
|
|
7097
|
+
isSupportedChain,
|
|
7098
|
+
resolveDepositRoute,
|
|
7099
|
+
resolveRelaySlippageBps
|
|
6237
7100
|
};
|