@dzapio/sdk 2.0.51 → 2.0.52

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.js CHANGED
@@ -5,11 +5,11 @@ var Axios = require('axios');
5
5
  var ethers = require('ethers');
6
6
  var viemChains = require('viem/chains');
7
7
  var core = require('@bigmi/core');
8
- var utils = require('viem/utils');
9
8
  var actions = require('viem/actions');
9
+ var utils = require('viem/utils');
10
+ var web3_js = require('@solana/web3.js');
10
11
  var Decimal = require('decimal.js');
11
12
  var bitcoinAddressValidation = require('bitcoin-address-validation');
12
- var web3_js = require('@solana/web3.js');
13
13
  var TonWeb = require('tonweb');
14
14
 
15
15
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -563,6 +563,7 @@ var eFormatNativeTokenLowerCase = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
563
563
  var eFormatNativeToken = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
564
564
  var zkNativeToken = "0x000000000000000000000000000000000000800A";
565
565
  var solanaNativeToken = "11111111111111111111111111111111";
566
+ var solanaWNativeToken = "So11111111111111111111111111111111111111112";
566
567
  var unmarshalDeadAddress = "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000";
567
568
  var tonNativeToken = "EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c";
568
569
  var artheraNativeToken = "0x000000000000000000000000000000000000aA09";
@@ -10923,1238 +10924,218 @@ var viemChainsById = [...Object.values(viemChains__namespace), ...customViemChai
10923
10924
  var RPC_RETRY_DELAY = 500;
10924
10925
  var RPC_BATCHING_WAIT_TIME = 1e3;
10925
10926
 
10926
- // src/utils/decoder/swap/abis.ts
10927
- var SwapAbisByFunctionName = {
10928
- SingleSwap: [
10929
- {
10930
- inputs: [
10931
- {
10932
- internalType: "bytes32",
10933
- name: "_transactionId",
10934
- type: "bytes32"
10935
- },
10936
- {
10937
- internalType: "bytes",
10938
- name: "_feeData",
10939
- type: "bytes"
10940
- },
10941
- {
10942
- internalType: "bytes",
10943
- name: "_feeVerificationSignature",
10944
- type: "bytes"
10945
- },
10946
- {
10947
- internalType: "uint256",
10948
- name: "_deadline",
10949
- type: "uint256"
10950
- },
10951
- {
10952
- components: [
10953
- {
10954
- internalType: "address",
10955
- name: "token",
10956
- type: "address"
10957
- },
10958
- {
10959
- internalType: "uint256",
10960
- name: "amount",
10961
- type: "uint256"
10962
- },
10963
- {
10964
- internalType: "bytes",
10965
- name: "permit",
10966
- type: "bytes"
10967
- }
10968
- ],
10969
- internalType: "struct InputToken",
10970
- name: "_inputTokens",
10971
- type: "tuple"
10972
- },
10973
- {
10974
- components: [
10975
- {
10976
- internalType: "address",
10977
- name: "recipient",
10978
- type: "address"
10979
- },
10980
- {
10981
- internalType: "address",
10982
- name: "from",
10983
- type: "address"
10984
- },
10985
- {
10986
- internalType: "address",
10987
- name: "to",
10988
- type: "address"
10989
- },
10990
- {
10991
- internalType: "uint256",
10992
- name: "fromAmount",
10993
- type: "uint256"
10994
- },
10995
- {
10996
- internalType: "uint256",
10997
- name: "minToAmount",
10998
- type: "uint256"
10999
- }
11000
- ],
11001
- internalType: "struct SwapData",
11002
- name: "_swapData",
11003
- type: "tuple"
11004
- },
11005
- {
11006
- components: [
11007
- {
11008
- internalType: "string",
11009
- name: "dex",
11010
- type: "string"
11011
- },
11012
- {
11013
- internalType: "address",
11014
- name: "callTo",
11015
- type: "address"
11016
- },
11017
- {
11018
- internalType: "address",
11019
- name: "approveTo",
11020
- type: "address"
11021
- },
11022
- {
11023
- internalType: "bytes",
11024
- name: "swapCallData",
11025
- type: "bytes"
11026
- },
11027
- {
11028
- internalType: "bool",
11029
- name: "isDirectTransfer",
11030
- type: "bool"
11031
- }
11032
- ],
11033
- internalType: "struct SwapExecutionData",
11034
- name: "_swapExecutionData",
11035
- type: "tuple"
11036
- }
11037
- ],
11038
- name: "swap",
11039
- outputs: [],
11040
- stateMutability: "payable",
11041
- type: "function"
10927
+ // src/utils/index.ts
10928
+ var publicClientRpcConfig = { batch: { wait: RPC_BATCHING_WAIT_TIME }, retryDelay: RPC_RETRY_DELAY };
10929
+ var getPublicClient = ({ rpcUrls, chainId }) => {
10930
+ var _a, _b;
10931
+ const chain = viemChainsById[chainId];
10932
+ const urls = ((rpcUrls == null ? void 0 : rpcUrls.length) ? rpcUrls : (_b = (_a = chain == null ? void 0 : chain.rpcUrls) == null ? void 0 : _a.default) == null ? void 0 : _b.http) ?? [];
10933
+ const transports = urls.length ? urls.map((url) => viem.http(url, publicClientRpcConfig)) : [viem.http()];
10934
+ return viem.createPublicClient({
10935
+ chain,
10936
+ transport: viem.fallback(transports),
10937
+ batch: {
10938
+ multicall: {
10939
+ wait: RPC_BATCHING_WAIT_TIME
10940
+ }
11042
10941
  }
11043
- ],
11044
- BatchPermitSwapAbi: [
11045
- {
11046
- inputs: [
11047
- {
11048
- internalType: "bytes32",
11049
- name: "_transactionId",
11050
- type: "bytes32"
11051
- },
11052
- {
11053
- internalType: "bytes",
11054
- name: "_feeData",
11055
- type: "bytes"
11056
- },
11057
- {
11058
- internalType: "bytes",
11059
- name: "_feeVerificationSignature",
11060
- type: "bytes"
11061
- },
11062
- {
11063
- internalType: "uint256",
11064
- name: "_deadline",
11065
- type: "uint256"
11066
- },
11067
- {
11068
- internalType: "bytes",
11069
- name: "_batchDepositSignature",
11070
- type: "bytes"
11071
- },
11072
- {
11073
- components: [
11074
- {
11075
- components: [
11076
- {
11077
- internalType: "address",
11078
- name: "token",
11079
- type: "address"
11080
- },
11081
- {
11082
- internalType: "uint256",
11083
- name: "amount",
11084
- type: "uint256"
11085
- }
11086
- ],
11087
- internalType: "struct TokenPermissions[]",
11088
- name: "permitted",
11089
- type: "tuple[]"
11090
- },
11091
- {
11092
- internalType: "uint256",
11093
- name: "nonce",
11094
- type: "uint256"
11095
- },
11096
- {
11097
- internalType: "uint256",
11098
- name: "deadline",
11099
- type: "uint256"
11100
- }
11101
- ],
11102
- internalType: "struct PermitBatchTransferFrom",
11103
- name: "_tokenDepositDetails",
11104
- type: "tuple"
11105
- },
11106
- {
11107
- components: [
11108
- {
11109
- internalType: "address",
11110
- name: "recipient",
11111
- type: "address"
11112
- },
11113
- {
11114
- internalType: "address",
11115
- name: "from",
11116
- type: "address"
11117
- },
11118
- {
11119
- internalType: "address",
11120
- name: "to",
11121
- type: "address"
11122
- },
11123
- {
11124
- internalType: "uint256",
11125
- name: "fromAmount",
11126
- type: "uint256"
11127
- },
11128
- {
11129
- internalType: "uint256",
11130
- name: "minToAmount",
11131
- type: "uint256"
11132
- }
11133
- ],
11134
- internalType: "struct SwapData[]",
11135
- name: "_swapData",
11136
- type: "tuple[]"
11137
- },
11138
- {
11139
- components: [
11140
- {
11141
- internalType: "string",
11142
- name: "dex",
11143
- type: "string"
11144
- },
11145
- {
11146
- internalType: "address",
11147
- name: "callTo",
11148
- type: "address"
11149
- },
11150
- {
11151
- internalType: "address",
11152
- name: "approveTo",
11153
- type: "address"
11154
- },
11155
- {
11156
- internalType: "bytes",
11157
- name: "swapCallData",
11158
- type: "bytes"
11159
- },
11160
- {
11161
- internalType: "bool",
11162
- name: "isDirectTransfer",
11163
- type: "bool"
11164
- }
11165
- ],
11166
- internalType: "struct SwapExecutionData[]",
11167
- name: "_swapExecutionData",
11168
- type: "tuple[]"
11169
- },
11170
- {
11171
- internalType: "bool",
11172
- name: "withoutRevert",
11173
- type: "bool"
11174
- }
11175
- ],
11176
- name: "swap",
11177
- outputs: [],
11178
- stateMutability: "payable",
11179
- type: "function"
10942
+ });
10943
+ };
10944
+ function getTokensPairKey({
10945
+ srcToken,
10946
+ destToken,
10947
+ srcChainId,
10948
+ destChainId,
10949
+ srcChainNativeAddress = viem.zeroAddress,
10950
+ destChainNativeAddress = viem.zeroAddress
10951
+ }) {
10952
+ const srcFormattedAddress = formatToken(srcToken, srcChainNativeAddress);
10953
+ const destFormattedAddress = formatToken(destToken, destChainNativeAddress);
10954
+ return `${srcChainId}_${srcFormattedAddress}-${destChainId}_${destFormattedAddress}`;
10955
+ }
10956
+ var writeContract = async ({
10957
+ chainId,
10958
+ contractAddress,
10959
+ abi: abi7,
10960
+ functionName,
10961
+ args = [],
10962
+ value = "0",
10963
+ rpcUrls = [""],
10964
+ signer
10965
+ }) => {
10966
+ const publicClient = getPublicClient({ chainId, rpcUrls });
10967
+ try {
10968
+ const { request } = await publicClient.simulateContract({
10969
+ address: contractAddress,
10970
+ abi: abi7,
10971
+ functionName,
10972
+ args,
10973
+ account: signer.account,
10974
+ value: BigInt(value)
10975
+ });
10976
+ const hash = await signer.writeContract(request);
10977
+ return { txnHash: hash, status: "success" /* success */, code: 200 /* Success */ };
10978
+ } catch (e) {
10979
+ console.log({ e });
10980
+ if ((e == null ? void 0 : e.code) === 4001 /* UserRejectedRequest */) {
10981
+ return { status: "rejected" /* rejected */, code: e == null ? void 0 : e.code, txnHash: "" };
11180
10982
  }
11181
- ],
11182
- MultiSwapAbi: [
10983
+ return { status: "error" /* error */, code: e == null ? void 0 : e.code, txnHash: "" };
10984
+ }
10985
+ };
10986
+ var calcTotalSrcTokenAmount = (data) => {
10987
+ return data.reduce((acc, obj) => {
10988
+ return acc + BigInt(obj.amount);
10989
+ }, BigInt(0));
10990
+ };
10991
+ var isOneToMany = (firstTokenAddress, secondTokenAddress) => firstTokenAddress === secondTokenAddress;
10992
+ BigInt(15) / BigInt(10);
10993
+ var isTypeSigner = (variable) => {
10994
+ return variable instanceof ethers.Signer;
10995
+ };
10996
+ var isDZapNativeToken = (srcToken) => srcToken === dZapNativeTokenFormat;
10997
+ var getDZapAbi = (service, version) => {
10998
+ switch (service) {
10999
+ case Services.trade:
11000
+ switch (version) {
11001
+ case "v1" /* v1 */:
11002
+ return artifacts_exports[DZapAbis.dZapCoreAbi];
11003
+ case "v2" /* v2 */:
11004
+ return artifacts_exports[DZapAbis.dZapCoreV2Abi];
11005
+ default:
11006
+ throw new Error("Invalid Version for Trade");
11007
+ }
11008
+ case Services.dca:
11009
+ return artifacts_exports[DZapAbis.dZapDcaAbi];
11010
+ case Services.zap:
11011
+ default:
11012
+ throw new Error("Invalid Service");
11013
+ }
11014
+ };
11015
+ var getOtherAbis = (name) => {
11016
+ switch (name) {
11017
+ case OtherAbis.permit2:
11018
+ return abi4;
11019
+ case OtherAbis.erc20:
11020
+ return abi5;
11021
+ default:
11022
+ throw new Error("Invalid Abi");
11023
+ }
11024
+ };
11025
+ var BRIDGE_ERRORS = {
11026
+ BridgeCallFailed: "BridgeCallFailed"
11027
+ };
11028
+ function getErrorName(errorString) {
11029
+ const match = errorString.match(/Error: (\w+)/);
11030
+ return match ? match[1] : null;
11031
+ }
11032
+ var getRevertMsg = (res) => {
11033
+ if (res.length < 68) {
11034
+ return res;
11035
+ }
11036
+ const revertData = "0x" + res.slice(10);
11037
+ const msg = viem.decodeAbiParameters(viem.parseAbiParameters("string"), revertData)[0];
11038
+ return msg;
11039
+ };
11040
+ var isAxiosError = (error) => {
11041
+ return Boolean(error) && error.isAxiosError;
11042
+ };
11043
+ var handleViemTransactionError = ({ error }) => {
11044
+ var _a, _b;
11045
+ if ((error == null ? void 0 : error.code) === 429 /* WalletRPCFailure */ || ((_a = error == null ? void 0 : error.cause) == null ? void 0 : _a.code) === 429 /* WalletRPCFailure */) {
11046
+ return {
11047
+ error,
11048
+ errorMsg: "Too many requests, failure on user wallet",
11049
+ code: 429 /* WalletRPCFailure */,
11050
+ status: "error" /* error */
11051
+ };
11052
+ }
11053
+ if ((error == null ? void 0 : error.code) === 4001 /* UserRejectedRequest */ || ((_b = error == null ? void 0 : error.cause) == null ? void 0 : _b.code) === 4001 /* UserRejectedRequest */) {
11054
+ return {
11055
+ error,
11056
+ errorMsg: "Rejected by User",
11057
+ code: 4001 /* UserRejectedRequest */,
11058
+ status: "rejected" /* rejected */
11059
+ };
11060
+ }
11061
+ let errMsg = error.shortMessage;
11062
+ const errName = getErrorName(error.metaMessages[0]);
11063
+ if (errName == BRIDGE_ERRORS.BridgeCallFailed) {
11064
+ let msg = error.metaMessages[1];
11065
+ try {
11066
+ msg = getRevertMsg(error.metaMessages[1].match(/\((.*?)\)/)[1]);
11067
+ } catch (err) {
11068
+ }
11069
+ errMsg = `${BRIDGE_ERRORS.BridgeCallFailed} : ${msg}`;
11070
+ } else if (errName) {
11071
+ errMsg = errName;
11072
+ }
11073
+ return {
11074
+ status: "error" /* error */,
11075
+ error,
11076
+ errorMsg: errMsg,
11077
+ code: -500 /* ContractExecutionError */
11078
+ };
11079
+ };
11080
+
11081
+ // src/transactionHandlers/generic.ts
11082
+ var GenericTxnHandler = class {
11083
+ };
11084
+ GenericTxnHandler.sendTransaction = async ({
11085
+ chainId,
11086
+ signer,
11087
+ from,
11088
+ to,
11089
+ data,
11090
+ value
11091
+ }) => {
11092
+ try {
11093
+ if (isTypeSigner(signer)) {
11094
+ console.log("Using ethers signer.");
11095
+ const txnRes = await signer.sendTransaction({
11096
+ from,
11097
+ to,
11098
+ data,
11099
+ value
11100
+ });
11101
+ return {
11102
+ status: "success" /* success */,
11103
+ code: 200 /* Success */,
11104
+ txnHash: txnRes.hash
11105
+ };
11106
+ } else {
11107
+ console.log("Using viem walletClient.");
11108
+ const txnHash = await signer.sendTransaction({
11109
+ chain: viemChainsById[chainId],
11110
+ account: from,
11111
+ to,
11112
+ data,
11113
+ value: BigInt(value)
11114
+ });
11115
+ return {
11116
+ status: "success" /* success */,
11117
+ code: 200 /* Success */,
11118
+ txnHash
11119
+ };
11120
+ }
11121
+ } catch (error) {
11122
+ console.log({ error });
11123
+ return handleViemTransactionError({ error });
11124
+ }
11125
+ };
11126
+ var generic_default = GenericTxnHandler;
11127
+
11128
+ // src/types/eip-2612.ts
11129
+ var EIP2612DefaultTypes = {
11130
+ Permit: [
11183
11131
  {
11184
- inputs: [
11185
- {
11186
- internalType: "bytes32",
11187
- name: "_transactionId",
11188
- type: "bytes32"
11189
- },
11190
- {
11191
- internalType: "bytes",
11192
- name: "_feeData",
11193
- type: "bytes"
11194
- },
11195
- {
11196
- internalType: "bytes",
11197
- name: "_feeVerificationSignature",
11198
- type: "bytes"
11199
- },
11200
- {
11201
- internalType: "uint256",
11202
- name: "_deadline",
11203
- type: "uint256"
11204
- },
11205
- {
11206
- components: [
11207
- {
11208
- internalType: "address",
11209
- name: "token",
11210
- type: "address"
11211
- },
11212
- {
11213
- internalType: "uint256",
11214
- name: "amount",
11215
- type: "uint256"
11216
- },
11217
- {
11218
- internalType: "bytes",
11219
- name: "permit",
11220
- type: "bytes"
11221
- }
11222
- ],
11223
- internalType: "struct InputToken[]",
11224
- name: "_inputTokens",
11225
- type: "tuple[]"
11226
- },
11227
- {
11228
- components: [
11229
- {
11230
- internalType: "address",
11231
- name: "recipient",
11232
- type: "address"
11233
- },
11234
- {
11235
- internalType: "address",
11236
- name: "from",
11237
- type: "address"
11238
- },
11239
- {
11240
- internalType: "address",
11241
- name: "to",
11242
- type: "address"
11243
- },
11244
- {
11245
- internalType: "uint256",
11246
- name: "fromAmount",
11247
- type: "uint256"
11248
- },
11249
- {
11250
- internalType: "uint256",
11251
- name: "minToAmount",
11252
- type: "uint256"
11253
- }
11254
- ],
11255
- internalType: "struct SwapData[]",
11256
- name: "_swapData",
11257
- type: "tuple[]"
11258
- },
11259
- {
11260
- components: [
11261
- {
11262
- internalType: "string",
11263
- name: "dex",
11264
- type: "string"
11265
- },
11266
- {
11267
- internalType: "address",
11268
- name: "callTo",
11269
- type: "address"
11270
- },
11271
- {
11272
- internalType: "address",
11273
- name: "approveTo",
11274
- type: "address"
11275
- },
11276
- {
11277
- internalType: "bytes",
11278
- name: "swapCallData",
11279
- type: "bytes"
11280
- },
11281
- {
11282
- internalType: "bool",
11283
- name: "isDirectTransfer",
11284
- type: "bool"
11285
- }
11286
- ],
11287
- internalType: "struct SwapExecutionData[]",
11288
- name: "_swapExecutionData",
11289
- type: "tuple[]"
11290
- },
11291
- {
11292
- internalType: "bool",
11293
- name: "withoutRevert",
11294
- type: "bool"
11295
- }
11296
- ],
11297
- name: "swap",
11298
- outputs: [],
11299
- stateMutability: "payable",
11300
- type: "function"
11301
- }
11302
- ],
11303
- GaslessExecuteMultiSwapAbi: [
11132
+ name: "owner",
11133
+ type: "address"
11134
+ },
11304
11135
  {
11305
- inputs: [
11306
- {
11307
- internalType: "bytes32",
11308
- name: "_transactionId",
11309
- type: "bytes32"
11310
- },
11311
- {
11312
- internalType: "bytes",
11313
- name: "_feeData",
11314
- type: "bytes"
11315
- },
11316
- {
11317
- internalType: "bytes",
11318
- name: "_feeVerificationSignature",
11319
- type: "bytes"
11320
- },
11321
- {
11322
- internalType: "bytes",
11323
- name: "_userIntentSignature",
11324
- type: "bytes"
11325
- },
11326
- {
11327
- internalType: "uint256",
11328
- name: "_userIntentDeadline",
11329
- type: "uint256"
11330
- },
11331
- {
11332
- internalType: "uint256",
11333
- name: "_feeDeadline",
11334
- type: "uint256"
11335
- },
11336
- {
11337
- internalType: "address",
11338
- name: "_user",
11339
- type: "address"
11340
- },
11341
- {
11342
- components: [
11343
- {
11344
- internalType: "address",
11345
- name: "token",
11346
- type: "address"
11347
- },
11348
- {
11349
- internalType: "uint256",
11350
- name: "amount",
11351
- type: "uint256"
11352
- },
11353
- {
11354
- internalType: "bytes",
11355
- name: "permit",
11356
- type: "bytes"
11357
- }
11358
- ],
11359
- internalType: "struct InputToken[]",
11360
- name: "_inputTokens",
11361
- type: "tuple[]"
11362
- },
11363
- {
11364
- components: [
11365
- {
11366
- internalType: "address",
11367
- name: "token",
11368
- type: "address"
11369
- },
11370
- {
11371
- internalType: "uint256",
11372
- name: "amount",
11373
- type: "uint256"
11374
- }
11375
- ],
11376
- internalType: "struct TokenInfo[]",
11377
- name: "_executorFeeInfo",
11378
- type: "tuple[]"
11379
- },
11380
- {
11381
- components: [
11382
- {
11383
- internalType: "address",
11384
- name: "recipient",
11385
- type: "address"
11386
- },
11387
- {
11388
- internalType: "address",
11389
- name: "from",
11390
- type: "address"
11391
- },
11392
- {
11393
- internalType: "address",
11394
- name: "to",
11395
- type: "address"
11396
- },
11397
- {
11398
- internalType: "uint256",
11399
- name: "fromAmount",
11400
- type: "uint256"
11401
- },
11402
- {
11403
- internalType: "uint256",
11404
- name: "minToAmount",
11405
- type: "uint256"
11406
- }
11407
- ],
11408
- internalType: "struct SwapData[]",
11409
- name: "_swapData",
11410
- type: "tuple[]"
11411
- },
11412
- {
11413
- components: [
11414
- {
11415
- internalType: "string",
11416
- name: "dex",
11417
- type: "string"
11418
- },
11419
- {
11420
- internalType: "address",
11421
- name: "callTo",
11422
- type: "address"
11423
- },
11424
- {
11425
- internalType: "address",
11426
- name: "approveTo",
11427
- type: "address"
11428
- },
11429
- {
11430
- internalType: "bytes",
11431
- name: "swapCallData",
11432
- type: "bytes"
11433
- },
11434
- {
11435
- internalType: "bool",
11436
- name: "isDirectTransfer",
11437
- type: "bool"
11438
- }
11439
- ],
11440
- internalType: "struct SwapExecutionData[]",
11441
- name: "_swapExecutionData",
11442
- type: "tuple[]"
11443
- }
11444
- ],
11445
- name: "executeMultiSwap",
11446
- outputs: [],
11447
- stateMutability: "payable",
11448
- type: "function"
11449
- }
11450
- ],
11451
- GaslessExecuteMultiSwapWithWitnessAbi: [
11452
- {
11453
- inputs: [
11454
- {
11455
- internalType: "bytes32",
11456
- name: "_transactionId",
11457
- type: "bytes32"
11458
- },
11459
- {
11460
- internalType: "bytes",
11461
- name: "_feeData",
11462
- type: "bytes"
11463
- },
11464
- {
11465
- internalType: "bytes",
11466
- name: "_feeVerificationSignature",
11467
- type: "bytes"
11468
- },
11469
- {
11470
- internalType: "bytes",
11471
- name: "_userIntentSignature",
11472
- type: "bytes"
11473
- },
11474
- {
11475
- internalType: "uint256",
11476
- name: "_feeDeadline",
11477
- type: "uint256"
11478
- },
11479
- {
11480
- internalType: "address",
11481
- name: "_user",
11482
- type: "address"
11483
- },
11484
- {
11485
- components: [
11486
- {
11487
- components: [
11488
- {
11489
- internalType: "address",
11490
- name: "token",
11491
- type: "address"
11492
- },
11493
- {
11494
- internalType: "uint256",
11495
- name: "amount",
11496
- type: "uint256"
11497
- }
11498
- ],
11499
- internalType: "struct TokenPermissions[]",
11500
- name: "permitted",
11501
- type: "tuple[]"
11502
- },
11503
- {
11504
- internalType: "uint256",
11505
- name: "nonce",
11506
- type: "uint256"
11507
- },
11508
- {
11509
- internalType: "uint256",
11510
- name: "deadline",
11511
- type: "uint256"
11512
- }
11513
- ],
11514
- internalType: "struct PermitBatchTransferFrom",
11515
- name: "_tokenDepositDetails",
11516
- type: "tuple"
11517
- },
11518
- {
11519
- components: [
11520
- {
11521
- internalType: "address",
11522
- name: "token",
11523
- type: "address"
11524
- },
11525
- {
11526
- internalType: "uint256",
11527
- name: "amount",
11528
- type: "uint256"
11529
- }
11530
- ],
11531
- internalType: "struct TokenInfo[]",
11532
- name: "_executorFeeInfo",
11533
- type: "tuple[]"
11534
- },
11535
- {
11536
- components: [
11537
- {
11538
- internalType: "address",
11539
- name: "recipient",
11540
- type: "address"
11541
- },
11542
- {
11543
- internalType: "address",
11544
- name: "from",
11545
- type: "address"
11546
- },
11547
- {
11548
- internalType: "address",
11549
- name: "to",
11550
- type: "address"
11551
- },
11552
- {
11553
- internalType: "uint256",
11554
- name: "fromAmount",
11555
- type: "uint256"
11556
- },
11557
- {
11558
- internalType: "uint256",
11559
- name: "minToAmount",
11560
- type: "uint256"
11561
- }
11562
- ],
11563
- internalType: "struct SwapData[]",
11564
- name: "_swapData",
11565
- type: "tuple[]"
11566
- },
11567
- {
11568
- components: [
11569
- {
11570
- internalType: "string",
11571
- name: "dex",
11572
- type: "string"
11573
- },
11574
- {
11575
- internalType: "address",
11576
- name: "callTo",
11577
- type: "address"
11578
- },
11579
- {
11580
- internalType: "address",
11581
- name: "approveTo",
11582
- type: "address"
11583
- },
11584
- {
11585
- internalType: "bytes",
11586
- name: "swapCallData",
11587
- type: "bytes"
11588
- },
11589
- {
11590
- internalType: "bool",
11591
- name: "isDirectTransfer",
11592
- type: "bool"
11593
- }
11594
- ],
11595
- internalType: "struct SwapExecutionData[]",
11596
- name: "_swapExecutionData",
11597
- type: "tuple[]"
11598
- }
11599
- ],
11600
- name: "executeMultiSwapWithWitness",
11601
- outputs: [],
11602
- stateMutability: "payable",
11603
- type: "function"
11604
- }
11605
- ],
11606
- GaslessExecuteSwapAbi: [
11607
- {
11608
- inputs: [
11609
- {
11610
- internalType: "bytes32",
11611
- name: "_transactionId",
11612
- type: "bytes32"
11613
- },
11614
- {
11615
- internalType: "bytes",
11616
- name: "_feeData",
11617
- type: "bytes"
11618
- },
11619
- {
11620
- internalType: "bytes",
11621
- name: "_feeVerificationSignature",
11622
- type: "bytes"
11623
- },
11624
- {
11625
- internalType: "bytes",
11626
- name: "_userIntentSignature",
11627
- type: "bytes"
11628
- },
11629
- {
11630
- internalType: "uint256",
11631
- name: "_userIntentDeadline",
11632
- type: "uint256"
11633
- },
11634
- {
11635
- internalType: "uint256",
11636
- name: "_feeDeadline",
11637
- type: "uint256"
11638
- },
11639
- {
11640
- internalType: "address",
11641
- name: "_user",
11642
- type: "address"
11643
- },
11644
- {
11645
- components: [
11646
- {
11647
- internalType: "address",
11648
- name: "token",
11649
- type: "address"
11650
- },
11651
- {
11652
- internalType: "uint256",
11653
- name: "amount",
11654
- type: "uint256"
11655
- },
11656
- {
11657
- internalType: "bytes",
11658
- name: "permit",
11659
- type: "bytes"
11660
- }
11661
- ],
11662
- internalType: "struct InputToken",
11663
- name: "_inputToken",
11664
- type: "tuple"
11665
- },
11666
- {
11667
- components: [
11668
- {
11669
- internalType: "address",
11670
- name: "token",
11671
- type: "address"
11672
- },
11673
- {
11674
- internalType: "uint256",
11675
- name: "amount",
11676
- type: "uint256"
11677
- }
11678
- ],
11679
- internalType: "struct TokenInfo",
11680
- name: "_executorFeeInfo",
11681
- type: "tuple"
11682
- },
11683
- {
11684
- components: [
11685
- {
11686
- internalType: "address",
11687
- name: "recipient",
11688
- type: "address"
11689
- },
11690
- {
11691
- internalType: "address",
11692
- name: "from",
11693
- type: "address"
11694
- },
11695
- {
11696
- internalType: "address",
11697
- name: "to",
11698
- type: "address"
11699
- },
11700
- {
11701
- internalType: "uint256",
11702
- name: "fromAmount",
11703
- type: "uint256"
11704
- },
11705
- {
11706
- internalType: "uint256",
11707
- name: "minToAmount",
11708
- type: "uint256"
11709
- }
11710
- ],
11711
- internalType: "struct SwapData",
11712
- name: "_swapData",
11713
- type: "tuple"
11714
- },
11715
- {
11716
- components: [
11717
- {
11718
- internalType: "string",
11719
- name: "dex",
11720
- type: "string"
11721
- },
11722
- {
11723
- internalType: "address",
11724
- name: "callTo",
11725
- type: "address"
11726
- },
11727
- {
11728
- internalType: "address",
11729
- name: "approveTo",
11730
- type: "address"
11731
- },
11732
- {
11733
- internalType: "bytes",
11734
- name: "swapCallData",
11735
- type: "bytes"
11736
- },
11737
- {
11738
- internalType: "bool",
11739
- name: "isDirectTransfer",
11740
- type: "bool"
11741
- }
11742
- ],
11743
- internalType: "struct SwapExecutionData",
11744
- name: "_swapExecutionData",
11745
- type: "tuple"
11746
- }
11747
- ],
11748
- name: "executeSwap",
11749
- outputs: [],
11750
- stateMutability: "payable",
11751
- type: "function"
11752
- }
11753
- ]
11754
- };
11755
-
11756
- // src/utils/decoder/swap/inputDataDecoder.ts
11757
- var SwapInputDataDecoder = class {
11758
- constructor() {
11759
- this.decodeSingleSwapData = (data) => {
11760
- var _a;
11761
- const decodedData = utils.decodeFunctionData({
11762
- data,
11763
- abi: SwapAbisByFunctionName.SingleSwap
11764
- });
11765
- return [(_a = decodedData == null ? void 0 : decodedData.args) == null ? void 0 : _a[4]];
11766
- };
11767
- this.decodeMultiSwapData = (data) => {
11768
- var _a;
11769
- const decodedData = utils.decodeFunctionData({
11770
- data,
11771
- abi: SwapAbisByFunctionName.MultiSwapAbi
11772
- });
11773
- return (_a = decodedData == null ? void 0 : decodedData.args) == null ? void 0 : _a[4];
11774
- };
11775
- this.decodeBatchPermitSwapData = (data) => {
11776
- var _a, _b;
11777
- const decodedData = utils.decodeFunctionData({
11778
- data,
11779
- abi: SwapAbisByFunctionName.BatchPermitSwapAbi
11780
- });
11781
- const permitData = (_b = (_a = decodedData == null ? void 0 : decodedData.args) == null ? void 0 : _a[5]) == null ? void 0 : _b.permitted;
11782
- return permitData;
11783
- };
11784
- this.decodeGaslessExecuteMultiSwapData = (data) => {
11785
- var _a;
11786
- const decodedData = utils.decodeFunctionData({
11787
- data,
11788
- abi: SwapAbisByFunctionName.GaslessExecuteMultiSwapAbi
11789
- });
11790
- return (_a = decodedData == null ? void 0 : decodedData.args) == null ? void 0 : _a[7];
11791
- };
11792
- this.decodeGaslessExecuteMultiSwapWithWitnessData = (data) => {
11793
- var _a;
11794
- const decodedData = utils.decodeFunctionData({
11795
- data,
11796
- abi: SwapAbisByFunctionName.GaslessExecuteMultiSwapWithWitnessAbi
11797
- });
11798
- return (_a = decodedData == null ? void 0 : decodedData.args) == null ? void 0 : _a[7];
11799
- };
11800
- this.decodeGaslessExecuteSwapData = (data) => {
11801
- var _a;
11802
- const decodedData = utils.decodeFunctionData({
11803
- data,
11804
- abi: SwapAbisByFunctionName.GaslessExecuteSwapAbi
11805
- });
11806
- return [(_a = decodedData == null ? void 0 : decodedData.args) == null ? void 0 : _a[7]];
11807
- };
11808
- this.swapFunctionSignatureWithInputTokenIndex = {
11809
- "0x50d52584": {
11810
- name: "singleSwap",
11811
- decoder: this.decodeSingleSwapData
11812
- },
11813
- "0x8de34776": {
11814
- name: "multiSwap",
11815
- decoder: this.decodeMultiSwapData
11816
- },
11817
- "0x8d44ea24": {
11818
- name: "batchPermitSwap",
11819
- decoder: this.decodeBatchPermitSwapData
11820
- },
11821
- "0xd367ada5": {
11822
- name: "gaslessExecuteMultiSwap",
11823
- decoder: this.decodeGaslessExecuteMultiSwapData
11824
- },
11825
- "0xdcdc6089": {
11826
- name: "gaslessExecuteMultiSwapWithWitness",
11827
- decoder: this.decodeGaslessExecuteMultiSwapWithWitnessData
11828
- },
11829
- "0x0d2eedd4": {
11830
- name: "gaslessExecuteSwap",
11831
- decoder: this.decodeGaslessExecuteSwapData
11832
- }
11833
- };
11834
- this.updateSwapInfo = ({
11835
- data,
11836
- eventSwapInfo
11837
- }) => {
11838
- var _a;
11839
- try {
11840
- if (!data || !eventSwapInfo || data === "0x") {
11841
- return eventSwapInfo;
11842
- }
11843
- const functionSignature = data.slice(0, 10);
11844
- const decoder = (_a = this.swapFunctionSignatureWithInputTokenIndex[functionSignature]) == null ? void 0 : _a.decoder;
11845
- if (!decoder) {
11846
- return eventSwapInfo;
11847
- }
11848
- const inputTokenData = decoder(data);
11849
- if (!inputTokenData || inputTokenData.length === 0) {
11850
- return eventSwapInfo;
11851
- }
11852
- const tokenToAmount = inputTokenData.filter((item) => item.token && item.amount).reduce(
11853
- (acc, cur) => {
11854
- acc[formatToken(cur.token)] = cur.amount;
11855
- return acc;
11856
- },
11857
- {}
11858
- );
11859
- if (Array.isArray(eventSwapInfo)) {
11860
- return eventSwapInfo.map((item) => {
11861
- const formattedSrcToken = formatToken(item.fromToken);
11862
- const inputAmount = tokenToAmount[formattedSrcToken] || item.fromAmount;
11863
- return {
11864
- ...item,
11865
- fromAmount: inputAmount
11866
- };
11867
- });
11868
- } else {
11869
- const formattedSrcToken = formatToken(eventSwapInfo.fromToken);
11870
- const inputAmount = tokenToAmount[formattedSrcToken] || eventSwapInfo.fromAmount;
11871
- return {
11872
- ...eventSwapInfo,
11873
- fromAmount: inputAmount
11874
- };
11875
- }
11876
- } catch (error) {
11877
- return eventSwapInfo;
11878
- }
11879
- };
11880
- }
11881
- };
11882
-
11883
- // src/utils/index.ts
11884
- var publicClientRpcConfig = { batch: { wait: RPC_BATCHING_WAIT_TIME }, retryDelay: RPC_RETRY_DELAY };
11885
- var getPublicClient = ({ rpcUrls, chainId }) => {
11886
- var _a, _b;
11887
- const chain = viemChainsById[chainId];
11888
- const urls = ((rpcUrls == null ? void 0 : rpcUrls.length) ? rpcUrls : (_b = (_a = chain == null ? void 0 : chain.rpcUrls) == null ? void 0 : _a.default) == null ? void 0 : _b.http) ?? [];
11889
- const transports = urls.length ? urls.map((url) => viem.http(url, publicClientRpcConfig)) : [viem.http()];
11890
- return viem.createPublicClient({
11891
- chain,
11892
- transport: viem.fallback(transports),
11893
- batch: {
11894
- multicall: {
11895
- wait: RPC_BATCHING_WAIT_TIME
11896
- }
11897
- }
11898
- });
11899
- };
11900
- function getTokensPairKey({
11901
- srcToken,
11902
- destToken,
11903
- srcChainId,
11904
- destChainId,
11905
- srcChainNativeAddress = viem.zeroAddress,
11906
- destChainNativeAddress = viem.zeroAddress
11907
- }) {
11908
- const srcFormattedAddress = formatToken(srcToken, srcChainNativeAddress);
11909
- const destFormattedAddress = formatToken(destToken, destChainNativeAddress);
11910
- return `${srcChainId}_${srcFormattedAddress}-${destChainId}_${destFormattedAddress}`;
11911
- }
11912
- var writeContract = async ({
11913
- chainId,
11914
- contractAddress,
11915
- abi: abi7,
11916
- functionName,
11917
- args = [],
11918
- value = "0",
11919
- rpcUrls = [""],
11920
- signer
11921
- }) => {
11922
- const publicClient = getPublicClient({ chainId, rpcUrls });
11923
- try {
11924
- const { request } = await publicClient.simulateContract({
11925
- address: contractAddress,
11926
- abi: abi7,
11927
- functionName,
11928
- args,
11929
- account: signer.account,
11930
- value: BigInt(value)
11931
- });
11932
- const hash = await signer.writeContract(request);
11933
- return { txnHash: hash, status: "success" /* success */, code: 200 /* Success */ };
11934
- } catch (e) {
11935
- console.log({ e });
11936
- if ((e == null ? void 0 : e.code) === 4001 /* UserRejectedRequest */) {
11937
- return { status: "rejected" /* rejected */, code: e == null ? void 0 : e.code, txnHash: "" };
11938
- }
11939
- return { status: "error" /* error */, code: e == null ? void 0 : e.code, txnHash: "" };
11940
- }
11941
- };
11942
- var calcTotalSrcTokenAmount = (data) => {
11943
- return data.reduce((acc, obj) => {
11944
- return acc + BigInt(obj.amount);
11945
- }, BigInt(0));
11946
- };
11947
- var isOneToMany = (firstTokenAddress, secondTokenAddress) => firstTokenAddress === secondTokenAddress;
11948
- BigInt(15) / BigInt(10);
11949
- var isTypeSigner = (variable) => {
11950
- return variable instanceof ethers.Signer;
11951
- };
11952
- var isDZapNativeToken = (srcToken) => srcToken === dZapNativeTokenFormat;
11953
- var getDZapAbi = (service, version) => {
11954
- switch (service) {
11955
- case Services.trade:
11956
- switch (version) {
11957
- case "v1" /* v1 */:
11958
- return artifacts_exports[DZapAbis.dZapCoreAbi];
11959
- case "v2" /* v2 */:
11960
- return artifacts_exports[DZapAbis.dZapCoreV2Abi];
11961
- default:
11962
- throw new Error("Invalid Version for Trade");
11963
- }
11964
- case Services.dca:
11965
- return artifacts_exports[DZapAbis.dZapDcaAbi];
11966
- case Services.zap:
11967
- default:
11968
- throw new Error("Invalid Service");
11969
- }
11970
- };
11971
- var handleDecodeTxnData = (transaction, receipt, service, chain) => {
11972
- var _a, _b, _c, _d, _e;
11973
- let events = [];
11974
- const dZapAbi = getDZapAbi(service, (chain == null ? void 0 : chain.version) || "v1" /* v1 */);
11975
- try {
11976
- events = viem.parseEventLogs({
11977
- abi: dZapAbi,
11978
- logs: receipt.logs
11979
- });
11980
- } catch (e) {
11981
- events = [];
11982
- }
11983
- events = events == null ? void 0 : events.filter((item) => item !== null);
11984
- const txLogArgs = (_a = events[0]) == null ? void 0 : _a.args;
11985
- const swapFailPairs = [];
11986
- let swapInfo = [];
11987
- if (Array.isArray(txLogArgs == null ? void 0 : txLogArgs.swapInfo)) {
11988
- swapInfo = txLogArgs.swapInfo.map((info) => {
11989
- var _a2, _b2, _c2, _d2;
11990
- if (BigInt(info.returnToAmount) === BigInt(0) || BigInt(info.fromAmount) === BigInt(0)) {
11991
- swapFailPairs.push(
11992
- getTokensPairKey({
11993
- srcToken: info.fromToken,
11994
- destToken: info.toToken,
11995
- srcChainId: chain.chainId,
11996
- destChainId: chain.chainId,
11997
- srcChainNativeAddress: (_a2 = chain == null ? void 0 : chain.nativeToken) == null ? void 0 : _a2.contract,
11998
- destChainNativeAddress: (_b2 = chain == null ? void 0 : chain.nativeToken) == null ? void 0 : _b2.contract
11999
- })
12000
- );
12001
- }
12002
- return {
12003
- ...info,
12004
- fromToken: formatToken(info.fromToken, (_c2 = chain == null ? void 0 : chain.nativeToken) == null ? void 0 : _c2.contract),
12005
- toToken: formatToken(info.toToken, (_d2 = chain == null ? void 0 : chain.nativeToken) == null ? void 0 : _d2.contract)
12006
- };
12007
- });
12008
- } else if (typeof (txLogArgs == null ? void 0 : txLogArgs.swapInfo) === "object" && Object.keys(txLogArgs == null ? void 0 : txLogArgs.swapInfo).length > 0) {
12009
- const { fromAmount, returnToAmount, fromToken, toToken } = txLogArgs.swapInfo;
12010
- if (BigInt(returnToAmount) === BigInt(0) || BigInt(fromAmount) === BigInt(0)) {
12011
- swapFailPairs.push(
12012
- getTokensPairKey({
12013
- srcToken: fromToken,
12014
- destToken: toToken,
12015
- srcChainId: chain.chainId,
12016
- destChainId: chain.chainId,
12017
- srcChainNativeAddress: (_b = chain == null ? void 0 : chain.nativeToken) == null ? void 0 : _b.contract,
12018
- destChainNativeAddress: (_c = chain == null ? void 0 : chain.nativeToken) == null ? void 0 : _c.contract
12019
- })
12020
- );
12021
- }
12022
- swapInfo = {
12023
- ...txLogArgs.swapInfo,
12024
- fromToken: formatToken(txLogArgs.swapInfo.fromToken, (_d = chain == null ? void 0 : chain.nativeToken) == null ? void 0 : _d.contract),
12025
- toToken: formatToken(txLogArgs.swapInfo.toToken, (_e = chain == null ? void 0 : chain.nativeToken) == null ? void 0 : _e.contract)
12026
- };
12027
- }
12028
- const updatedSwapInfo = new SwapInputDataDecoder().updateSwapInfo({
12029
- data: transaction.input,
12030
- eventSwapInfo: swapInfo
12031
- }) || swapInfo;
12032
- return { swapInfo: updatedSwapInfo, swapFailPairs };
12033
- };
12034
- var getOtherAbis = (name) => {
12035
- switch (name) {
12036
- case OtherAbis.permit2:
12037
- return abi4;
12038
- case OtherAbis.erc20:
12039
- return abi5;
12040
- default:
12041
- throw new Error("Invalid Abi");
12042
- }
12043
- };
12044
- var BRIDGE_ERRORS = {
12045
- BridgeCallFailed: "BridgeCallFailed"
12046
- };
12047
- function getErrorName(errorString) {
12048
- const match = errorString.match(/Error: (\w+)/);
12049
- return match ? match[1] : null;
12050
- }
12051
- var getRevertMsg = (res) => {
12052
- if (res.length < 68) {
12053
- return res;
12054
- }
12055
- const revertData = "0x" + res.slice(10);
12056
- const msg = viem.decodeAbiParameters(viem.parseAbiParameters("string"), revertData)[0];
12057
- return msg;
12058
- };
12059
- var isAxiosError = (error) => {
12060
- return Boolean(error) && error.isAxiosError;
12061
- };
12062
- var handleViemTransactionError = ({ error }) => {
12063
- var _a, _b;
12064
- if ((error == null ? void 0 : error.code) === 429 /* WalletRPCFailure */ || ((_a = error == null ? void 0 : error.cause) == null ? void 0 : _a.code) === 429 /* WalletRPCFailure */) {
12065
- return {
12066
- error,
12067
- errorMsg: "Too many requests, failure on user wallet",
12068
- code: 429 /* WalletRPCFailure */,
12069
- status: "error" /* error */
12070
- };
12071
- }
12072
- if ((error == null ? void 0 : error.code) === 4001 /* UserRejectedRequest */ || ((_b = error == null ? void 0 : error.cause) == null ? void 0 : _b.code) === 4001 /* UserRejectedRequest */) {
12073
- return {
12074
- error,
12075
- errorMsg: "Rejected by User",
12076
- code: 4001 /* UserRejectedRequest */,
12077
- status: "rejected" /* rejected */
12078
- };
12079
- }
12080
- let errMsg = error.shortMessage;
12081
- const errName = getErrorName(error.metaMessages[0]);
12082
- if (errName == BRIDGE_ERRORS.BridgeCallFailed) {
12083
- let msg = error.metaMessages[1];
12084
- try {
12085
- msg = getRevertMsg(error.metaMessages[1].match(/\((.*?)\)/)[1]);
12086
- } catch (err) {
12087
- }
12088
- errMsg = `${BRIDGE_ERRORS.BridgeCallFailed} : ${msg}`;
12089
- } else if (errName) {
12090
- errMsg = errName;
12091
- }
12092
- return {
12093
- status: "error" /* error */,
12094
- error,
12095
- errorMsg: errMsg,
12096
- code: -500 /* ContractExecutionError */
12097
- };
12098
- };
12099
-
12100
- // src/transactionHandlers/generic.ts
12101
- var GenericTxnHandler = class {
12102
- };
12103
- GenericTxnHandler.sendTransaction = async ({
12104
- chainId,
12105
- signer,
12106
- from,
12107
- to,
12108
- data,
12109
- value
12110
- }) => {
12111
- try {
12112
- if (isTypeSigner(signer)) {
12113
- console.log("Using ethers signer.");
12114
- const txnRes = await signer.sendTransaction({
12115
- from,
12116
- to,
12117
- data,
12118
- value
12119
- });
12120
- return {
12121
- status: "success" /* success */,
12122
- code: 200 /* Success */,
12123
- txnHash: txnRes.hash
12124
- };
12125
- } else {
12126
- console.log("Using viem walletClient.");
12127
- const txnHash = await signer.sendTransaction({
12128
- chain: viemChainsById[chainId],
12129
- account: from,
12130
- to,
12131
- data,
12132
- value: BigInt(value)
12133
- });
12134
- return {
12135
- status: "success" /* success */,
12136
- code: 200 /* Success */,
12137
- txnHash
12138
- };
12139
- }
12140
- } catch (error) {
12141
- console.log({ error });
12142
- return handleViemTransactionError({ error });
12143
- }
12144
- };
12145
- var generic_default = GenericTxnHandler;
12146
-
12147
- // src/types/eip-2612.ts
12148
- var EIP2612DefaultTypes = {
12149
- Permit: [
12150
- {
12151
- name: "owner",
12152
- type: "address"
12153
- },
12154
- {
12155
- name: "spender",
12156
- type: "address"
12157
- },
11136
+ name: "spender",
11137
+ type: "address"
11138
+ },
12158
11139
  {
12159
11140
  name: "value",
12160
11141
  type: "uint256"
@@ -14394,897 +13375,2030 @@ var _PermitTxnHandler = class _PermitTxnHandler {
14394
13375
  permitType: PermitTypes.PermitBatchWitnessTransferFrom
14395
13376
  //override because only PermitBatchWitnessTransferFrom supports batch
14396
13377
  });
14397
- if (resp.status !== "success" /* success */) {
14398
- return { status: resp.status, code: resp.code, permitType: PermitTypes.PermitBatchWitnessTransferFrom };
14399
- }
14400
- if (signPermitReq.signatureCallback) {
14401
- await signPermitReq.signatureCallback({
14402
- batchPermitData: resp.permitData,
14403
- tokens,
14404
- permitType: resp.permitType
14405
- });
14406
- }
13378
+ if (resp.status !== "success" /* success */) {
13379
+ return { status: resp.status, code: resp.code, permitType: PermitTypes.PermitBatchWitnessTransferFrom };
13380
+ }
13381
+ if (signPermitReq.signatureCallback) {
13382
+ await signPermitReq.signatureCallback({
13383
+ batchPermitData: resp.permitData,
13384
+ tokens,
13385
+ permitType: resp.permitType
13386
+ });
13387
+ }
13388
+ return {
13389
+ status: "success" /* success */,
13390
+ code: 200 /* Success */,
13391
+ batchPermitData: resp.permitData,
13392
+ permitType: resp.permitType
13393
+ };
13394
+ } else {
13395
+ if (signPermitReq.permitType === PermitTypes.PermitBatchWitnessTransferFrom) {
13396
+ return { status: "error" /* error */, code: 500 /* Error */, permitType: PermitTypes.PermitBatchWitnessTransferFrom };
13397
+ }
13398
+ const totalSrcAmount = calcTotalSrcTokenAmount(tokens);
13399
+ let firstTokenNonce = null;
13400
+ let permitType = _PermitTxnHandler.v1PermitSupport({
13401
+ contractVersion: signPermitReq.contractVersion,
13402
+ service: signPermitReq.service
13403
+ }) ? PermitTypes.PermitSingle : signPermitReq.permitType;
13404
+ for (let dataIdx = 0; dataIdx < tokens.length; dataIdx++) {
13405
+ const isFirstToken = dataIdx === 0;
13406
+ const res = await _PermitTxnHandler.generatePermitDataForToken({
13407
+ ...signPermitReq,
13408
+ token: {
13409
+ ...tokens[dataIdx],
13410
+ index: dataIdx
13411
+ },
13412
+ firstTokenNonce: firstTokenNonce ?? void 0,
13413
+ oneToMany,
13414
+ totalSrcAmount,
13415
+ account: signPermitReq.sender,
13416
+ permitType
13417
+ });
13418
+ permitType = res.permitType;
13419
+ if (res.status !== "success" /* success */) {
13420
+ return { status: res.status, code: res.code, permitType: res.permitType };
13421
+ }
13422
+ tokens[dataIdx].permitData = res.permitData;
13423
+ if (isFirstToken && !isDZapNativeToken(tokens[dataIdx].address)) {
13424
+ firstTokenNonce = res.nonce ?? null;
13425
+ }
13426
+ if (signPermitReq.signatureCallback && !isDZapNativeToken(tokens[dataIdx].address)) {
13427
+ const amount = oneToMany && isFirstToken ? totalSrcAmount : BigInt(tokens[dataIdx].amount);
13428
+ await signPermitReq.signatureCallback({
13429
+ permitData: res.permitData,
13430
+ srcToken: tokens[dataIdx].address,
13431
+ amount: amount.toString(),
13432
+ permitType: res.permitType
13433
+ });
13434
+ }
13435
+ }
13436
+ return { status: "success" /* success */, tokens, code: 200 /* Success */, permitType };
13437
+ }
13438
+ }
13439
+ };
13440
+ _PermitTxnHandler.generateBatchPermitDataForTokens = async (params) => {
13441
+ const resp = await getPermit2Signature(params);
13442
+ return {
13443
+ ...resp,
13444
+ permitType: PermitTypes.PermitBatchWitnessTransferFrom
13445
+ };
13446
+ };
13447
+ _PermitTxnHandler.generatePermitDataForToken = async (params) => {
13448
+ const { token, oneToMany, totalSrcAmount, chainId, rpcUrls, permitType, account } = params;
13449
+ const isFirstToken = token.index === 0;
13450
+ if (isDZapNativeToken(token.address)) {
13451
+ return {
13452
+ status: "success" /* success */,
13453
+ code: 200 /* Success */,
13454
+ permitData: DEFAULT_PERMIT_DATA,
13455
+ nonce: BigInt(0),
13456
+ // For native tokens, nonce is not used
13457
+ permitType: PermitTypes.EIP2612Permit
13458
+ };
13459
+ }
13460
+ const amount = oneToMany && isFirstToken ? totalSrcAmount : BigInt(token.amount);
13461
+ const eip2612PermitData = await checkEIP2612PermitSupport({
13462
+ address: token.address,
13463
+ chainId,
13464
+ rpcUrls,
13465
+ owner: account,
13466
+ permit: token.permit
13467
+ });
13468
+ if (permitType === PermitTypes.EIP2612Permit || permitType === PermitTypes.AutoPermit && eip2612PermitData.supportsPermit) {
13469
+ if (!eip2612PermitData.supportsPermit || !eip2612PermitData.data) {
13470
+ throw new Error("Token does not support EIP-2612 permits");
13471
+ }
13472
+ if (oneToMany && !isFirstToken) {
13473
+ return {
13474
+ status: "success" /* success */,
13475
+ code: 200 /* Success */,
13476
+ permitData: DEFAULT_PERMIT_DATA,
13477
+ nonce: BigInt(0),
13478
+ // For EIP2612 permits, nonce is not used it's already set in permitData
13479
+ permitType: PermitTypes.EIP2612Permit
13480
+ };
13481
+ }
13482
+ const { permitData, status, code } = await getEIP2612PermitSignature({
13483
+ ...params,
13484
+ token: {
13485
+ address: token.address,
13486
+ amount: amount.toString(),
13487
+ index: 0,
13488
+ permit: token.permit
13489
+ },
13490
+ gasless: false,
13491
+ version: eip2612PermitData.data.version,
13492
+ name: eip2612PermitData.data.name,
13493
+ nonce: eip2612PermitData.data.nonce
13494
+ });
13495
+ return {
13496
+ status,
13497
+ code,
13498
+ permitData,
13499
+ nonce: BigInt(0),
13500
+ // For EIP2612 permits, nonce is not used
13501
+ permitType: PermitTypes.EIP2612Permit
13502
+ };
13503
+ } else {
13504
+ const normalizedPermitType = permitType === PermitTypes.AutoPermit ? PermitTypes.PermitWitnessTransferFrom : permitType;
13505
+ if (oneToMany && !isFirstToken) {
13506
+ return {
13507
+ status: "success" /* success */,
13508
+ code: 200 /* Success */,
13509
+ permitData: DEFAULT_PERMIT2_DATA,
13510
+ nonce: BigInt(0),
13511
+ // For one-to-many non-first tokens, nonce is not used
13512
+ permitType: normalizedPermitType
13513
+ };
13514
+ } else {
13515
+ const resp = await getPermit2Signature({
13516
+ ...params,
13517
+ tokens: [token],
13518
+ permitType: normalizedPermitType
13519
+ });
13520
+ return {
13521
+ ...resp,
13522
+ permitType: normalizedPermitType
13523
+ };
13524
+ }
13525
+ }
13526
+ };
13527
+ _PermitTxnHandler.signGaslessUserIntent = async (signPermitReq) => {
13528
+ const { tokens, sender, permitType } = signPermitReq;
13529
+ const type = permitType === PermitTypes.AutoPermit ? PermitTypes.PermitBatchWitnessTransferFrom : permitType;
13530
+ if (type === PermitTypes.EIP2612Permit) {
13531
+ const resp2 = await signGaslessDzapUserIntent({
13532
+ ...signPermitReq,
13533
+ account: sender
13534
+ });
13535
+ return {
13536
+ status: resp2.status,
13537
+ code: resp2.code,
13538
+ data: (resp2 == null ? void 0 : resp2.data) && {
13539
+ ...resp2.data,
13540
+ type
13541
+ }
13542
+ };
13543
+ }
13544
+ const resp = await getPermit2Signature({
13545
+ ...signPermitReq,
13546
+ tokens: tokens.map((token, index) => ({ ...token, index })),
13547
+ account: sender,
13548
+ permitType: type
13549
+ });
13550
+ return {
13551
+ status: resp.status,
13552
+ code: resp.code,
13553
+ data: resp.permitData && {
13554
+ type,
13555
+ batchPermitData: resp.permitData
13556
+ }
13557
+ };
13558
+ };
13559
+ _PermitTxnHandler.v1PermitSupport = ({ contractVersion, service }) => {
13560
+ return contractVersion === "v1" /* v1 */ && service !== Services.zap;
13561
+ };
13562
+ _PermitTxnHandler.shouldUseBatchPermit = ({
13563
+ permitType,
13564
+ isBatchPermitAllowed = true,
13565
+ tokens,
13566
+ oneToMany,
13567
+ contractVersion,
13568
+ service
13569
+ }) => {
13570
+ const isBatchPermitRequested = permitType === PermitTypes.PermitBatchWitnessTransferFrom;
13571
+ const shouldAutoBatch = permitType === PermitTypes.AutoPermit && (tokens == null ? void 0 : tokens.length) > 1 && !oneToMany;
13572
+ const isContractSupport = !_PermitTxnHandler.v1PermitSupport({ contractVersion, service });
13573
+ return isBatchPermitAllowed && (isBatchPermitRequested || shouldAutoBatch) && isContractSupport;
13574
+ };
13575
+ var PermitTxnHandler = _PermitTxnHandler;
13576
+ var permit_default = PermitTxnHandler;
13577
+ function encodeApproveCallData({ spender, amount }) {
13578
+ return viem.encodeFunctionData({
13579
+ abi: abi5,
13580
+ functionName: erc20Functions.approve,
13581
+ args: [spender, amount]
13582
+ });
13583
+ }
13584
+ var approveToken = async ({
13585
+ chainId,
13586
+ signer,
13587
+ rpcUrls,
13588
+ mode,
13589
+ tokens,
13590
+ approvalTxnCallback,
13591
+ spender
13592
+ }) => {
13593
+ if (mode !== ApprovalModes.Default) {
13594
+ spender = getPermit2Address(chainId);
13595
+ }
13596
+ for (let dataIdx = 0; dataIdx < tokens.length; dataIdx++) {
13597
+ let txnDetails = { status: "success" /* success */, code: 200 /* Success */, txnHash: "" };
13598
+ if (isTypeSigner(signer)) {
13599
+ const from = await signer.getAddress();
13600
+ const callData = viem.encodeFunctionData({
13601
+ abi: abi5,
13602
+ functionName: erc20Functions.approve,
13603
+ args: [spender, BigInt(tokens[dataIdx].amount)]
13604
+ });
13605
+ await signer.sendTransaction({
13606
+ from,
13607
+ chainId,
13608
+ to: tokens[dataIdx].address,
13609
+ data: callData
13610
+ });
14407
13611
  return {
14408
13612
  status: "success" /* success */,
14409
- code: 200 /* Success */,
14410
- batchPermitData: resp.permitData,
14411
- permitType: resp.permitType
13613
+ code: 200 /* Success */
14412
13614
  };
14413
13615
  } else {
14414
- if (signPermitReq.permitType === PermitTypes.PermitBatchWitnessTransferFrom) {
14415
- return { status: "error" /* error */, code: 500 /* Error */, permitType: PermitTypes.PermitBatchWitnessTransferFrom };
13616
+ txnDetails = await writeContract({
13617
+ chainId,
13618
+ contractAddress: tokens[dataIdx].address,
13619
+ abi: abi5,
13620
+ functionName: erc20Functions.approve,
13621
+ args: [spender, tokens[dataIdx].amount],
13622
+ rpcUrls,
13623
+ signer
13624
+ });
13625
+ }
13626
+ if (txnDetails.code !== 200 /* Success */) {
13627
+ return {
13628
+ status: txnDetails.status,
13629
+ code: (txnDetails == null ? void 0 : txnDetails.code) || 32771 /* FunctionNotFound */
13630
+ };
13631
+ }
13632
+ if (approvalTxnCallback) {
13633
+ const callbackStatus = await approvalTxnCallback({ txnDetails, address: tokens[dataIdx].address });
13634
+ if (callbackStatus && callbackStatus !== "success" /* success */) {
13635
+ return {
13636
+ status: txnDetails.status,
13637
+ code: (txnDetails == null ? void 0 : txnDetails.code) || 500 /* Error */
13638
+ };
14416
13639
  }
14417
- const totalSrcAmount = calcTotalSrcTokenAmount(tokens);
14418
- let firstTokenNonce = null;
14419
- let permitType = _PermitTxnHandler.v1PermitSupport({
14420
- contractVersion: signPermitReq.contractVersion,
14421
- service: signPermitReq.service
14422
- }) ? PermitTypes.PermitSingle : signPermitReq.permitType;
14423
- for (let dataIdx = 0; dataIdx < tokens.length; dataIdx++) {
14424
- const isFirstToken = dataIdx === 0;
14425
- const res = await _PermitTxnHandler.generatePermitDataForToken({
14426
- ...signPermitReq,
14427
- token: {
14428
- ...tokens[dataIdx],
14429
- index: dataIdx
14430
- },
14431
- firstTokenNonce: firstTokenNonce ?? void 0,
14432
- oneToMany,
14433
- totalSrcAmount,
14434
- account: signPermitReq.sender,
14435
- permitType
13640
+ }
13641
+ }
13642
+ return { status: "success" /* success */, code: 200 /* Success */ };
13643
+ };
13644
+ var batchGetAllowances = async ({
13645
+ chainId,
13646
+ data,
13647
+ owner,
13648
+ multicallAddress,
13649
+ rpcUrls
13650
+ }) => {
13651
+ const contracts = data.map(({ token, spender }) => ({
13652
+ address: token,
13653
+ abi: abi5,
13654
+ functionName: erc20Functions.allowance,
13655
+ args: [owner, spender]
13656
+ }));
13657
+ const {
13658
+ status,
13659
+ code,
13660
+ data: allowances
13661
+ } = await multicall({
13662
+ chainId,
13663
+ contracts,
13664
+ rpcUrls,
13665
+ multicallAddress,
13666
+ allowFailure: false
13667
+ });
13668
+ if (status !== "success" /* success */) {
13669
+ return { status, code, data: {} };
13670
+ }
13671
+ const tokenAllowances = {};
13672
+ for (let i = 0; i < data.length; i++) {
13673
+ tokenAllowances[data[i].token] = allowances[i];
13674
+ }
13675
+ return { status, code, data: tokenAllowances };
13676
+ };
13677
+ var getAllowance = async ({ chainId, sender, tokens, rpcUrls, multicallAddress, mode, spender }) => {
13678
+ const data = {};
13679
+ const nativeTokens2 = tokens.filter(({ address }) => isDZapNativeToken(address));
13680
+ const erc20Tokens = tokens.filter(({ address }) => !isDZapNativeToken(address));
13681
+ const approvalData = await Promise.all(
13682
+ erc20Tokens.map(async ({ address, permit }) => {
13683
+ if (mode === ApprovalModes.AutoPermit) {
13684
+ const eip2612PermitData = await checkEIP2612PermitSupport({
13685
+ address,
13686
+ chainId,
13687
+ rpcUrls,
13688
+ owner: sender,
13689
+ permit
14436
13690
  });
14437
- permitType = res.permitType;
14438
- if (res.status !== "success" /* success */) {
14439
- return { status: res.status, code: res.code, permitType: res.permitType };
14440
- }
14441
- tokens[dataIdx].permitData = res.permitData;
14442
- if (isFirstToken && !isDZapNativeToken(tokens[dataIdx].address)) {
14443
- firstTokenNonce = res.nonce ?? null;
14444
- }
14445
- if (signPermitReq.signatureCallback && !isDZapNativeToken(tokens[dataIdx].address)) {
14446
- const amount = oneToMany && isFirstToken ? totalSrcAmount : BigInt(tokens[dataIdx].amount);
14447
- await signPermitReq.signatureCallback({
14448
- permitData: res.permitData,
14449
- srcToken: tokens[dataIdx].address,
14450
- amount: amount.toString(),
14451
- permitType: res.permitType
14452
- });
14453
- }
13691
+ const allowanceType = eip2612PermitData.supportsPermit ? AllowanceTypes.eip2612 : AllowanceTypes.permit2;
13692
+ return {
13693
+ token: address,
13694
+ spender: eip2612PermitData.supportsPermit ? spender : getPermit2Address(chainId),
13695
+ allowanceType
13696
+ };
13697
+ } else if (mode === ApprovalModes.Default) {
13698
+ return {
13699
+ token: address,
13700
+ spender,
13701
+ allowanceType: AllowanceTypes.dzap
13702
+ };
13703
+ } else {
13704
+ const permit2Address = getPermit2Address(chainId);
13705
+ return { token: address, spender: permit2Address, allowanceType: AllowanceTypes.permit2 };
14454
13706
  }
14455
- return { status: "success" /* success */, tokens, code: 200 /* Success */, permitType };
13707
+ })
13708
+ );
13709
+ for (const { address } of nativeTokens2) {
13710
+ data[address] = { allowance: viem.maxUint256, type: AllowanceTypes.dzap };
13711
+ }
13712
+ if (erc20Tokens.length === 0) {
13713
+ return { status: "success" /* success */, code: 200 /* Success */, data };
13714
+ }
13715
+ try {
13716
+ const { data: allowances } = await batchGetAllowances({
13717
+ chainId,
13718
+ data: approvalData,
13719
+ owner: sender,
13720
+ multicallAddress,
13721
+ rpcUrls
13722
+ });
13723
+ for (let i = 0; i < approvalData.length; i++) {
13724
+ const { token, allowanceType } = approvalData[i];
13725
+ const allowance = allowanceType === AllowanceTypes.eip2612 ? viem.maxUint256 : allowances[token];
13726
+ data[token] = { allowance, type: allowanceType };
14456
13727
  }
13728
+ return { status: "success" /* success */, code: 200 /* Success */, data };
13729
+ } catch (error) {
13730
+ console.error("Multicall allowance check failed:", error);
13731
+ return { status: "error" /* error */, code: 500 /* Error */, data };
14457
13732
  }
14458
13733
  };
14459
- _PermitTxnHandler.generateBatchPermitDataForTokens = async (params) => {
14460
- const resp = await getPermit2Signature(params);
14461
- return {
14462
- ...resp,
14463
- permitType: PermitTypes.PermitBatchWitnessTransferFrom
14464
- };
13734
+ async function sendBatchCalls(walletClient, calls) {
13735
+ try {
13736
+ const result = await utils.getAction(
13737
+ walletClient,
13738
+ actions.sendCalls,
13739
+ "sendCalls"
13740
+ )({
13741
+ account: walletClient.account,
13742
+ calls: calls.map((call) => ({
13743
+ to: call.to,
13744
+ data: call.data,
13745
+ value: call.value ?? BigInt(0)
13746
+ }))
13747
+ });
13748
+ return result;
13749
+ } catch (error) {
13750
+ console.warn("EIP-5792 batch calls not supported:", error);
13751
+ return null;
13752
+ }
13753
+ }
13754
+
13755
+ // src/utils/eip-5792/batchApproveTokens.ts
13756
+ async function generateApprovalBatchCalls({
13757
+ tokens,
13758
+ chainId,
13759
+ sender,
13760
+ spender,
13761
+ multicallAddress,
13762
+ rpcUrls
13763
+ }) {
13764
+ const tokensToCheck = tokens.filter((token) => !isDZapNativeToken(token.address));
13765
+ if (tokensToCheck.length === 0) {
13766
+ return [];
13767
+ }
13768
+ const { data: allowanceData } = await getAllowance({
13769
+ chainId,
13770
+ sender,
13771
+ tokens: tokensToCheck,
13772
+ spender,
13773
+ multicallAddress,
13774
+ rpcUrls
13775
+ });
13776
+ const tokensNeedingApproval = tokensToCheck.filter((token) => {
13777
+ const { allowance, type } = allowanceData[token.address] ?? {};
13778
+ if (type === AllowanceTypes.eip2612) return false;
13779
+ return allowance === void 0 || allowance < BigInt(token.amount);
13780
+ });
13781
+ return tokensNeedingApproval.map((token) => ({
13782
+ to: token.address,
13783
+ data: encodeApproveCallData({
13784
+ spender,
13785
+ amount: BigInt(token.amount)
13786
+ }),
13787
+ value: BigInt(0)
13788
+ }));
13789
+ }
13790
+ var waitForBatchTransactionReceipt = async (client, batchHash) => {
13791
+ const { receipts, status, statusCode } = await utils.getAction(
13792
+ client,
13793
+ actions.waitForCallsStatus,
13794
+ "waitForCallsStatus"
13795
+ )({
13796
+ id: batchHash,
13797
+ timeout: 36e5 * 24
13798
+ });
13799
+ if (status === "success" /* success */) {
13800
+ if (!(receipts == null ? void 0 : receipts.length) || !receipts.every((receipt) => receipt.transactionHash) || receipts.some((receipt) => receipt.status === "reverted" /* reverted */)) {
13801
+ throw new Error("Transaction was reverted.");
13802
+ }
13803
+ const transactionReceipt = receipts[receipts.length - 1];
13804
+ return transactionReceipt;
13805
+ }
13806
+ if (statusCode >= 400 && statusCode < 500) {
13807
+ throw new Error("Transaction was canceled.");
13808
+ }
13809
+ throw new Error("Transaction failed.");
14465
13810
  };
14466
- _PermitTxnHandler.generatePermitDataForToken = async (params) => {
14467
- const { token, oneToMany, totalSrcAmount, chainId, rpcUrls, permitType, account } = params;
14468
- const isFirstToken = token.index === 0;
14469
- if (isDZapNativeToken(token.address)) {
13811
+
13812
+ // src/utils/signIntent/custom.ts
13813
+ var signCustomTypedData = async (params) => {
13814
+ try {
13815
+ const { account, signer, message, domain, primaryType, types } = params;
13816
+ const signature = await signTypedData({
13817
+ signer,
13818
+ account,
13819
+ domain,
13820
+ message,
13821
+ primaryType,
13822
+ types
13823
+ });
14470
13824
  return {
14471
13825
  status: "success" /* success */,
14472
13826
  code: 200 /* Success */,
14473
- permitData: DEFAULT_PERMIT_DATA,
14474
- nonce: BigInt(0),
14475
- // For native tokens, nonce is not used
14476
- permitType: PermitTypes.EIP2612Permit
13827
+ data: {
13828
+ signature,
13829
+ message
13830
+ }
14477
13831
  };
13832
+ } catch (error) {
13833
+ return handleViemTransactionError({ error });
14478
13834
  }
14479
- const amount = oneToMany && isFirstToken ? totalSrcAmount : BigInt(token.amount);
14480
- const eip2612PermitData = await checkEIP2612PermitSupport({
14481
- address: token.address,
14482
- chainId,
14483
- rpcUrls,
14484
- owner: account,
14485
- permit: token.permit
14486
- });
14487
- if (permitType === PermitTypes.EIP2612Permit || permitType === PermitTypes.AutoPermit && eip2612PermitData.supportsPermit) {
14488
- if (!eip2612PermitData.supportsPermit || !eip2612PermitData.data) {
14489
- throw new Error("Token does not support EIP-2612 permits");
14490
- }
14491
- if (oneToMany && !isFirstToken) {
14492
- return {
14493
- status: "success" /* success */,
14494
- code: 200 /* Success */,
14495
- permitData: DEFAULT_PERMIT_DATA,
14496
- nonce: BigInt(0),
14497
- // For EIP2612 permits, nonce is not used it's already set in permitData
14498
- permitType: PermitTypes.EIP2612Permit
14499
- };
14500
- }
14501
- const { permitData, status, code } = await getEIP2612PermitSignature({
14502
- ...params,
14503
- token: {
14504
- address: token.address,
14505
- amount: amount.toString(),
14506
- index: 0,
14507
- permit: token.permit
14508
- },
14509
- gasless: false,
14510
- version: eip2612PermitData.data.version,
14511
- name: eip2612PermitData.data.name,
14512
- nonce: eip2612PermitData.data.nonce
14513
- });
13835
+ };
13836
+
13837
+ // src/transactionHandlers/hyperliquid.ts
13838
+ var HyperLiquidTxHandler = class {
13839
+ };
13840
+ HyperLiquidTxHandler.sendTransaction = async (signer, account, txnData, chainId, additionalInfo, updatedQuotes) => {
13841
+ var _a;
13842
+ const signTypedData2 = "signTypedData" in txnData.transaction ? txnData.transaction.signTypedData : null;
13843
+ if (!signTypedData2) {
14514
13844
  return {
14515
- status,
14516
- code,
14517
- permitData,
14518
- nonce: BigInt(0),
14519
- // For EIP2612 permits, nonce is not used
14520
- permitType: PermitTypes.EIP2612Permit
13845
+ status: "error" /* error */,
13846
+ errorMsg: "Missing typed data for HyperLiquid transaction",
13847
+ code: 500 /* Error */
14521
13848
  };
14522
- } else {
14523
- const normalizedPermitType = permitType === PermitTypes.AutoPermit ? PermitTypes.PermitWitnessTransferFrom : permitType;
14524
- if (oneToMany && !isFirstToken) {
14525
- return {
14526
- status: "success" /* success */,
14527
- code: 200 /* Success */,
14528
- permitData: DEFAULT_PERMIT2_DATA,
14529
- nonce: BigInt(0),
14530
- // For one-to-many non-first tokens, nonce is not used
14531
- permitType: normalizedPermitType
14532
- };
14533
- } else {
14534
- const resp = await getPermit2Signature({
14535
- ...params,
14536
- tokens: [token],
14537
- permitType: normalizedPermitType
14538
- });
14539
- return {
14540
- ...resp,
14541
- permitType: normalizedPermitType
14542
- };
14543
- }
14544
13849
  }
14545
- };
14546
- _PermitTxnHandler.signGaslessUserIntent = async (signPermitReq) => {
14547
- const { tokens, sender, permitType } = signPermitReq;
14548
- const type = permitType === PermitTypes.AutoPermit ? PermitTypes.PermitBatchWitnessTransferFrom : permitType;
14549
- if (type === PermitTypes.EIP2612Permit) {
14550
- const resp2 = await signGaslessDzapUserIntent({
14551
- ...signPermitReq,
14552
- account: sender
13850
+ const txData = [];
13851
+ for (let i = 0; i < signTypedData2.length; i++) {
13852
+ const typedData = signTypedData2[i];
13853
+ const [resp, signatureChainId] = await Promise.all([
13854
+ signCustomTypedData({
13855
+ signer,
13856
+ account,
13857
+ domain: typedData.domain,
13858
+ types: typedData.types,
13859
+ message: typedData.message,
13860
+ primaryType: typedData.primaryType
13861
+ }),
13862
+ signer.getChainId()
13863
+ ]);
13864
+ if (resp.status !== "success" /* success */ || !((_a = resp.data) == null ? void 0 : _a.signature)) {
13865
+ throw new Error("Failed to sign transaction");
13866
+ }
13867
+ txData.push({
13868
+ primaryType: typedData.primaryType,
13869
+ message: typedData.message,
13870
+ signature: resp.data.signature,
13871
+ account,
13872
+ signatureChainId
14553
13873
  });
14554
- return {
14555
- status: resp2.status,
14556
- code: resp2.code,
14557
- data: (resp2 == null ? void 0 : resp2.data) && {
14558
- ...resp2.data,
14559
- type
14560
- }
14561
- };
14562
13874
  }
14563
- const resp = await getPermit2Signature({
14564
- ...signPermitReq,
14565
- tokens: tokens.map((token, index) => ({ ...token, index })),
14566
- account: sender,
14567
- permitType: type
13875
+ const txResp = await broadcastTradeTx({
13876
+ chainId,
13877
+ txData,
13878
+ txId: txnData.txId
14568
13879
  });
13880
+ if (txResp.status !== "success" /* success */) {
13881
+ throw new Error("Failed to broadcast or save transaction");
13882
+ }
14569
13883
  return {
14570
- status: resp.status,
14571
- code: resp.code,
14572
- data: resp.permitData && {
14573
- type,
14574
- batchPermitData: resp.permitData
14575
- }
13884
+ status: "success" /* success */,
13885
+ code: 200 /* Success */,
13886
+ txnHash: txResp.txnHash,
13887
+ additionalInfo,
13888
+ updatedQuotes
14576
13889
  };
14577
13890
  };
14578
- _PermitTxnHandler.v1PermitSupport = ({ contractVersion, service }) => {
14579
- return contractVersion === "v1" /* v1 */ && service !== Services.zap;
13891
+
13892
+ // src/transactionHandlers/trade.ts
13893
+ var _TradeTxnHandler = class _TradeTxnHandler {
14580
13894
  };
14581
- _PermitTxnHandler.shouldUseBatchPermit = ({
14582
- permitType,
14583
- isBatchPermitAllowed = true,
14584
- tokens,
14585
- oneToMany,
14586
- contractVersion,
14587
- service
14588
- }) => {
14589
- const isBatchPermitRequested = permitType === PermitTypes.PermitBatchWitnessTransferFrom;
14590
- const shouldAutoBatch = permitType === PermitTypes.AutoPermit && (tokens == null ? void 0 : tokens.length) > 1 && !oneToMany;
14591
- const isContractSupport = !_PermitTxnHandler.v1PermitSupport({ contractVersion, service });
14592
- return isBatchPermitAllowed && (isBatchPermitRequested || shouldAutoBatch) && isContractSupport;
13895
+ _TradeTxnHandler.sendTransaction = async (signer, txnParams, chainId, additionalInfo, updatedQuotes) => {
13896
+ let txnHash;
13897
+ if (isTypeSigner(signer)) {
13898
+ const txnRes = await signer.sendTransaction({
13899
+ from: txnParams.from,
13900
+ to: txnParams.to,
13901
+ data: txnParams.data,
13902
+ value: txnParams.value,
13903
+ gasLimit: txnParams.gasLimit
13904
+ });
13905
+ txnHash = txnRes.hash;
13906
+ } else {
13907
+ txnHash = await signer.sendTransaction({
13908
+ chain: viemChainsById[chainId],
13909
+ account: txnParams.from,
13910
+ to: txnParams.to,
13911
+ data: txnParams.data,
13912
+ value: BigInt(txnParams.value)
13913
+ });
13914
+ }
13915
+ return {
13916
+ status: "success" /* success */,
13917
+ code: 200 /* Success */,
13918
+ txnHash,
13919
+ additionalInfo,
13920
+ updatedQuotes
13921
+ };
14593
13922
  };
14594
- var PermitTxnHandler = _PermitTxnHandler;
14595
- var permit_default = PermitTxnHandler;
14596
- function encodeApproveCallData({ spender, amount }) {
14597
- return viem.encodeFunctionData({
14598
- abi: abi5,
14599
- functionName: erc20Functions.approve,
14600
- args: [spender, amount]
13923
+ _TradeTxnHandler.sendTxnWithBatch = async (request, signer, txnParams, chainId, additionalInfo, updatedQuotes, multicallAddress, rpcUrls) => {
13924
+ const approvalBatchCalls = await generateApprovalBatchCalls({
13925
+ tokens: request.data.map((token) => ({
13926
+ address: token.srcToken,
13927
+ amount: token.amount
13928
+ })),
13929
+ chainId,
13930
+ multicallAddress,
13931
+ sender: txnParams.from,
13932
+ spender: txnParams.to,
13933
+ rpcUrls
14601
13934
  });
14602
- }
14603
- var approveToken = async ({
14604
- chainId,
13935
+ const batchCalls = [
13936
+ ...approvalBatchCalls,
13937
+ {
13938
+ to: txnParams.to,
13939
+ data: txnParams.data,
13940
+ value: BigInt(txnParams.value)
13941
+ }
13942
+ ];
13943
+ if (approvalBatchCalls.length === 0) {
13944
+ return _TradeTxnHandler.sendTransaction(signer, txnParams, chainId, additionalInfo, updatedQuotes);
13945
+ }
13946
+ const batchResult = await sendBatchCalls(signer, batchCalls);
13947
+ if (!batchResult) {
13948
+ return {
13949
+ status: "error" /* error */,
13950
+ errorMsg: "Batch call failed",
13951
+ code: 500 /* Error */
13952
+ };
13953
+ }
13954
+ console.log("Waiting for batch transaction completion...");
13955
+ const receipt = await waitForBatchTransactionReceipt(signer, batchResult.id);
13956
+ console.log({ receipt });
13957
+ return {
13958
+ status: "success" /* success */,
13959
+ code: 200 /* Success */,
13960
+ txnHash: receipt.transactionHash,
13961
+ additionalInfo,
13962
+ updatedQuotes
13963
+ };
13964
+ };
13965
+ _TradeTxnHandler.buildAndSendTransaction = async ({
13966
+ request,
14605
13967
  signer,
14606
- rpcUrls,
14607
- mode,
14608
- tokens,
14609
- approvalTxnCallback,
14610
- spender
13968
+ txnData,
13969
+ multicallAddress,
13970
+ batchTransaction = false,
13971
+ rpcUrls
14611
13972
  }) => {
14612
- if (mode !== ApprovalModes.Default) {
14613
- spender = getPermit2Address(chainId);
14614
- }
14615
- for (let dataIdx = 0; dataIdx < tokens.length; dataIdx++) {
14616
- let txnDetails = { status: "success" /* success */, code: 200 /* Success */, txnHash: "" };
14617
- if (isTypeSigner(signer)) {
14618
- const from = await signer.getAddress();
14619
- const callData = viem.encodeFunctionData({
14620
- abi: abi5,
14621
- functionName: erc20Functions.approve,
14622
- args: [spender, BigInt(tokens[dataIdx].amount)]
14623
- });
14624
- await signer.sendTransaction({
14625
- from,
14626
- chainId,
14627
- to: tokens[dataIdx].address,
14628
- data: callData
14629
- });
14630
- return {
14631
- status: "success" /* success */,
14632
- code: 200 /* Success */
14633
- };
13973
+ var _a, _b, _c, _d, _e, _f, _g, _h;
13974
+ try {
13975
+ const chainId = request.fromChain;
13976
+ let buildTxnResponseData;
13977
+ if (txnData) {
13978
+ buildTxnResponseData = txnData;
14634
13979
  } else {
14635
- txnDetails = await writeContract({
13980
+ buildTxnResponseData = await fetchTradeBuildTxnData(request);
13981
+ }
13982
+ const { data, from, to, value, gasLimit, additionalInfo, updatedQuotes } = buildTxnResponseData;
13983
+ const txnParams = { from, to, data, value, gasLimit };
13984
+ if (chainId === exclusiveChainIds.hyperLiquid) {
13985
+ return HyperLiquidTxHandler.sendTransaction(
13986
+ signer,
13987
+ txnParams.from,
13988
+ buildTxnResponseData,
14636
13989
  chainId,
14637
- contractAddress: tokens[dataIdx].address,
14638
- abi: abi5,
14639
- functionName: erc20Functions.approve,
14640
- args: [spender, tokens[dataIdx].amount],
14641
- rpcUrls,
14642
- signer
14643
- });
13990
+ additionalInfo,
13991
+ updatedQuotes
13992
+ );
14644
13993
  }
14645
- if (txnDetails.code !== 200 /* Success */) {
14646
- return {
14647
- status: txnDetails.status,
14648
- code: (txnDetails == null ? void 0 : txnDetails.code) || 32771 /* FunctionNotFound */
14649
- };
13994
+ if (batchTransaction && !isTypeSigner(signer)) {
13995
+ return _TradeTxnHandler.sendTxnWithBatch(request, signer, txnParams, chainId, additionalInfo, updatedQuotes, multicallAddress, rpcUrls);
14650
13996
  }
14651
- if (approvalTxnCallback) {
14652
- const callbackStatus = await approvalTxnCallback({ txnDetails, address: tokens[dataIdx].address });
14653
- if (callbackStatus && callbackStatus !== "success" /* success */) {
13997
+ console.log("Using viem walletClient - sending regular transaction.");
13998
+ return _TradeTxnHandler.sendTransaction(signer, txnParams, chainId, additionalInfo, updatedQuotes);
13999
+ } catch (error) {
14000
+ console.log({ error });
14001
+ if (isAxiosError(error)) {
14002
+ if (((_a = error == null ? void 0 : error.response) == null ? void 0 : _a.status) === 417 /* SimulationFailure */) {
14654
14003
  return {
14655
- status: txnDetails.status,
14656
- code: (txnDetails == null ? void 0 : txnDetails.code) || 500 /* Error */
14004
+ status: "error" /* error */,
14005
+ errorMsg: "Simulation Failed",
14006
+ error: ((_b = error.response) == null ? void 0 : _b.data).message,
14007
+ code: ((_c = error.response) == null ? void 0 : _c.data).code,
14008
+ action: ((_d = error.response) == null ? void 0 : _d.data).action
14657
14009
  };
14658
14010
  }
14011
+ return {
14012
+ status: "error" /* error */,
14013
+ errorMsg: "Params Failed: " + JSON.stringify((_f = (_e = error == null ? void 0 : error.response) == null ? void 0 : _e.data) == null ? void 0 : _f.message),
14014
+ error: ((_g = error == null ? void 0 : error.response) == null ? void 0 : _g.data) ?? error,
14015
+ code: ((_h = error == null ? void 0 : error.response) == null ? void 0 : _h.status) ?? 500 /* Error */
14016
+ };
14659
14017
  }
14018
+ return handleViemTransactionError({ error });
14660
14019
  }
14661
- return { status: "success" /* success */, code: 200 /* Success */ };
14662
14020
  };
14663
- var batchGetAllowances = async ({
14664
- chainId,
14665
- data,
14666
- owner,
14667
- multicallAddress,
14668
- rpcUrls
14021
+ _TradeTxnHandler.buildGaslessTxAndSignPermit = async ({
14022
+ request,
14023
+ signer,
14024
+ rpcUrls,
14025
+ spender,
14026
+ txnData,
14027
+ txnStatusCallback
14669
14028
  }) => {
14670
- const contracts = data.map(({ token, spender }) => ({
14671
- address: token,
14672
- abi: abi5,
14673
- functionName: erc20Functions.allowance,
14674
- args: [owner, spender]
14675
- }));
14676
- const {
14677
- status,
14678
- code,
14679
- data: allowances
14680
- } = await multicall({
14681
- chainId,
14682
- contracts,
14683
- rpcUrls,
14684
- multicallAddress,
14685
- allowFailure: false
14686
- });
14687
- if (status !== "success" /* success */) {
14688
- return { status, code, data: {} };
14689
- }
14690
- const tokenAllowances = {};
14691
- for (let i = 0; i < data.length; i++) {
14692
- tokenAllowances[data[i].token] = allowances[i];
14693
- }
14694
- return { status, code, data: tokenAllowances };
14695
- };
14696
- var getAllowance = async ({ chainId, sender, tokens, rpcUrls, multicallAddress, mode, spender }) => {
14697
- const data = {};
14698
- const nativeTokens2 = tokens.filter(({ address }) => isDZapNativeToken(address));
14699
- const erc20Tokens = tokens.filter(({ address }) => !isDZapNativeToken(address));
14700
- const approvalData = await Promise.all(
14701
- erc20Tokens.map(async ({ address, permit }) => {
14702
- if (mode === ApprovalModes.AutoPermit) {
14703
- const eip2612PermitData = await checkEIP2612PermitSupport({
14704
- address,
14705
- chainId,
14706
- rpcUrls,
14707
- owner: sender,
14708
- permit
14709
- });
14710
- const allowanceType = eip2612PermitData.supportsPermit ? AllowanceTypes.eip2612 : AllowanceTypes.permit2;
14711
- return {
14712
- token: address,
14713
- spender: eip2612PermitData.supportsPermit ? spender : getPermit2Address(chainId),
14714
- allowanceType
14715
- };
14716
- } else if (mode === ApprovalModes.Default) {
14029
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
14030
+ try {
14031
+ const chainId = request.fromChain;
14032
+ let buildTxnResponseData;
14033
+ if (txnData) {
14034
+ buildTxnResponseData = txnData;
14035
+ } else {
14036
+ buildTxnResponseData = await fetchTradeBuildTxnData({
14037
+ ...request,
14038
+ gasless: true
14039
+ });
14040
+ }
14041
+ const permitType = request.hasPermit2ApprovalForAllTokens ? PermitTypes.PermitBatchWitnessTransferFrom : PermitTypes.EIP2612Permit;
14042
+ const txId = buildTxnResponseData.txId;
14043
+ const resp = await permit_default.signGaslessUserIntent({
14044
+ tokens: request.data.map((req, index) => {
14717
14045
  return {
14718
- token: address,
14719
- spender,
14720
- allowanceType: AllowanceTypes.dzap
14046
+ address: req.srcToken,
14047
+ amount: req.amount,
14048
+ index
14721
14049
  };
14722
- } else {
14723
- const permit2Address = getPermit2Address(chainId);
14724
- return { token: address, spender: permit2Address, allowanceType: AllowanceTypes.permit2 };
14725
- }
14726
- })
14727
- );
14728
- for (const { address } of nativeTokens2) {
14729
- data[address] = { allowance: viem.maxUint256, type: AllowanceTypes.dzap };
14730
- }
14731
- if (erc20Tokens.length === 0) {
14732
- return { status: "success" /* success */, code: 200 /* Success */, data };
14733
- }
14734
- try {
14735
- const { data: allowances } = await batchGetAllowances({
14050
+ }),
14736
14051
  chainId,
14737
- data: approvalData,
14738
- owner: sender,
14739
- multicallAddress,
14740
- rpcUrls
14052
+ rpcUrls,
14053
+ sender: request.sender,
14054
+ spender,
14055
+ permitType,
14056
+ signer,
14057
+ gasless: true,
14058
+ txId,
14059
+ service: "trade",
14060
+ contractVersion: "v2" /* v2 */,
14061
+ ...buildTxnResponseData.transaction
14741
14062
  });
14742
- for (let i = 0; i < approvalData.length; i++) {
14743
- const { token, allowanceType } = approvalData[i];
14744
- const allowance = allowanceType === AllowanceTypes.eip2612 ? viem.maxUint256 : allowances[token];
14745
- data[token] = { allowance, type: allowanceType };
14063
+ if (resp.status === "success" /* success */ && resp.data) {
14064
+ if (txnStatusCallback) {
14065
+ txnStatusCallback("waitingForExecution" /* waitingForExecution */);
14066
+ }
14067
+ const permit = resp.data.type === PermitTypes.EIP2612Permit ? {
14068
+ permitData: request.data.map((req) => {
14069
+ return {
14070
+ token: req.srcToken,
14071
+ amount: req.amount,
14072
+ permit: req.permitData
14073
+ };
14074
+ }),
14075
+ gaslessIntentNonce: (_a = resp.data.nonce) == null ? void 0 : _a.toString(),
14076
+ gaslessIntentSignature: resp.data.signature,
14077
+ gaslessIntentDeadline: (_b = resp.data.deadline) == null ? void 0 : _b.toString()
14078
+ } : {
14079
+ batchPermitData: resp.data.batchPermitData
14080
+ };
14081
+ const gaslessTxResp = await executeGaslessTxnData({
14082
+ chainId: request.fromChain,
14083
+ txId,
14084
+ permit
14085
+ });
14086
+ if (gaslessTxResp.status !== "success" /* success */) {
14087
+ throw new Error("Failed to execute gasless transaction");
14088
+ }
14089
+ return {
14090
+ status: "success" /* success */,
14091
+ code: 200 /* Success */,
14092
+ txnHash: gaslessTxResp.txnHash
14093
+ };
14094
+ }
14095
+ throw new Error("Gasless Transaction Failed");
14096
+ } catch (error) {
14097
+ console.log({ error });
14098
+ if (isAxiosError(error)) {
14099
+ if (((_c = error == null ? void 0 : error.response) == null ? void 0 : _c.status) === 417 /* SimulationFailure */) {
14100
+ return {
14101
+ status: "error" /* error */,
14102
+ errorMsg: "Simulation Failed",
14103
+ error: ((_d = error.response) == null ? void 0 : _d.data).message,
14104
+ code: ((_e = error.response) == null ? void 0 : _e.data).code,
14105
+ action: ((_f = error.response) == null ? void 0 : _f.data).action
14106
+ };
14107
+ }
14108
+ return {
14109
+ status: "error" /* error */,
14110
+ errorMsg: "Params Failed: " + JSON.stringify((_h = (_g = error == null ? void 0 : error.response) == null ? void 0 : _g.data) == null ? void 0 : _h.message),
14111
+ error: ((_i = error == null ? void 0 : error.response) == null ? void 0 : _i.data) ?? error,
14112
+ code: ((_j = error == null ? void 0 : error.response) == null ? void 0 : _j.status) ?? 500 /* Error */
14113
+ };
14746
14114
  }
14747
- return { status: "success" /* success */, code: 200 /* Success */, data };
14748
- } catch (error) {
14749
- console.error("Multicall allowance check failed:", error);
14750
- return { status: "error" /* error */, code: 500 /* Error */, data };
14115
+ return handleViemTransactionError({ error });
14751
14116
  }
14752
14117
  };
14753
- async function sendBatchCalls(walletClient, calls) {
14754
- try {
14755
- const result = await utils.getAction(
14756
- walletClient,
14757
- actions.sendCalls,
14758
- "sendCalls"
14759
- )({
14760
- account: walletClient.account,
14761
- calls: calls.map((call) => ({
14762
- to: call.to,
14763
- data: call.data,
14764
- value: call.value ?? BigInt(0)
14765
- }))
14766
- });
14767
- return result;
14768
- } catch (error) {
14769
- console.warn("EIP-5792 batch calls not supported:", error);
14770
- return null;
14771
- }
14772
- }
14118
+ var TradeTxnHandler = _TradeTxnHandler;
14119
+ var trade_default = TradeTxnHandler;
14773
14120
 
14774
- // src/utils/eip-5792/batchApproveTokens.ts
14775
- async function generateApprovalBatchCalls({
14776
- tokens,
14777
- chainId,
14778
- sender,
14779
- spender,
14780
- multicallAddress,
14781
- rpcUrls
14782
- }) {
14783
- const tokensToCheck = tokens.filter((token) => !isDZapNativeToken(token.address));
14784
- if (tokensToCheck.length === 0) {
14785
- return [];
14786
- }
14787
- const { data: allowanceData } = await getAllowance({
14788
- chainId,
14789
- sender,
14790
- tokens: tokensToCheck,
14791
- spender,
14792
- multicallAddress,
14793
- rpcUrls
14794
- });
14795
- const tokensNeedingApproval = tokensToCheck.filter((token) => {
14796
- const { allowance, type } = allowanceData[token.address] ?? {};
14797
- if (type === AllowanceTypes.eip2612) return false;
14798
- return allowance === void 0 || allowance < BigInt(token.amount);
14799
- });
14800
- return tokensNeedingApproval.map((token) => ({
14801
- to: token.address,
14802
- data: encodeApproveCallData({
14803
- spender,
14804
- amount: BigInt(token.amount)
14805
- }),
14806
- value: BigInt(0)
14807
- }));
14808
- }
14809
- var waitForBatchTransactionReceipt = async (client, batchHash) => {
14810
- const { receipts, status, statusCode } = await utils.getAction(
14811
- client,
14812
- actions.waitForCallsStatus,
14813
- "waitForCallsStatus"
14814
- )({
14815
- id: batchHash,
14816
- timeout: 36e5 * 24
14817
- });
14818
- if (status === "success" /* success */) {
14819
- if (!(receipts == null ? void 0 : receipts.length) || !receipts.every((receipt) => receipt.transactionHash) || receipts.some((receipt) => receipt.status === "reverted" /* reverted */)) {
14820
- throw new Error("Transaction was reverted.");
14821
- }
14822
- const transactionReceipt = receipts[receipts.length - 1];
14823
- return transactionReceipt;
14824
- }
14825
- if (statusCode >= 400 && statusCode < 500) {
14826
- throw new Error("Transaction was canceled.");
14827
- }
14828
- throw new Error("Transaction failed.");
14121
+ // src/zap/constants/step.ts
14122
+ var zapStepAction = {
14123
+ execute: "execute"
14829
14124
  };
14830
14125
 
14831
- // src/utils/signIntent/custom.ts
14832
- var signCustomTypedData = async (params) => {
14126
+ // src/transactionHandlers/zap.ts
14127
+ var _ZapTxnHandler = class _ZapTxnHandler {
14128
+ };
14129
+ _ZapTxnHandler.execute = async ({
14130
+ chainId,
14131
+ txnData,
14132
+ signer
14133
+ }) => {
14134
+ var _a;
14833
14135
  try {
14834
- const { account, signer, message, domain, primaryType, types } = params;
14835
- const signature = await signTypedData({
14836
- signer,
14837
- account,
14838
- domain,
14839
- message,
14840
- primaryType,
14841
- types
14842
- });
14843
- return {
14844
- status: "success" /* success */,
14845
- code: 200 /* Success */,
14846
- data: {
14847
- signature,
14848
- message
14849
- }
14850
- };
14136
+ const { callData, callTo, value, estimatedGas } = txnData;
14137
+ if (isTypeSigner(signer)) {
14138
+ console.log("Using ethers signer.");
14139
+ const from = await signer.getAddress();
14140
+ const txnRes = await signer.sendTransaction({
14141
+ from,
14142
+ to: callTo,
14143
+ data: callData,
14144
+ value: BigInt(value),
14145
+ gasLimit: BigInt(estimatedGas) ? BigInt(estimatedGas) : void 0
14146
+ });
14147
+ return {
14148
+ status: "success" /* success */,
14149
+ code: 200 /* Success */,
14150
+ txnHash: txnRes.hash
14151
+ };
14152
+ } else {
14153
+ console.log("Using viem walletClient.");
14154
+ const txnHash = await signer.sendTransaction({
14155
+ chain: viemChainsById[chainId],
14156
+ account: (_a = signer.account) == null ? void 0 : _a.address,
14157
+ to: txnData.callTo,
14158
+ data: txnData.callData,
14159
+ value: BigInt(txnData.value)
14160
+ });
14161
+ return {
14162
+ status: "success" /* success */,
14163
+ code: 200 /* Success */,
14164
+ txnHash
14165
+ };
14166
+ }
14851
14167
  } catch (error) {
14168
+ console.log({ error });
14852
14169
  return handleViemTransactionError({ error });
14853
14170
  }
14854
14171
  };
14855
-
14856
- // src/transactionHandlers/hyperliquid.ts
14857
- var HyperLiquidTxHandler = class {
14858
- };
14859
- HyperLiquidTxHandler.sendTransaction = async (signer, account, txnData, chainId, additionalInfo, updatedQuotes) => {
14172
+ _ZapTxnHandler.approve = async ({ chainId, data, signer }) => {
14860
14173
  var _a;
14861
- const signTypedData2 = "signTypedData" in txnData.transaction ? txnData.transaction.signTypedData : null;
14862
- if (!signTypedData2) {
14863
- return {
14864
- status: "error" /* error */,
14865
- errorMsg: "Missing typed data for HyperLiquid transaction",
14866
- code: 500 /* Error */
14867
- };
14174
+ try {
14175
+ const { callData, callTo, value, estimatedGas } = data;
14176
+ const publicClient = getPublicClient({ chainId, rpcUrls: void 0 });
14177
+ const blockNumber = await publicClient.getBlockNumber();
14178
+ console.log("block Number and data");
14179
+ console.dir(
14180
+ {
14181
+ blockNumber,
14182
+ ...data
14183
+ },
14184
+ { depth: null }
14185
+ );
14186
+ if (isTypeSigner(signer)) {
14187
+ console.log("Using ethers signer.");
14188
+ const from = await signer.getAddress();
14189
+ const txnRes = await signer.sendTransaction({
14190
+ from,
14191
+ to: callTo,
14192
+ data: callData,
14193
+ value: BigInt(value),
14194
+ gasLimit: BigInt(estimatedGas) ? BigInt(estimatedGas) : void 0
14195
+ });
14196
+ return {
14197
+ status: "success" /* success */,
14198
+ code: 200 /* Success */,
14199
+ txnHash: txnRes.hash
14200
+ };
14201
+ } else {
14202
+ console.log("Using viem walletClient.");
14203
+ const txnHash = await signer.sendTransaction({
14204
+ chain: viemChainsById[chainId],
14205
+ account: (_a = signer.account) == null ? void 0 : _a.address,
14206
+ to: data.callTo,
14207
+ data: data.callData,
14208
+ value: BigInt(data.value)
14209
+ });
14210
+ return {
14211
+ status: "success" /* success */,
14212
+ code: 200 /* Success */,
14213
+ txnHash
14214
+ };
14215
+ }
14216
+ } catch (error) {
14217
+ console.log({ error });
14218
+ return handleViemTransactionError({ error });
14868
14219
  }
14869
- const txData = [];
14870
- for (let i = 0; i < signTypedData2.length; i++) {
14871
- const typedData = signTypedData2[i];
14872
- const [resp, signatureChainId] = await Promise.all([
14873
- signCustomTypedData({
14874
- signer,
14875
- account,
14876
- domain: typedData.domain,
14877
- types: typedData.types,
14878
- message: typedData.message,
14879
- primaryType: typedData.primaryType
14880
- }),
14881
- signer.getChainId()
14882
- ]);
14883
- if (resp.status !== "success" /* success */ || !((_a = resp.data) == null ? void 0 : _a.signature)) {
14884
- throw new Error("Failed to sign transaction");
14220
+ };
14221
+ _ZapTxnHandler.zap = async ({
14222
+ request,
14223
+ steps,
14224
+ signer
14225
+ }) => {
14226
+ try {
14227
+ const chainId = "srcChainId" in request ? request.srcChainId : request.actions[0].srcChainId;
14228
+ if (!steps || steps.length === 0) {
14229
+ const route = "actions" in request ? (await fetchZapBundleBuildTx(request)).data : (await fetchZapBuildTxnData(request)).data;
14230
+ steps = route.steps;
14231
+ if (!steps || steps.length === 0) {
14232
+ return {
14233
+ status: "error" /* error */,
14234
+ code: 32771 /* FunctionNotFound */,
14235
+ errorMsg: "No steps found in the zap route."
14236
+ };
14237
+ }
14238
+ }
14239
+ let txnHash;
14240
+ for (let i = 0; i < steps.length; i++) {
14241
+ const step = steps[i];
14242
+ if (step.action === zapStepAction.execute) {
14243
+ const result = await _ZapTxnHandler.execute({ chainId, txnData: step.data, signer });
14244
+ if (result.status !== "success" /* success */) {
14245
+ return result;
14246
+ }
14247
+ txnHash = result.txnHash;
14248
+ }
14885
14249
  }
14886
- txData.push({
14887
- primaryType: typedData.primaryType,
14888
- message: typedData.message,
14889
- signature: resp.data.signature,
14890
- account,
14891
- signatureChainId
14892
- });
14250
+ if (!txnHash) {
14251
+ return {
14252
+ status: "error" /* error */,
14253
+ code: 500 /* Error */,
14254
+ errorMsg: "No executable steps found."
14255
+ };
14256
+ }
14257
+ return {
14258
+ status: "success" /* success */,
14259
+ code: 200 /* Success */,
14260
+ txnHash
14261
+ };
14262
+ } catch (error) {
14263
+ console.log({ error });
14264
+ return handleViemTransactionError({ error });
14893
14265
  }
14894
- const txResp = await broadcastTradeTx({
14895
- chainId,
14896
- txData,
14897
- txId: txnData.txId
14266
+ };
14267
+ var ZapTxnHandler = _ZapTxnHandler;
14268
+ var zap_default = ZapTxnHandler;
14269
+ var SUI_DEFAULT_RPC = "https://sui-rpc.publicnode.com";
14270
+ var decodeSuivmTransaction = async ({ txHash, rpcUrls }) => {
14271
+ var _a, _b, _c, _d, _e, _f, _g, _h;
14272
+ const rpcUrl = (rpcUrls == null ? void 0 : rpcUrls[0]) ?? SUI_DEFAULT_RPC;
14273
+ const response = await Axios__default.default.post(rpcUrl, {
14274
+ jsonrpc: "2.0",
14275
+ id: 1,
14276
+ method: "sui_getTransactionBlock",
14277
+ params: [txHash, { showBalanceChanges: true, showEffects: true, showInput: true }]
14898
14278
  });
14899
- if (txResp.status !== "success" /* success */) {
14900
- throw new Error("Failed to broadcast or save transaction");
14279
+ if (response.status !== 200 || ((_a = response.data) == null ? void 0 : _a.error)) {
14280
+ return void 0;
14901
14281
  }
14902
- return {
14903
- status: "success" /* success */,
14904
- code: 200 /* Success */,
14905
- txnHash: txResp.txnHash,
14906
- additionalInfo,
14907
- updatedQuotes
14908
- };
14909
- };
14910
-
14911
- // src/transactionHandlers/trade.ts
14912
- var _TradeTxnHandler = class _TradeTxnHandler {
14913
- };
14914
- _TradeTxnHandler.sendTransaction = async (signer, txnParams, chainId, additionalInfo, updatedQuotes) => {
14915
- let txnHash;
14916
- if (isTypeSigner(signer)) {
14917
- const txnRes = await signer.sendTransaction({
14918
- from: txnParams.from,
14919
- to: txnParams.to,
14920
- data: txnParams.data,
14921
- value: txnParams.value,
14922
- gasLimit: txnParams.gasLimit
14923
- });
14924
- txnHash = txnRes.hash;
14925
- } else {
14926
- txnHash = await signer.sendTransaction({
14927
- chain: viemChainsById[chainId],
14928
- account: txnParams.from,
14929
- to: txnParams.to,
14930
- data: txnParams.data,
14931
- value: BigInt(txnParams.value)
14932
- });
14282
+ const result = (_b = response.data) == null ? void 0 : _b.result;
14283
+ const sender = (_d = (_c = result == null ? void 0 : result.transaction) == null ? void 0 : _c.data) == null ? void 0 : _d.sender;
14284
+ const balanceChanges = result == null ? void 0 : result.balanceChanges;
14285
+ if (!sender || !balanceChanges) {
14286
+ return void 0;
14933
14287
  }
14934
- return {
14935
- status: "success" /* success */,
14936
- code: 200 /* Success */,
14937
- txnHash,
14938
- additionalInfo,
14939
- updatedQuotes
14940
- };
14941
- };
14942
- _TradeTxnHandler.sendTxnWithBatch = async (request, signer, txnParams, chainId, additionalInfo, updatedQuotes, multicallAddress, rpcUrls) => {
14943
- const approvalBatchCalls = await generateApprovalBatchCalls({
14944
- tokens: request.data.map((token) => ({
14945
- address: token.srcToken,
14946
- amount: token.amount
14947
- })),
14948
- chainId,
14949
- multicallAddress,
14950
- sender: txnParams.from,
14951
- spender: txnParams.to,
14952
- rpcUrls
14953
- });
14954
- const batchCalls = [
14955
- ...approvalBatchCalls,
14956
- {
14957
- to: txnParams.to,
14958
- data: txnParams.data,
14959
- value: BigInt(txnParams.value)
14288
+ const gasUsed = (_e = result == null ? void 0 : result.effects) == null ? void 0 : _e.gasUsed;
14289
+ const senderPaidGas = (((_h = (_g = (_f = result == null ? void 0 : result.transaction) == null ? void 0 : _f.data) == null ? void 0 : _g.gasData) == null ? void 0 : _h.owner) ?? sender) === sender;
14290
+ const gasCost = gasUsed && senderPaidGas ? BigInt(gasUsed.computationCost ?? 0) + BigInt(gasUsed.storageCost ?? 0) - BigInt(gasUsed.storageRebate ?? 0) : BigInt(0);
14291
+ const sent = [];
14292
+ const received = [];
14293
+ balanceChanges.filter((change) => {
14294
+ var _a2;
14295
+ return ((_a2 = change.owner) == null ? void 0 : _a2.AddressOwner) === sender;
14296
+ }).forEach((change) => {
14297
+ const amount = BigInt(change.amount) + (change.coinType === suiNativeToken ? gasCost : BigInt(0));
14298
+ if (amount < BigInt(0)) {
14299
+ sent.push({ token: change.coinType, amount: -amount });
14300
+ } else if (amount > BigInt(0)) {
14301
+ received.push({ token: change.coinType, amount });
14960
14302
  }
14961
- ];
14962
- if (approvalBatchCalls.length === 0) {
14963
- return _TradeTxnHandler.sendTransaction(signer, txnParams, chainId, additionalInfo, updatedQuotes);
14303
+ });
14304
+ if (sent.length === 0 && received.length === 0) {
14305
+ return void 0;
14964
14306
  }
14965
- const batchResult = await sendBatchCalls(signer, batchCalls);
14966
- if (!batchResult) {
14967
- return {
14968
- status: "error" /* error */,
14969
- errorMsg: "Batch call failed",
14970
- code: 500 /* Error */
14971
- };
14307
+ return { sent, received };
14308
+ };
14309
+ var SVM_TX_LOOKUP_ATTEMPTS = 6;
14310
+ var SVM_TX_LOOKUP_BASE_DELAY_MS = 500;
14311
+ var getConfirmedTransaction = async (connection, txHash, attempt = 1) => {
14312
+ const tx = await connection.getParsedTransaction(txHash, { commitment: "confirmed", maxSupportedTransactionVersion: 0 });
14313
+ if (tx) {
14314
+ return tx;
14972
14315
  }
14973
- console.log("Waiting for batch transaction completion...");
14974
- const receipt = await waitForBatchTransactionReceipt(signer, batchResult.id);
14975
- console.log({ receipt });
14976
- return {
14977
- status: "success" /* success */,
14978
- code: 200 /* Success */,
14979
- txnHash: receipt.transactionHash,
14980
- additionalInfo,
14981
- updatedQuotes
14982
- };
14316
+ if (attempt >= SVM_TX_LOOKUP_ATTEMPTS) {
14317
+ throw new Error(`transaction ${txHash} not found after ${attempt} attempts`);
14318
+ }
14319
+ await new Promise((resolve) => setTimeout(resolve, SVM_TX_LOOKUP_BASE_DELAY_MS * 2 ** (attempt - 1)));
14320
+ return getConfirmedTransaction(connection, txHash, attempt + 1);
14983
14321
  };
14984
- _TradeTxnHandler.buildAndSendTransaction = async ({
14985
- request,
14986
- signer,
14987
- txnData,
14988
- multicallAddress,
14989
- batchTransaction = false,
14990
- rpcUrls
14991
- }) => {
14992
- var _a, _b, _c, _d, _e, _f, _g, _h;
14993
- try {
14994
- const chainId = request.fromChain;
14995
- let buildTxnResponseData;
14996
- if (txnData) {
14997
- buildTxnResponseData = txnData;
14998
- } else {
14999
- buildTxnResponseData = await fetchTradeBuildTxnData(request);
14322
+ var decodeSvmTransaction = async ({ txHash, rpcUrls }) => {
14323
+ var _a, _b, _c, _d, _e;
14324
+ const connection = new web3_js.Connection((rpcUrls == null ? void 0 : rpcUrls[0]) || web3_js.clusterApiUrl("mainnet-beta"));
14325
+ const tx = await getConfirmedTransaction(connection, txHash);
14326
+ const meta = tx == null ? void 0 : tx.meta;
14327
+ const owner = (_e = (_d = (_c = (_b = (_a = tx == null ? void 0 : tx.transaction) == null ? void 0 : _a.message) == null ? void 0 : _b.accountKeys) == null ? void 0 : _c[0]) == null ? void 0 : _d.pubkey) == null ? void 0 : _e.toBase58();
14328
+ if (!meta || !owner) {
14329
+ return void 0;
14330
+ }
14331
+ const preTokenBalances = meta.preTokenBalances ?? [];
14332
+ const postTokenBalances = meta.postTokenBalances ?? [];
14333
+ const preBalances = meta.preBalances ?? [];
14334
+ const postBalances = meta.postBalances ?? [];
14335
+ const deltas = /* @__PURE__ */ new Map();
14336
+ const addDelta = (token, delta) => deltas.set(token, (deltas.get(token) ?? BigInt(0)) + delta);
14337
+ let rentAdjustment = BigInt(0);
14338
+ const rentOf = (accountIndex, wrappedDelta) => BigInt(postBalances[accountIndex] ?? 0) - BigInt(preBalances[accountIndex] ?? 0) - wrappedDelta;
14339
+ const wrappedPart = (mint, delta) => mint === solanaWNativeToken ? delta : BigInt(0);
14340
+ postTokenBalances.filter((balance) => balance.owner === owner).forEach((post) => {
14341
+ const pre = preTokenBalances.find((item) => item.accountIndex === post.accountIndex);
14342
+ const delta = BigInt(post.uiTokenAmount.amount) - BigInt((pre == null ? void 0 : pre.uiTokenAmount.amount) ?? "0");
14343
+ addDelta(post.mint, delta);
14344
+ if (!pre) {
14345
+ rentAdjustment += rentOf(post.accountIndex, wrappedPart(post.mint, delta));
15000
14346
  }
15001
- const { data, from, to, value, gasLimit, additionalInfo, updatedQuotes } = buildTxnResponseData;
15002
- const txnParams = { from, to, data, value, gasLimit };
15003
- if (chainId === exclusiveChainIds.hyperLiquid) {
15004
- return HyperLiquidTxHandler.sendTransaction(
15005
- signer,
15006
- txnParams.from,
15007
- buildTxnResponseData,
15008
- chainId,
15009
- additionalInfo,
15010
- updatedQuotes
15011
- );
14347
+ });
14348
+ preTokenBalances.filter((balance) => balance.owner === owner && !postTokenBalances.some((post) => post.accountIndex === balance.accountIndex)).forEach((pre) => {
14349
+ const delta = -BigInt(pre.uiTokenAmount.amount);
14350
+ addDelta(pre.mint, delta);
14351
+ rentAdjustment += rentOf(pre.accountIndex, wrappedPart(pre.mint, delta));
14352
+ });
14353
+ const nativeDelta = BigInt(postBalances[0] ?? 0) - BigInt(preBalances[0] ?? 0) + BigInt(meta.fee ?? 0) + rentAdjustment;
14354
+ addDelta(solanaNativeToken, nativeDelta);
14355
+ const sent = [];
14356
+ const received = [];
14357
+ deltas.forEach((amount, token) => {
14358
+ if (amount < BigInt(0)) {
14359
+ sent.push({ token, amount: -amount });
14360
+ } else if (amount > BigInt(0)) {
14361
+ received.push({ token, amount });
15012
14362
  }
15013
- if (batchTransaction && !isTypeSigner(signer)) {
15014
- return _TradeTxnHandler.sendTxnWithBatch(request, signer, txnParams, chainId, additionalInfo, updatedQuotes, multicallAddress, rpcUrls);
14363
+ });
14364
+ if (sent.length === 0 && received.length === 0) {
14365
+ return void 0;
14366
+ }
14367
+ return { sent, received };
14368
+ };
14369
+
14370
+ // src/utils/decoder/swap/abis.ts
14371
+ var SwapAbisByFunctionName = {
14372
+ SingleSwap: [
14373
+ {
14374
+ inputs: [
14375
+ {
14376
+ internalType: "bytes32",
14377
+ name: "_transactionId",
14378
+ type: "bytes32"
14379
+ },
14380
+ {
14381
+ internalType: "bytes",
14382
+ name: "_feeData",
14383
+ type: "bytes"
14384
+ },
14385
+ {
14386
+ internalType: "bytes",
14387
+ name: "_feeVerificationSignature",
14388
+ type: "bytes"
14389
+ },
14390
+ {
14391
+ internalType: "uint256",
14392
+ name: "_deadline",
14393
+ type: "uint256"
14394
+ },
14395
+ {
14396
+ components: [
14397
+ {
14398
+ internalType: "address",
14399
+ name: "token",
14400
+ type: "address"
14401
+ },
14402
+ {
14403
+ internalType: "uint256",
14404
+ name: "amount",
14405
+ type: "uint256"
14406
+ },
14407
+ {
14408
+ internalType: "bytes",
14409
+ name: "permit",
14410
+ type: "bytes"
14411
+ }
14412
+ ],
14413
+ internalType: "struct InputToken",
14414
+ name: "_inputTokens",
14415
+ type: "tuple"
14416
+ },
14417
+ {
14418
+ components: [
14419
+ {
14420
+ internalType: "address",
14421
+ name: "recipient",
14422
+ type: "address"
14423
+ },
14424
+ {
14425
+ internalType: "address",
14426
+ name: "from",
14427
+ type: "address"
14428
+ },
14429
+ {
14430
+ internalType: "address",
14431
+ name: "to",
14432
+ type: "address"
14433
+ },
14434
+ {
14435
+ internalType: "uint256",
14436
+ name: "fromAmount",
14437
+ type: "uint256"
14438
+ },
14439
+ {
14440
+ internalType: "uint256",
14441
+ name: "minToAmount",
14442
+ type: "uint256"
14443
+ }
14444
+ ],
14445
+ internalType: "struct SwapData",
14446
+ name: "_swapData",
14447
+ type: "tuple"
14448
+ },
14449
+ {
14450
+ components: [
14451
+ {
14452
+ internalType: "string",
14453
+ name: "dex",
14454
+ type: "string"
14455
+ },
14456
+ {
14457
+ internalType: "address",
14458
+ name: "callTo",
14459
+ type: "address"
14460
+ },
14461
+ {
14462
+ internalType: "address",
14463
+ name: "approveTo",
14464
+ type: "address"
14465
+ },
14466
+ {
14467
+ internalType: "bytes",
14468
+ name: "swapCallData",
14469
+ type: "bytes"
14470
+ },
14471
+ {
14472
+ internalType: "bool",
14473
+ name: "isDirectTransfer",
14474
+ type: "bool"
14475
+ }
14476
+ ],
14477
+ internalType: "struct SwapExecutionData",
14478
+ name: "_swapExecutionData",
14479
+ type: "tuple"
14480
+ }
14481
+ ],
14482
+ name: "swap",
14483
+ outputs: [],
14484
+ stateMutability: "payable",
14485
+ type: "function"
15015
14486
  }
15016
- console.log("Using viem walletClient - sending regular transaction.");
15017
- return _TradeTxnHandler.sendTransaction(signer, txnParams, chainId, additionalInfo, updatedQuotes);
15018
- } catch (error) {
15019
- console.log({ error });
15020
- if (isAxiosError(error)) {
15021
- if (((_a = error == null ? void 0 : error.response) == null ? void 0 : _a.status) === 417 /* SimulationFailure */) {
15022
- return {
15023
- status: "error" /* error */,
15024
- errorMsg: "Simulation Failed",
15025
- error: ((_b = error.response) == null ? void 0 : _b.data).message,
15026
- code: ((_c = error.response) == null ? void 0 : _c.data).code,
15027
- action: ((_d = error.response) == null ? void 0 : _d.data).action
15028
- };
15029
- }
15030
- return {
15031
- status: "error" /* error */,
15032
- errorMsg: "Params Failed: " + JSON.stringify((_f = (_e = error == null ? void 0 : error.response) == null ? void 0 : _e.data) == null ? void 0 : _f.message),
15033
- error: ((_g = error == null ? void 0 : error.response) == null ? void 0 : _g.data) ?? error,
15034
- code: ((_h = error == null ? void 0 : error.response) == null ? void 0 : _h.status) ?? 500 /* Error */
15035
- };
14487
+ ],
14488
+ BatchPermitSwapAbi: [
14489
+ {
14490
+ inputs: [
14491
+ {
14492
+ internalType: "bytes32",
14493
+ name: "_transactionId",
14494
+ type: "bytes32"
14495
+ },
14496
+ {
14497
+ internalType: "bytes",
14498
+ name: "_feeData",
14499
+ type: "bytes"
14500
+ },
14501
+ {
14502
+ internalType: "bytes",
14503
+ name: "_feeVerificationSignature",
14504
+ type: "bytes"
14505
+ },
14506
+ {
14507
+ internalType: "uint256",
14508
+ name: "_deadline",
14509
+ type: "uint256"
14510
+ },
14511
+ {
14512
+ internalType: "bytes",
14513
+ name: "_batchDepositSignature",
14514
+ type: "bytes"
14515
+ },
14516
+ {
14517
+ components: [
14518
+ {
14519
+ components: [
14520
+ {
14521
+ internalType: "address",
14522
+ name: "token",
14523
+ type: "address"
14524
+ },
14525
+ {
14526
+ internalType: "uint256",
14527
+ name: "amount",
14528
+ type: "uint256"
14529
+ }
14530
+ ],
14531
+ internalType: "struct TokenPermissions[]",
14532
+ name: "permitted",
14533
+ type: "tuple[]"
14534
+ },
14535
+ {
14536
+ internalType: "uint256",
14537
+ name: "nonce",
14538
+ type: "uint256"
14539
+ },
14540
+ {
14541
+ internalType: "uint256",
14542
+ name: "deadline",
14543
+ type: "uint256"
14544
+ }
14545
+ ],
14546
+ internalType: "struct PermitBatchTransferFrom",
14547
+ name: "_tokenDepositDetails",
14548
+ type: "tuple"
14549
+ },
14550
+ {
14551
+ components: [
14552
+ {
14553
+ internalType: "address",
14554
+ name: "recipient",
14555
+ type: "address"
14556
+ },
14557
+ {
14558
+ internalType: "address",
14559
+ name: "from",
14560
+ type: "address"
14561
+ },
14562
+ {
14563
+ internalType: "address",
14564
+ name: "to",
14565
+ type: "address"
14566
+ },
14567
+ {
14568
+ internalType: "uint256",
14569
+ name: "fromAmount",
14570
+ type: "uint256"
14571
+ },
14572
+ {
14573
+ internalType: "uint256",
14574
+ name: "minToAmount",
14575
+ type: "uint256"
14576
+ }
14577
+ ],
14578
+ internalType: "struct SwapData[]",
14579
+ name: "_swapData",
14580
+ type: "tuple[]"
14581
+ },
14582
+ {
14583
+ components: [
14584
+ {
14585
+ internalType: "string",
14586
+ name: "dex",
14587
+ type: "string"
14588
+ },
14589
+ {
14590
+ internalType: "address",
14591
+ name: "callTo",
14592
+ type: "address"
14593
+ },
14594
+ {
14595
+ internalType: "address",
14596
+ name: "approveTo",
14597
+ type: "address"
14598
+ },
14599
+ {
14600
+ internalType: "bytes",
14601
+ name: "swapCallData",
14602
+ type: "bytes"
14603
+ },
14604
+ {
14605
+ internalType: "bool",
14606
+ name: "isDirectTransfer",
14607
+ type: "bool"
14608
+ }
14609
+ ],
14610
+ internalType: "struct SwapExecutionData[]",
14611
+ name: "_swapExecutionData",
14612
+ type: "tuple[]"
14613
+ },
14614
+ {
14615
+ internalType: "bool",
14616
+ name: "withoutRevert",
14617
+ type: "bool"
14618
+ }
14619
+ ],
14620
+ name: "swap",
14621
+ outputs: [],
14622
+ stateMutability: "payable",
14623
+ type: "function"
15036
14624
  }
15037
- return handleViemTransactionError({ error });
15038
- }
15039
- };
15040
- _TradeTxnHandler.buildGaslessTxAndSignPermit = async ({
15041
- request,
15042
- signer,
15043
- rpcUrls,
15044
- spender,
15045
- txnData,
15046
- txnStatusCallback
15047
- }) => {
15048
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
15049
- try {
15050
- const chainId = request.fromChain;
15051
- let buildTxnResponseData;
15052
- if (txnData) {
15053
- buildTxnResponseData = txnData;
15054
- } else {
15055
- buildTxnResponseData = await fetchTradeBuildTxnData({
15056
- ...request,
15057
- gasless: true
15058
- });
14625
+ ],
14626
+ MultiSwapAbi: [
14627
+ {
14628
+ inputs: [
14629
+ {
14630
+ internalType: "bytes32",
14631
+ name: "_transactionId",
14632
+ type: "bytes32"
14633
+ },
14634
+ {
14635
+ internalType: "bytes",
14636
+ name: "_feeData",
14637
+ type: "bytes"
14638
+ },
14639
+ {
14640
+ internalType: "bytes",
14641
+ name: "_feeVerificationSignature",
14642
+ type: "bytes"
14643
+ },
14644
+ {
14645
+ internalType: "uint256",
14646
+ name: "_deadline",
14647
+ type: "uint256"
14648
+ },
14649
+ {
14650
+ components: [
14651
+ {
14652
+ internalType: "address",
14653
+ name: "token",
14654
+ type: "address"
14655
+ },
14656
+ {
14657
+ internalType: "uint256",
14658
+ name: "amount",
14659
+ type: "uint256"
14660
+ },
14661
+ {
14662
+ internalType: "bytes",
14663
+ name: "permit",
14664
+ type: "bytes"
14665
+ }
14666
+ ],
14667
+ internalType: "struct InputToken[]",
14668
+ name: "_inputTokens",
14669
+ type: "tuple[]"
14670
+ },
14671
+ {
14672
+ components: [
14673
+ {
14674
+ internalType: "address",
14675
+ name: "recipient",
14676
+ type: "address"
14677
+ },
14678
+ {
14679
+ internalType: "address",
14680
+ name: "from",
14681
+ type: "address"
14682
+ },
14683
+ {
14684
+ internalType: "address",
14685
+ name: "to",
14686
+ type: "address"
14687
+ },
14688
+ {
14689
+ internalType: "uint256",
14690
+ name: "fromAmount",
14691
+ type: "uint256"
14692
+ },
14693
+ {
14694
+ internalType: "uint256",
14695
+ name: "minToAmount",
14696
+ type: "uint256"
14697
+ }
14698
+ ],
14699
+ internalType: "struct SwapData[]",
14700
+ name: "_swapData",
14701
+ type: "tuple[]"
14702
+ },
14703
+ {
14704
+ components: [
14705
+ {
14706
+ internalType: "string",
14707
+ name: "dex",
14708
+ type: "string"
14709
+ },
14710
+ {
14711
+ internalType: "address",
14712
+ name: "callTo",
14713
+ type: "address"
14714
+ },
14715
+ {
14716
+ internalType: "address",
14717
+ name: "approveTo",
14718
+ type: "address"
14719
+ },
14720
+ {
14721
+ internalType: "bytes",
14722
+ name: "swapCallData",
14723
+ type: "bytes"
14724
+ },
14725
+ {
14726
+ internalType: "bool",
14727
+ name: "isDirectTransfer",
14728
+ type: "bool"
14729
+ }
14730
+ ],
14731
+ internalType: "struct SwapExecutionData[]",
14732
+ name: "_swapExecutionData",
14733
+ type: "tuple[]"
14734
+ },
14735
+ {
14736
+ internalType: "bool",
14737
+ name: "withoutRevert",
14738
+ type: "bool"
14739
+ }
14740
+ ],
14741
+ name: "swap",
14742
+ outputs: [],
14743
+ stateMutability: "payable",
14744
+ type: "function"
15059
14745
  }
15060
- const permitType = request.hasPermit2ApprovalForAllTokens ? PermitTypes.PermitBatchWitnessTransferFrom : PermitTypes.EIP2612Permit;
15061
- const txId = buildTxnResponseData.txId;
15062
- const resp = await permit_default.signGaslessUserIntent({
15063
- tokens: request.data.map((req, index) => {
15064
- return {
15065
- address: req.srcToken,
15066
- amount: req.amount,
15067
- index
15068
- };
15069
- }),
15070
- chainId,
15071
- rpcUrls,
15072
- sender: request.sender,
15073
- spender,
15074
- permitType,
15075
- signer,
15076
- gasless: true,
15077
- txId,
15078
- service: "trade",
15079
- contractVersion: "v2" /* v2 */,
15080
- ...buildTxnResponseData.transaction
15081
- });
15082
- if (resp.status === "success" /* success */ && resp.data) {
15083
- if (txnStatusCallback) {
15084
- txnStatusCallback("waitingForExecution" /* waitingForExecution */);
15085
- }
15086
- const permit = resp.data.type === PermitTypes.EIP2612Permit ? {
15087
- permitData: request.data.map((req) => {
15088
- return {
15089
- token: req.srcToken,
15090
- amount: req.amount,
15091
- permit: req.permitData
15092
- };
15093
- }),
15094
- gaslessIntentNonce: (_a = resp.data.nonce) == null ? void 0 : _a.toString(),
15095
- gaslessIntentSignature: resp.data.signature,
15096
- gaslessIntentDeadline: (_b = resp.data.deadline) == null ? void 0 : _b.toString()
15097
- } : {
15098
- batchPermitData: resp.data.batchPermitData
15099
- };
15100
- const gaslessTxResp = await executeGaslessTxnData({
15101
- chainId: request.fromChain,
15102
- txId,
15103
- permit
15104
- });
15105
- if (gaslessTxResp.status !== "success" /* success */) {
15106
- throw new Error("Failed to execute gasless transaction");
15107
- }
15108
- return {
15109
- status: "success" /* success */,
15110
- code: 200 /* Success */,
15111
- txnHash: gaslessTxResp.txnHash
15112
- };
14746
+ ],
14747
+ GaslessExecuteMultiSwapAbi: [
14748
+ {
14749
+ inputs: [
14750
+ {
14751
+ internalType: "bytes32",
14752
+ name: "_transactionId",
14753
+ type: "bytes32"
14754
+ },
14755
+ {
14756
+ internalType: "bytes",
14757
+ name: "_feeData",
14758
+ type: "bytes"
14759
+ },
14760
+ {
14761
+ internalType: "bytes",
14762
+ name: "_feeVerificationSignature",
14763
+ type: "bytes"
14764
+ },
14765
+ {
14766
+ internalType: "bytes",
14767
+ name: "_userIntentSignature",
14768
+ type: "bytes"
14769
+ },
14770
+ {
14771
+ internalType: "uint256",
14772
+ name: "_userIntentDeadline",
14773
+ type: "uint256"
14774
+ },
14775
+ {
14776
+ internalType: "uint256",
14777
+ name: "_feeDeadline",
14778
+ type: "uint256"
14779
+ },
14780
+ {
14781
+ internalType: "address",
14782
+ name: "_user",
14783
+ type: "address"
14784
+ },
14785
+ {
14786
+ components: [
14787
+ {
14788
+ internalType: "address",
14789
+ name: "token",
14790
+ type: "address"
14791
+ },
14792
+ {
14793
+ internalType: "uint256",
14794
+ name: "amount",
14795
+ type: "uint256"
14796
+ },
14797
+ {
14798
+ internalType: "bytes",
14799
+ name: "permit",
14800
+ type: "bytes"
14801
+ }
14802
+ ],
14803
+ internalType: "struct InputToken[]",
14804
+ name: "_inputTokens",
14805
+ type: "tuple[]"
14806
+ },
14807
+ {
14808
+ components: [
14809
+ {
14810
+ internalType: "address",
14811
+ name: "token",
14812
+ type: "address"
14813
+ },
14814
+ {
14815
+ internalType: "uint256",
14816
+ name: "amount",
14817
+ type: "uint256"
14818
+ }
14819
+ ],
14820
+ internalType: "struct TokenInfo[]",
14821
+ name: "_executorFeeInfo",
14822
+ type: "tuple[]"
14823
+ },
14824
+ {
14825
+ components: [
14826
+ {
14827
+ internalType: "address",
14828
+ name: "recipient",
14829
+ type: "address"
14830
+ },
14831
+ {
14832
+ internalType: "address",
14833
+ name: "from",
14834
+ type: "address"
14835
+ },
14836
+ {
14837
+ internalType: "address",
14838
+ name: "to",
14839
+ type: "address"
14840
+ },
14841
+ {
14842
+ internalType: "uint256",
14843
+ name: "fromAmount",
14844
+ type: "uint256"
14845
+ },
14846
+ {
14847
+ internalType: "uint256",
14848
+ name: "minToAmount",
14849
+ type: "uint256"
14850
+ }
14851
+ ],
14852
+ internalType: "struct SwapData[]",
14853
+ name: "_swapData",
14854
+ type: "tuple[]"
14855
+ },
14856
+ {
14857
+ components: [
14858
+ {
14859
+ internalType: "string",
14860
+ name: "dex",
14861
+ type: "string"
14862
+ },
14863
+ {
14864
+ internalType: "address",
14865
+ name: "callTo",
14866
+ type: "address"
14867
+ },
14868
+ {
14869
+ internalType: "address",
14870
+ name: "approveTo",
14871
+ type: "address"
14872
+ },
14873
+ {
14874
+ internalType: "bytes",
14875
+ name: "swapCallData",
14876
+ type: "bytes"
14877
+ },
14878
+ {
14879
+ internalType: "bool",
14880
+ name: "isDirectTransfer",
14881
+ type: "bool"
14882
+ }
14883
+ ],
14884
+ internalType: "struct SwapExecutionData[]",
14885
+ name: "_swapExecutionData",
14886
+ type: "tuple[]"
14887
+ }
14888
+ ],
14889
+ name: "executeMultiSwap",
14890
+ outputs: [],
14891
+ stateMutability: "payable",
14892
+ type: "function"
15113
14893
  }
15114
- throw new Error("Gasless Transaction Failed");
15115
- } catch (error) {
15116
- console.log({ error });
15117
- if (isAxiosError(error)) {
15118
- if (((_c = error == null ? void 0 : error.response) == null ? void 0 : _c.status) === 417 /* SimulationFailure */) {
15119
- return {
15120
- status: "error" /* error */,
15121
- errorMsg: "Simulation Failed",
15122
- error: ((_d = error.response) == null ? void 0 : _d.data).message,
15123
- code: ((_e = error.response) == null ? void 0 : _e.data).code,
15124
- action: ((_f = error.response) == null ? void 0 : _f.data).action
15125
- };
15126
- }
15127
- return {
15128
- status: "error" /* error */,
15129
- errorMsg: "Params Failed: " + JSON.stringify((_h = (_g = error == null ? void 0 : error.response) == null ? void 0 : _g.data) == null ? void 0 : _h.message),
15130
- error: ((_i = error == null ? void 0 : error.response) == null ? void 0 : _i.data) ?? error,
15131
- code: ((_j = error == null ? void 0 : error.response) == null ? void 0 : _j.status) ?? 500 /* Error */
15132
- };
14894
+ ],
14895
+ GaslessExecuteMultiSwapWithWitnessAbi: [
14896
+ {
14897
+ inputs: [
14898
+ {
14899
+ internalType: "bytes32",
14900
+ name: "_transactionId",
14901
+ type: "bytes32"
14902
+ },
14903
+ {
14904
+ internalType: "bytes",
14905
+ name: "_feeData",
14906
+ type: "bytes"
14907
+ },
14908
+ {
14909
+ internalType: "bytes",
14910
+ name: "_feeVerificationSignature",
14911
+ type: "bytes"
14912
+ },
14913
+ {
14914
+ internalType: "bytes",
14915
+ name: "_userIntentSignature",
14916
+ type: "bytes"
14917
+ },
14918
+ {
14919
+ internalType: "uint256",
14920
+ name: "_feeDeadline",
14921
+ type: "uint256"
14922
+ },
14923
+ {
14924
+ internalType: "address",
14925
+ name: "_user",
14926
+ type: "address"
14927
+ },
14928
+ {
14929
+ components: [
14930
+ {
14931
+ components: [
14932
+ {
14933
+ internalType: "address",
14934
+ name: "token",
14935
+ type: "address"
14936
+ },
14937
+ {
14938
+ internalType: "uint256",
14939
+ name: "amount",
14940
+ type: "uint256"
14941
+ }
14942
+ ],
14943
+ internalType: "struct TokenPermissions[]",
14944
+ name: "permitted",
14945
+ type: "tuple[]"
14946
+ },
14947
+ {
14948
+ internalType: "uint256",
14949
+ name: "nonce",
14950
+ type: "uint256"
14951
+ },
14952
+ {
14953
+ internalType: "uint256",
14954
+ name: "deadline",
14955
+ type: "uint256"
14956
+ }
14957
+ ],
14958
+ internalType: "struct PermitBatchTransferFrom",
14959
+ name: "_tokenDepositDetails",
14960
+ type: "tuple"
14961
+ },
14962
+ {
14963
+ components: [
14964
+ {
14965
+ internalType: "address",
14966
+ name: "token",
14967
+ type: "address"
14968
+ },
14969
+ {
14970
+ internalType: "uint256",
14971
+ name: "amount",
14972
+ type: "uint256"
14973
+ }
14974
+ ],
14975
+ internalType: "struct TokenInfo[]",
14976
+ name: "_executorFeeInfo",
14977
+ type: "tuple[]"
14978
+ },
14979
+ {
14980
+ components: [
14981
+ {
14982
+ internalType: "address",
14983
+ name: "recipient",
14984
+ type: "address"
14985
+ },
14986
+ {
14987
+ internalType: "address",
14988
+ name: "from",
14989
+ type: "address"
14990
+ },
14991
+ {
14992
+ internalType: "address",
14993
+ name: "to",
14994
+ type: "address"
14995
+ },
14996
+ {
14997
+ internalType: "uint256",
14998
+ name: "fromAmount",
14999
+ type: "uint256"
15000
+ },
15001
+ {
15002
+ internalType: "uint256",
15003
+ name: "minToAmount",
15004
+ type: "uint256"
15005
+ }
15006
+ ],
15007
+ internalType: "struct SwapData[]",
15008
+ name: "_swapData",
15009
+ type: "tuple[]"
15010
+ },
15011
+ {
15012
+ components: [
15013
+ {
15014
+ internalType: "string",
15015
+ name: "dex",
15016
+ type: "string"
15017
+ },
15018
+ {
15019
+ internalType: "address",
15020
+ name: "callTo",
15021
+ type: "address"
15022
+ },
15023
+ {
15024
+ internalType: "address",
15025
+ name: "approveTo",
15026
+ type: "address"
15027
+ },
15028
+ {
15029
+ internalType: "bytes",
15030
+ name: "swapCallData",
15031
+ type: "bytes"
15032
+ },
15033
+ {
15034
+ internalType: "bool",
15035
+ name: "isDirectTransfer",
15036
+ type: "bool"
15037
+ }
15038
+ ],
15039
+ internalType: "struct SwapExecutionData[]",
15040
+ name: "_swapExecutionData",
15041
+ type: "tuple[]"
15042
+ }
15043
+ ],
15044
+ name: "executeMultiSwapWithWitness",
15045
+ outputs: [],
15046
+ stateMutability: "payable",
15047
+ type: "function"
15048
+ }
15049
+ ],
15050
+ GaslessExecuteSwapAbi: [
15051
+ {
15052
+ inputs: [
15053
+ {
15054
+ internalType: "bytes32",
15055
+ name: "_transactionId",
15056
+ type: "bytes32"
15057
+ },
15058
+ {
15059
+ internalType: "bytes",
15060
+ name: "_feeData",
15061
+ type: "bytes"
15062
+ },
15063
+ {
15064
+ internalType: "bytes",
15065
+ name: "_feeVerificationSignature",
15066
+ type: "bytes"
15067
+ },
15068
+ {
15069
+ internalType: "bytes",
15070
+ name: "_userIntentSignature",
15071
+ type: "bytes"
15072
+ },
15073
+ {
15074
+ internalType: "uint256",
15075
+ name: "_userIntentDeadline",
15076
+ type: "uint256"
15077
+ },
15078
+ {
15079
+ internalType: "uint256",
15080
+ name: "_feeDeadline",
15081
+ type: "uint256"
15082
+ },
15083
+ {
15084
+ internalType: "address",
15085
+ name: "_user",
15086
+ type: "address"
15087
+ },
15088
+ {
15089
+ components: [
15090
+ {
15091
+ internalType: "address",
15092
+ name: "token",
15093
+ type: "address"
15094
+ },
15095
+ {
15096
+ internalType: "uint256",
15097
+ name: "amount",
15098
+ type: "uint256"
15099
+ },
15100
+ {
15101
+ internalType: "bytes",
15102
+ name: "permit",
15103
+ type: "bytes"
15104
+ }
15105
+ ],
15106
+ internalType: "struct InputToken",
15107
+ name: "_inputToken",
15108
+ type: "tuple"
15109
+ },
15110
+ {
15111
+ components: [
15112
+ {
15113
+ internalType: "address",
15114
+ name: "token",
15115
+ type: "address"
15116
+ },
15117
+ {
15118
+ internalType: "uint256",
15119
+ name: "amount",
15120
+ type: "uint256"
15121
+ }
15122
+ ],
15123
+ internalType: "struct TokenInfo",
15124
+ name: "_executorFeeInfo",
15125
+ type: "tuple"
15126
+ },
15127
+ {
15128
+ components: [
15129
+ {
15130
+ internalType: "address",
15131
+ name: "recipient",
15132
+ type: "address"
15133
+ },
15134
+ {
15135
+ internalType: "address",
15136
+ name: "from",
15137
+ type: "address"
15138
+ },
15139
+ {
15140
+ internalType: "address",
15141
+ name: "to",
15142
+ type: "address"
15143
+ },
15144
+ {
15145
+ internalType: "uint256",
15146
+ name: "fromAmount",
15147
+ type: "uint256"
15148
+ },
15149
+ {
15150
+ internalType: "uint256",
15151
+ name: "minToAmount",
15152
+ type: "uint256"
15153
+ }
15154
+ ],
15155
+ internalType: "struct SwapData",
15156
+ name: "_swapData",
15157
+ type: "tuple"
15158
+ },
15159
+ {
15160
+ components: [
15161
+ {
15162
+ internalType: "string",
15163
+ name: "dex",
15164
+ type: "string"
15165
+ },
15166
+ {
15167
+ internalType: "address",
15168
+ name: "callTo",
15169
+ type: "address"
15170
+ },
15171
+ {
15172
+ internalType: "address",
15173
+ name: "approveTo",
15174
+ type: "address"
15175
+ },
15176
+ {
15177
+ internalType: "bytes",
15178
+ name: "swapCallData",
15179
+ type: "bytes"
15180
+ },
15181
+ {
15182
+ internalType: "bool",
15183
+ name: "isDirectTransfer",
15184
+ type: "bool"
15185
+ }
15186
+ ],
15187
+ internalType: "struct SwapExecutionData",
15188
+ name: "_swapExecutionData",
15189
+ type: "tuple"
15190
+ }
15191
+ ],
15192
+ name: "executeSwap",
15193
+ outputs: [],
15194
+ stateMutability: "payable",
15195
+ type: "function"
15133
15196
  }
15134
- return handleViemTransactionError({ error });
15135
- }
15197
+ ]
15136
15198
  };
15137
- var TradeTxnHandler = _TradeTxnHandler;
15138
- var trade_default = TradeTxnHandler;
15139
15199
 
15140
- // src/zap/constants/step.ts
15141
- var zapStepAction = {
15142
- execute: "execute"
15200
+ // src/utils/decoder/swap/evm.ts
15201
+ var decodeSingleSwapData = (data) => {
15202
+ var _a;
15203
+ const decodedData = utils.decodeFunctionData({ data, abi: SwapAbisByFunctionName.SingleSwap });
15204
+ return [(_a = decodedData == null ? void 0 : decodedData.args) == null ? void 0 : _a[4]];
15205
+ };
15206
+ var decodeMultiSwapData = (data) => {
15207
+ var _a;
15208
+ const decodedData = utils.decodeFunctionData({ data, abi: SwapAbisByFunctionName.MultiSwapAbi });
15209
+ return (_a = decodedData == null ? void 0 : decodedData.args) == null ? void 0 : _a[4];
15210
+ };
15211
+ var decodeBatchPermitSwapData = (data) => {
15212
+ var _a, _b;
15213
+ const decodedData = utils.decodeFunctionData({ data, abi: SwapAbisByFunctionName.BatchPermitSwapAbi });
15214
+ return (_b = (_a = decodedData == null ? void 0 : decodedData.args) == null ? void 0 : _a[5]) == null ? void 0 : _b.permitted;
15215
+ };
15216
+ var decodeGaslessExecuteMultiSwapData = (data) => {
15217
+ var _a;
15218
+ const decodedData = utils.decodeFunctionData({ data, abi: SwapAbisByFunctionName.GaslessExecuteMultiSwapAbi });
15219
+ return (_a = decodedData == null ? void 0 : decodedData.args) == null ? void 0 : _a[7];
15220
+ };
15221
+ var decodeGaslessExecuteMultiSwapWithWitnessData = (data) => {
15222
+ var _a;
15223
+ const decodedData = utils.decodeFunctionData({ data, abi: SwapAbisByFunctionName.GaslessExecuteMultiSwapWithWitnessAbi });
15224
+ return (_a = decodedData == null ? void 0 : decodedData.args) == null ? void 0 : _a[7];
15225
+ };
15226
+ var decodeGaslessExecuteSwapData = (data) => {
15227
+ var _a;
15228
+ const decodedData = utils.decodeFunctionData({ data, abi: SwapAbisByFunctionName.GaslessExecuteSwapAbi });
15229
+ return [(_a = decodedData == null ? void 0 : decodedData.args) == null ? void 0 : _a[7]];
15230
+ };
15231
+ var swapFunctionSignatureWithInputTokenIndex = {
15232
+ "0x50d52584": decodeSingleSwapData,
15233
+ "0x8de34776": decodeMultiSwapData,
15234
+ "0x8d44ea24": decodeBatchPermitSwapData,
15235
+ "0xd367ada5": decodeGaslessExecuteMultiSwapData,
15236
+ "0xdcdc6089": decodeGaslessExecuteMultiSwapWithWitnessData,
15237
+ "0x0d2eedd4": decodeGaslessExecuteSwapData
15238
+ };
15239
+ var decodeEvmTransaction = async ({ txHash, chainId, rpcUrls }) => {
15240
+ const { input } = await getPublicClient({ chainId, rpcUrls }).getTransaction({ hash: txHash });
15241
+ const decoder = swapFunctionSignatureWithInputTokenIndex[input.slice(0, 10)];
15242
+ if (!decoder) {
15243
+ return void 0;
15244
+ }
15245
+ const sent = decoder(input).filter((item) => (item == null ? void 0 : item.token) && (item == null ? void 0 : item.amount));
15246
+ if (sent.length === 0) {
15247
+ return void 0;
15248
+ }
15249
+ return { sent };
15143
15250
  };
15144
15251
 
15145
- // src/transactionHandlers/zap.ts
15146
- var _ZapTxnHandler = class _ZapTxnHandler {
15252
+ // src/utils/decoder/swap/index.ts
15253
+ var transactionDecoders = {
15254
+ [chainTypes.evm]: decodeEvmTransaction,
15255
+ [chainTypes.svm]: decodeSvmTransaction,
15256
+ [chainTypes.suivm]: decodeSuivmTransaction
15147
15257
  };
15148
- _ZapTxnHandler.execute = async ({
15258
+ var amountByToken = (tokenAmounts) => tokenAmounts.reduce(
15259
+ (acc, cur) => {
15260
+ const token = formatToken(cur.token);
15261
+ acc[token] = (acc[token] ?? BigInt(0)) + cur.amount;
15262
+ return acc;
15263
+ },
15264
+ {}
15265
+ );
15266
+ var swapCountByToken = (tokens) => tokens.reduce(
15267
+ (acc, cur) => {
15268
+ const token = formatToken(cur);
15269
+ acc[token] = (acc[token] ?? 0) + 1;
15270
+ return acc;
15271
+ },
15272
+ {}
15273
+ );
15274
+ var applyTxTokenAmounts = (eventSwapInfo, txTokenAmounts) => {
15275
+ const swaps = Array.isArray(eventSwapInfo) ? eventSwapInfo : [eventSwapInfo];
15276
+ const sentByToken = amountByToken(txTokenAmounts.sent);
15277
+ const receivedByToken = amountByToken(txTokenAmounts.received ?? []);
15278
+ const swapsByFromToken = swapCountByToken(swaps.map((info) => info.fromToken));
15279
+ const swapsByToToken = swapCountByToken(swaps.map((info) => info.toToken));
15280
+ const amountOf = (amounts, swapCounts, token) => swapCounts[formatToken(token)] === 1 ? amounts[formatToken(token)] : void 0;
15281
+ let isAmountPatched = false;
15282
+ const patch = (info) => {
15283
+ const fromAmount = amountOf(sentByToken, swapsByFromToken, info.fromToken);
15284
+ const returnToAmount = amountOf(receivedByToken, swapsByToToken, info.toToken);
15285
+ isAmountPatched = isAmountPatched || fromAmount !== void 0 || returnToAmount !== void 0;
15286
+ return { ...info, fromAmount: fromAmount ?? info.fromAmount, returnToAmount: returnToAmount ?? info.returnToAmount };
15287
+ };
15288
+ const swapInfo = Array.isArray(eventSwapInfo) ? eventSwapInfo.map(patch) : patch(eventSwapInfo);
15289
+ return isAmountPatched ? { swapInfo, isAmountPatched } : { swapInfo, isAmountPatched, amountPatchError: "no token amount of the transaction matched a swap token" };
15290
+ };
15291
+ var patchSwapAmountsFromTx = async ({
15292
+ chainType,
15149
15293
  chainId,
15150
- txnData,
15151
- signer
15294
+ txHash,
15295
+ rpcUrls,
15296
+ eventSwapInfo
15152
15297
  }) => {
15153
- var _a;
15298
+ const decodeTransaction = transactionDecoders[chainType];
15299
+ if (!decodeTransaction) {
15300
+ return { swapInfo: eventSwapInfo, isAmountPatched: false, amountPatchError: `decoding ${chainType} transactions is not supported` };
15301
+ }
15154
15302
  try {
15155
- const { callData, callTo, value, estimatedGas } = txnData;
15156
- if (isTypeSigner(signer)) {
15157
- console.log("Using ethers signer.");
15158
- const from = await signer.getAddress();
15159
- const txnRes = await signer.sendTransaction({
15160
- from,
15161
- to: callTo,
15162
- data: callData,
15163
- value: BigInt(value),
15164
- gasLimit: BigInt(estimatedGas) ? BigInt(estimatedGas) : void 0
15165
- });
15166
- return {
15167
- status: "success" /* success */,
15168
- code: 200 /* Success */,
15169
- txnHash: txnRes.hash
15170
- };
15171
- } else {
15172
- console.log("Using viem walletClient.");
15173
- const txnHash = await signer.sendTransaction({
15174
- chain: viemChainsById[chainId],
15175
- account: (_a = signer.account) == null ? void 0 : _a.address,
15176
- to: txnData.callTo,
15177
- data: txnData.callData,
15178
- value: BigInt(txnData.value)
15179
- });
15180
- return {
15181
- status: "success" /* success */,
15182
- code: 200 /* Success */,
15183
- txnHash
15184
- };
15303
+ const txTokenAmounts = await decodeTransaction({ txHash, chainId, rpcUrls: rpcUrls ?? config.getRpcUrlsByChainId(chainId) });
15304
+ if (!txTokenAmounts) {
15305
+ return { swapInfo: eventSwapInfo, isAmountPatched: false, amountPatchError: `no token amounts could be decoded from transaction ${txHash}` };
15185
15306
  }
15307
+ return applyTxTokenAmounts(eventSwapInfo, txTokenAmounts);
15186
15308
  } catch (error) {
15187
- console.log({ error });
15188
- return handleViemTransactionError({ error });
15309
+ return { swapInfo: eventSwapInfo, isAmountPatched: false, amountPatchError: error instanceof Error ? error.message : String(error) };
15189
15310
  }
15190
15311
  };
15191
- _ZapTxnHandler.approve = async ({ chainId, data, signer }) => {
15192
- var _a;
15312
+
15313
+ // src/utils/decoder/index.ts
15314
+ var formatSwapInfoTokens = (info, chain) => {
15315
+ var _a, _b;
15316
+ return {
15317
+ ...info,
15318
+ fromToken: formatToken(info.fromToken, (_a = chain == null ? void 0 : chain.nativeToken) == null ? void 0 : _a.contract),
15319
+ toToken: formatToken(info.toToken, (_b = chain == null ? void 0 : chain.nativeToken) == null ? void 0 : _b.contract)
15320
+ };
15321
+ };
15322
+ var getTxReceipt = async ({ chainId, txHash, rpcUrls }) => {
15323
+ return getPublicClient({ chainId, rpcUrls }).getTransactionReceipt({ hash: txHash });
15324
+ };
15325
+ var decodeSwapInfoFromReceipt = async ({
15326
+ txReceipt,
15327
+ service,
15328
+ chain
15329
+ }) => {
15330
+ var _a, _b;
15331
+ let events = [];
15332
+ const dZapAbi = getDZapAbi(service, (chain == null ? void 0 : chain.version) || "v1" /* v1 */);
15193
15333
  try {
15194
- const { callData, callTo, value, estimatedGas } = data;
15195
- const publicClient = getPublicClient({ chainId, rpcUrls: void 0 });
15196
- const blockNumber = await publicClient.getBlockNumber();
15197
- console.log("block Number and data");
15198
- console.dir(
15199
- {
15200
- blockNumber,
15201
- ...data
15202
- },
15203
- { depth: null }
15204
- );
15205
- if (isTypeSigner(signer)) {
15206
- console.log("Using ethers signer.");
15207
- const from = await signer.getAddress();
15208
- const txnRes = await signer.sendTransaction({
15209
- from,
15210
- to: callTo,
15211
- data: callData,
15212
- value: BigInt(value),
15213
- gasLimit: BigInt(estimatedGas) ? BigInt(estimatedGas) : void 0
15214
- });
15215
- return {
15216
- status: "success" /* success */,
15217
- code: 200 /* Success */,
15218
- txnHash: txnRes.hash
15219
- };
15220
- } else {
15221
- console.log("Using viem walletClient.");
15222
- const txnHash = await signer.sendTransaction({
15223
- chain: viemChainsById[chainId],
15224
- account: (_a = signer.account) == null ? void 0 : _a.address,
15225
- to: data.callTo,
15226
- data: data.callData,
15227
- value: BigInt(data.value)
15228
- });
15229
- return {
15230
- status: "success" /* success */,
15231
- code: 200 /* Success */,
15232
- txnHash
15233
- };
15234
- }
15235
- } catch (error) {
15236
- console.log({ error });
15237
- return handleViemTransactionError({ error });
15334
+ events = viem.parseEventLogs({ abi: dZapAbi, logs: txReceipt.logs });
15335
+ } catch {
15336
+ events = [];
15238
15337
  }
15338
+ const eventSwapInfo = (_b = (_a = events == null ? void 0 : events.find((item) => item !== null)) == null ? void 0 : _a.args) == null ? void 0 : _b.swapInfo;
15339
+ let swapInfo = [];
15340
+ if (Array.isArray(eventSwapInfo)) {
15341
+ swapInfo = eventSwapInfo.map((info) => formatSwapInfoTokens(info, chain));
15342
+ } else if (typeof eventSwapInfo === "object" && Object.keys(eventSwapInfo).length > 0) {
15343
+ swapInfo = formatSwapInfoTokens(eventSwapInfo, chain);
15344
+ }
15345
+ return { txHash: txReceipt.transactionHash, swapInfo };
15239
15346
  };
15240
- _ZapTxnHandler.zap = async ({
15241
- request,
15242
- steps,
15243
- signer
15347
+ var fetchReceiptAndDecodeSwapInfo = async ({
15348
+ params,
15349
+ chain,
15350
+ rpcUrls
15244
15351
  }) => {
15245
- try {
15246
- const chainId = "srcChainId" in request ? request.srcChainId : request.actions[0].srcChainId;
15247
- if (!steps || steps.length === 0) {
15248
- const route = "actions" in request ? (await fetchZapBundleBuildTx(request)).data : (await fetchZapBuildTxnData(request)).data;
15249
- steps = route.steps;
15250
- if (!steps || steps.length === 0) {
15251
- return {
15252
- status: "error" /* error */,
15253
- code: 32771 /* FunctionNotFound */,
15254
- errorMsg: "No steps found in the zap route."
15255
- };
15256
- }
15257
- }
15258
- let txnHash;
15259
- for (let i = 0; i < steps.length; i++) {
15260
- const step = steps[i];
15261
- if (step.action === zapStepAction.execute) {
15262
- const result = await _ZapTxnHandler.execute({ chainId, txnData: step.data, signer });
15263
- if (result.status !== "success" /* success */) {
15264
- return result;
15265
- }
15266
- txnHash = result.txnHash;
15267
- }
15268
- }
15269
- if (!txnHash) {
15270
- return {
15271
- status: "error" /* error */,
15272
- code: 500 /* Error */,
15273
- errorMsg: "No executable steps found."
15274
- };
15275
- }
15276
- return {
15277
- status: "success" /* success */,
15278
- code: 200 /* Success */,
15279
- txnHash
15280
- };
15281
- } catch (error) {
15282
- console.log({ error });
15283
- return handleViemTransactionError({ error });
15352
+ const txReceipt = await getTxReceipt({ txHash: params.txHash, chainId: chain.chainId, rpcUrls });
15353
+ return decodeSwapInfoFromReceipt({ txReceipt, service: params.service, chain });
15354
+ };
15355
+ var readGivenSwapInfo = async ({ params }) => {
15356
+ if ("txHash" in params && "eventSwapInfo" in params && typeof params.eventSwapInfo === "object" && Object.keys(params.eventSwapInfo).length > 0) {
15357
+ return { txHash: params.txHash, swapInfo: params.eventSwapInfo };
15284
15358
  }
15359
+ throw new Error("Invalid decode params");
15360
+ };
15361
+ var getSwapFailPairs = (swapInfo, chain) => (Array.isArray(swapInfo) ? swapInfo : [swapInfo]).filter((info) => BigInt(info.returnToAmount) === BigInt(0)).map(
15362
+ (info) => {
15363
+ var _a, _b;
15364
+ return getTokensPairKey({
15365
+ srcToken: info.fromToken,
15366
+ destToken: info.toToken,
15367
+ srcChainId: chain.chainId,
15368
+ destChainId: chain.chainId,
15369
+ srcChainNativeAddress: (_a = chain == null ? void 0 : chain.nativeToken) == null ? void 0 : _a.contract,
15370
+ destChainNativeAddress: (_b = chain == null ? void 0 : chain.nativeToken) == null ? void 0 : _b.contract
15371
+ });
15372
+ }
15373
+ );
15374
+ var getSwapInfoForEvm = async ({ params, chain, rpcUrls }) => {
15375
+ if ("receipt" in params) {
15376
+ return await decodeSwapInfoFromReceipt({ txReceipt: params.receipt, service: params.service, chain });
15377
+ }
15378
+ if ("txHash" in params) {
15379
+ return await fetchReceiptAndDecodeSwapInfo({ params, chain, rpcUrls });
15380
+ }
15381
+ if ("eventSwapInfo" in params) {
15382
+ return await readGivenSwapInfo({ params });
15383
+ }
15384
+ throw new Error("Invalid decode params");
15385
+ };
15386
+ var chainDecoders = {
15387
+ [chainTypes.evm]: getSwapInfoForEvm,
15388
+ [chainTypes.svm]: readGivenSwapInfo,
15389
+ [chainTypes.suivm]: readGivenSwapInfo
15390
+ };
15391
+ var decodeTxnData = async (params) => {
15392
+ const { chainId, rpcUrls, chainsConfig } = params;
15393
+ const chain = chainsConfig[chainId];
15394
+ const decoder = chainDecoders[chain.chainType];
15395
+ if (!decoder) {
15396
+ throw new Error(`No decoder found for chain type ${chain.chainType}`);
15397
+ }
15398
+ const { txHash, swapInfo } = await decoder({ params, chain, rpcUrls });
15399
+ const patchResult = await patchSwapAmountsFromTx({ chainType: chain.chainType, chainId: chain.chainId, txHash, rpcUrls, eventSwapInfo: swapInfo });
15400
+ return { ...patchResult, swapFailPairs: getSwapFailPairs(patchResult.swapInfo, chain) };
15285
15401
  };
15286
- var ZapTxnHandler = _ZapTxnHandler;
15287
- var zap_default = ZapTxnHandler;
15288
15402
  var calculateAmountUSD = (amountInWei, decimals, price) => {
15289
15403
  return decimals ? new Decimal__default.default(viem.formatUnits(BigInt(amountInWei), decimals)).mul(price || 0).toFixed(5) : "0";
15290
15404
  };
@@ -15904,15 +16018,22 @@ var _DZapClient = class _DZapClient {
15904
16018
  return await waitForBatchTransactionReceipt(walletClient, batchHash);
15905
16019
  }
15906
16020
  /**
15907
- * Decodes and interprets transaction receipt data for DZap protocol operations.
15908
- * This method parses transaction logs and events to provide human-readable transaction details.
15909
- * Useful for analyzing completed transactions and extracting structured data.
16021
+ * Decodes and interprets transaction data for DZap protocol operations on any supported chain type,
16022
+ * resolving the swap info and the actual fromAmount/returnToAmount of each swap.
16023
+ * On EVM the swap info is parsed from the transaction receipt's events. Solana and Sui have no such
16024
+ * event, so the caller-supplied `eventSwapInfo` (e.g. the quoted swap info) is patched with the
16025
+ * amounts the transaction actually moved.
15910
16026
  *
15911
16027
  * @param params - Configuration object for transaction decoding
15912
- * @param params.data - The transaction receipt containing logs and events to decode
16028
+ * @param params.data - EVM: the transaction receipt to decode, fetched by `txHash` when omitted
16029
+ * @param params.txHash - The transaction hash, signature or digest; required on non-EVM chains
16030
+ * @param params.eventSwapInfo - Non-EVM: the swap info to patch with the actual amounts
15913
16031
  * @param params.service - The DZap service type that generated the transaction
15914
16032
  * @param params.chainId - The blockchain network ID where the transaction occurred
15915
- * @returns Promise resolving to decoded transaction data with structured information
16033
+ * @param params.rpcUrls - Optional custom RPC URLs to read the transaction from
16034
+ * @returns Promise resolving to the swap info and failed swap pairs. `isAmountPatched` tells whether the
16035
+ * amounts were read from the transaction; when they could not be, the swap info is returned as given and
16036
+ * `amountPatchError` says why.
15916
16037
  *
15917
16038
  * @example
15918
16039
  * ```typescript
@@ -15925,18 +16046,9 @@ var _DZapClient = class _DZapClient {
15925
16046
  * console.log('Decoded transaction:', decodedData);
15926
16047
  * ```
15927
16048
  */
15928
- async decodeTxnData({ data, service, chainId }) {
15929
- const publicClient = getPublicClient({ chainId, rpcUrls: config.getRpcUrlsByChainId(chainId) });
15930
- const [chainConfig, transactionData] = await Promise.all([
15931
- _DZapClient.getChainConfig(),
15932
- publicClient.getTransaction({
15933
- hash: data.transactionHash
15934
- })
15935
- ]);
15936
- if (chainConfig === null || (chainConfig == null ? void 0 : chainConfig[chainId]) == null) {
15937
- throw new Error("Chains config not found");
15938
- }
15939
- return handleDecodeTxnData(transactionData, data, service, chainConfig[chainId]);
16049
+ async decodeTxnData(params) {
16050
+ const chainConfig = await _DZapClient.getChainConfig();
16051
+ return decodeTxnData({ ...params, chainsConfig: chainConfig });
15940
16052
  }
15941
16053
  /**
15942
16054
  * Calculates DZap reward points for completed trade operations including swaps and bridges.
@@ -16750,7 +16862,7 @@ async function classifyEvmAddress(params) {
16750
16862
  };
16751
16863
  }
16752
16864
  }
16753
- var SUI_DEFAULT_RPC = "https://fullnode.mainnet.sui.io";
16865
+ var SUI_DEFAULT_RPC2 = "https://fullnode.mainnet.sui.io";
16754
16866
  var suiAccountRegex = /^0x[a-fA-F0-9]{1,64}$/;
16755
16867
  var moveCoinTypeRegex2 = /^0x[a-fA-F0-9]{1,64}::[A-Za-z_][A-Za-z0-9_]*::[A-Za-z_][A-Za-z0-9_]*$/;
16756
16868
  async function classifySuivmAddress(params) {
@@ -16786,7 +16898,7 @@ async function classifySuivmAddress(params) {
16786
16898
  address
16787
16899
  };
16788
16900
  }
16789
- const rpcUrl = (rpcUrls == null ? void 0 : rpcUrls[0]) ?? SUI_DEFAULT_RPC;
16901
+ const rpcUrl = (rpcUrls == null ? void 0 : rpcUrls[0]) ?? SUI_DEFAULT_RPC2;
16790
16902
  try {
16791
16903
  const response = await Axios__default.default.post(rpcUrl, {
16792
16904
  jsonrpc: "2.0",
@@ -17144,7 +17256,6 @@ exports.STATUS = STATUS;
17144
17256
  exports.Services = Services;
17145
17257
  exports.SignatureExpiryInSecs = SignatureExpiryInSecs;
17146
17258
  exports.StatusCodes = StatusCodes;
17147
- exports.SwapInputDataDecoder = SwapInputDataDecoder;
17148
17259
  exports.TxnStatus = TxnStatus;
17149
17260
  exports.arcTestnet = arcTestnet;
17150
17261
  exports.arthera = arthera;
@@ -17166,6 +17277,7 @@ exports.hyperEvm = hyperEvm;
17166
17277
  exports.hyperliquid = hyperliquid;
17167
17278
  exports.katana = katana;
17168
17279
  exports.merlin = merlin;
17280
+ exports.patchSwapAmountsFromTx = patchSwapAmountsFromTx;
17169
17281
  exports.pushTestnet = pushTestnet;
17170
17282
  exports.robinhood = robinhood;
17171
17283
  exports.stableChain = stableChain;