@allbridge/bridge-core-sdk 3.26.0-alpha.9 → 3.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/index.js +1 -6
- package/dist/browser/index.js.map +4 -4
- package/dist/cjs/index.js +1 -6
- package/dist/cjs/index.js.map +4 -4
- package/dist/esm/index.js +1 -6
- package/dist/esm/index.js.map +4 -4
- package/dist/src/chains/chain.enums.d.ts +3 -4
- package/dist/src/chains/chain.enums.js +2 -3
- package/dist/src/chains/chain.enums.js.map +1 -1
- package/dist/src/chains/index.js +6 -6
- package/dist/src/chains/index.js.map +1 -1
- package/dist/src/client/core-api/core-api-mapper.js +0 -1
- package/dist/src/client/core-api/core-api-mapper.js.map +1 -1
- package/dist/src/client/core-api/core-api.model.d.ts +0 -1
- package/dist/src/client/core-api/core-api.model.js.map +1 -1
- package/dist/src/services/bridge/index.js +0 -16
- package/dist/src/services/bridge/index.js.map +1 -1
- package/dist/src/services/bridge/models/bridge.model.d.ts +0 -1
- package/dist/src/services/bridge/models/bridge.model.js.map +1 -1
- package/dist/src/services/bridge/sui/index.js.map +1 -1
- package/dist/src/services/bridge/utils.d.ts +1 -3
- package/dist/src/services/bridge/utils.js +15 -72
- package/dist/src/services/bridge/utils.js.map +1 -1
- package/dist/src/services/liquidity-pool/index.js +0 -16
- package/dist/src/services/liquidity-pool/index.js.map +1 -1
- package/dist/src/services/liquidity-pool/sui/index.js.map +1 -1
- package/dist/src/services/liquidity-pool/trx/index.js.map +1 -1
- package/dist/src/services/models/index.d.ts +5 -6
- package/dist/src/services/models/index.js.map +1 -1
- package/dist/src/services/token/index.js +0 -16
- package/dist/src/services/token/index.js.map +1 -1
- package/dist/src/services/token/sui/index.js.map +1 -1
- package/dist/src/services/utils/trx/index.js.map +1 -1
- package/dist/src/services/yield/index.js +0 -4
- package/dist/src/services/yield/index.js.map +1 -1
- package/dist/src/tokens-info/tokens-info.model.d.ts +0 -4
- package/dist/src/tokens-info/tokens-info.model.js.map +1 -1
- package/dist/src/utils/index.d.ts +0 -3
- package/dist/src/utils/index.js +0 -3
- package/dist/src/utils/index.js.map +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/dist/src/version.js.map +1 -1
- package/package.json +2 -5
- package/dist/src/services/bridge/alg/index.d.ts +0 -15
- package/dist/src/services/bridge/alg/index.js +0 -151
- package/dist/src/services/bridge/alg/index.js.map +0 -1
- package/dist/src/services/liquidity-pool/alg/index.d.ts +0 -19
- package/dist/src/services/liquidity-pool/alg/index.js +0 -141
- package/dist/src/services/liquidity-pool/alg/index.js.map +0 -1
- package/dist/src/services/models/alg/BridgeClient.d.ts +0 -2718
- package/dist/src/services/models/alg/BridgeClient.js +0 -2633
- package/dist/src/services/models/alg/BridgeClient.js.map +0 -1
- package/dist/src/services/models/alg/PoolClient.d.ts +0 -2265
- package/dist/src/services/models/alg/PoolClient.js +0 -2176
- package/dist/src/services/models/alg/PoolClient.js.map +0 -1
- package/dist/src/services/token/alg/index.d.ts +0 -17
- package/dist/src/services/token/alg/index.js +0 -46
- package/dist/src/services/token/alg/index.js.map +0 -1
- package/dist/src/services/utils/alg/index.d.ts +0 -17
- package/dist/src/services/utils/alg/index.js +0 -81
- package/dist/src/services/utils/alg/index.js.map +0 -1
- package/dist/src/utils/alg/index.d.ts +0 -21
- package/dist/src/utils/alg/index.js +0 -76
- package/dist/src/utils/alg/index.js.map +0 -1
|
@@ -1,27 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
-
if (mod && mod.__esModule) return mod;
|
|
20
|
-
var result = {};
|
|
21
|
-
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
-
__setModuleDefault(result, mod);
|
|
23
|
-
return result;
|
|
24
|
-
};
|
|
25
2
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
26
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
27
4
|
};
|
|
@@ -30,7 +7,6 @@ exports.formatAddress = formatAddress;
|
|
|
30
7
|
exports.normalizeSuiHex = normalizeSuiHex;
|
|
31
8
|
exports.hexToBuffer = hexToBuffer;
|
|
32
9
|
exports.evmAddressToBuffer32 = evmAddressToBuffer32;
|
|
33
|
-
exports.algAddressToBuffer32 = algAddressToBuffer32;
|
|
34
10
|
exports.tronAddressToBuffer32 = tronAddressToBuffer32;
|
|
35
11
|
exports.tronAddressToEthAddress = tronAddressToEthAddress;
|
|
36
12
|
exports.getTokenByTokenAddress = getTokenByTokenAddress;
|
|
@@ -43,7 +19,6 @@ exports.getExtraGasMaxLimits = getExtraGasMaxLimits;
|
|
|
43
19
|
exports.isSendParams = isSendParams;
|
|
44
20
|
const web3_js_1 = require("@solana/web3.js");
|
|
45
21
|
const stellar_sdk_1 = require("@stellar/stellar-sdk");
|
|
46
|
-
const algosdk_1 = __importStar(require("algosdk"));
|
|
47
22
|
const big_js_1 = require("big.js");
|
|
48
23
|
const randombytes_1 = __importDefault(require("randombytes"));
|
|
49
24
|
const tronweb_1 = require("tronweb");
|
|
@@ -76,10 +51,6 @@ function formatAddress(address, from, to) {
|
|
|
76
51
|
buffer = evmAddressToBuffer32(address);
|
|
77
52
|
break;
|
|
78
53
|
}
|
|
79
|
-
case models_1.ChainType.ALG: {
|
|
80
|
-
buffer = algAddressToBuffer32(address);
|
|
81
|
-
break;
|
|
82
|
-
}
|
|
83
54
|
}
|
|
84
55
|
switch (to) {
|
|
85
56
|
case models_1.ChainType.EVM: {
|
|
@@ -97,9 +68,6 @@ function formatAddress(address, from, to) {
|
|
|
97
68
|
case models_1.ChainType.SUI: {
|
|
98
69
|
return "0x" + buffer.toString("hex");
|
|
99
70
|
}
|
|
100
|
-
case models_1.ChainType.ALG: {
|
|
101
|
-
return buffer;
|
|
102
|
-
}
|
|
103
71
|
}
|
|
104
72
|
}
|
|
105
73
|
function normalizeSuiHex(hex) {
|
|
@@ -113,17 +81,6 @@ function evmAddressToBuffer32(address) {
|
|
|
113
81
|
const buff = hexToBuffer(address);
|
|
114
82
|
return Buffer.concat([Buffer.alloc(length - buff.length, 0), buff], length);
|
|
115
83
|
}
|
|
116
|
-
function algAddressToBuffer32(address) {
|
|
117
|
-
if (algosdk_1.default.isValidAddress(address)) {
|
|
118
|
-
return Buffer.from(algosdk_1.Address.fromString(address).publicKey);
|
|
119
|
-
}
|
|
120
|
-
if (/^\d+$/.test(address)) {
|
|
121
|
-
let hex = BigInt(address).toString(16);
|
|
122
|
-
hex = hex.padStart(64, "0");
|
|
123
|
-
return Buffer.from(hex, "hex");
|
|
124
|
-
}
|
|
125
|
-
throw new exceptions_1.SdkError(`Unexpected Alg address: ${address}`);
|
|
126
|
-
}
|
|
127
84
|
function tronAddressToBuffer32(address) {
|
|
128
85
|
const ethAddress = tronAddressToEthAddress(address);
|
|
129
86
|
const buffer = hexToBuffer(ethAddress);
|
|
@@ -171,38 +128,24 @@ function prepareTxSwapParams(bridgeChainType, params) {
|
|
|
171
128
|
txSwapParams.amount = (0, calculation_1.convertFloatAmountToInt)(params.amount, sourceToken.decimals).toFixed();
|
|
172
129
|
txSwapParams.contractAddress = sourceToken.bridgeAddress;
|
|
173
130
|
txSwapParams.fromAccountAddress = params.fromAccountAddress;
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
throw new exceptions_1.SdkError("SUI sourceToken must contain 'originTokenAddress'");
|
|
178
|
-
}
|
|
179
|
-
txSwapParams.fromTokenAddress = sourceToken.originTokenAddress;
|
|
180
|
-
break;
|
|
181
|
-
}
|
|
182
|
-
case models_1.ChainType.ALG: {
|
|
183
|
-
txSwapParams.fromTokenAddress = sourceToken.tokenAddress;
|
|
184
|
-
break;
|
|
185
|
-
}
|
|
186
|
-
default: {
|
|
187
|
-
txSwapParams.fromTokenAddress = formatAddress(sourceToken.tokenAddress, bridgeChainType, bridgeChainType);
|
|
131
|
+
if (bridgeChainType === models_1.ChainType.SUI) {
|
|
132
|
+
if (!sourceToken.originTokenAddress) {
|
|
133
|
+
throw new exceptions_1.SdkError("SUI sourceToken must contain 'originTokenAddress'");
|
|
188
134
|
}
|
|
135
|
+
txSwapParams.fromTokenAddress = sourceToken.originTokenAddress;
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
txSwapParams.fromTokenAddress = formatAddress(sourceToken.tokenAddress, bridgeChainType, bridgeChainType);
|
|
189
139
|
}
|
|
190
140
|
txSwapParams.toAccountAddress = params.toAccountAddress;
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
throw new exceptions_1.SdkError("SUI destinationToken must contain 'originTokenAddress'");
|
|
195
|
-
}
|
|
196
|
-
txSwapParams.toTokenAddress = params.destinationToken.originTokenAddress;
|
|
197
|
-
break;
|
|
198
|
-
}
|
|
199
|
-
case models_1.ChainType.ALG: {
|
|
200
|
-
txSwapParams.toTokenAddress = params.destinationToken.tokenAddress;
|
|
201
|
-
break;
|
|
202
|
-
}
|
|
203
|
-
default: {
|
|
204
|
-
txSwapParams.toTokenAddress = formatAddress(params.destinationToken.tokenAddress, bridgeChainType, bridgeChainType);
|
|
141
|
+
if (bridgeChainType === models_1.ChainType.SUI) {
|
|
142
|
+
if (!params.destinationToken.originTokenAddress) {
|
|
143
|
+
throw new exceptions_1.SdkError("SUI destinationToken must contain 'originTokenAddress'");
|
|
205
144
|
}
|
|
145
|
+
txSwapParams.toTokenAddress = params.destinationToken.originTokenAddress;
|
|
146
|
+
}
|
|
147
|
+
else {
|
|
148
|
+
txSwapParams.toTokenAddress = formatAddress(params.destinationToken.tokenAddress, bridgeChainType, bridgeChainType);
|
|
206
149
|
}
|
|
207
150
|
txSwapParams.minimumReceiveAmount = params.minimumReceiveAmount
|
|
208
151
|
? (0, calculation_1.convertFloatAmountToInt)(params.minimumReceiveAmount, params.destinationToken.decimals).toFixed()
|
|
@@ -320,7 +263,7 @@ async function prepareTxSendParams(bridgeChainType, params, api) {
|
|
|
320
263
|
}
|
|
321
264
|
validateExtraGasNotExceeded(txSendParams.extraGas, txSendParams.gasFeePaymentMethod, extraGasLimits);
|
|
322
265
|
}
|
|
323
|
-
if (
|
|
266
|
+
if (bridgeChainType !== models_1.ChainType.SUI) {
|
|
324
267
|
txSendParams.fromTokenAddress = formatAddress(txSendParams.fromTokenAddress, bridgeChainType, bridgeChainType);
|
|
325
268
|
}
|
|
326
269
|
txSendParams.toAccountAddress = formatAddress(params.toAccountAddress, toChainType, bridgeChainType);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/services/bridge/utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,sCAiDC;AAED,0CAEC;AAED,kCAEC;AAED,oDAIC;AAED,oDAWC;AAED,sDAIC;AAED,0DAIC;AAWD,wDAcC;AAED,4BAEC;AAED,wCAMC;AAeD,kDA+CC;AA8BD,kDA8JC;AAqBD,4CAoCC;AAmBD,oDA+DC;AAED,oCAEC;AA1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AAuB,CAAC,sBAAsB;KACvE,CAAC;AACJ,CAAC;AAED,SAAgB,YAAY,CAAC,MAA+B;IAC1D,OAAO,MAAM,CAAC,WAAW,CAAC,WAAW,KAAK,MAAM,CAAC,gBAAgB,CAAC,WAAW,CAAC;AAChF,CAAC","sourcesContent":["import { PublicKey } from \"@solana/web3.js\";\nimport { Address } from \"@stellar/stellar-sdk\";\nimport algosdk, { Address as AlgoAddress } from \"algosdk\";\nimport { Big, BigSource } from \"big.js\";\nimport randomBytes from \"randombytes\";\nimport { utils as TronWebUtils } from \"tronweb\";\nimport { Chains } from \"../../chains\";\nimport { Messenger } from \"../../client/core-api/core-api.model\";\nimport { AllbridgeCoreClient } from \"../../client/core-api/core-client-base\";\nimport {\n AmountNotEnoughError,\n CCTPDoesNotSupportedError,\n ExtraGasMaxLimitExceededError,\n InvalidGasFeePaymentOptionError,\n OFTDoesNotSupportedError,\n SdkError,\n} from \"../../exceptions\";\nimport {\n AmountFormat,\n ChainType,\n ExtraGasMaxLimitResponse,\n ExtraGasMaxLimits,\n FeePaymentMethod,\n GasFeeOptions,\n SwapParams,\n} from \"../../models\";\nimport { ChainDetailsMap, TokenWithChainDetails } from \"../../tokens-info\";\nimport { convertAmountPrecision, convertFloatAmountToInt, convertIntAmountToFloat } from \"../../utils/calculation\";\nimport {\n SendParams,\n TxSendParams,\n TxSendParamsAlg,\n TxSendParamsEvm,\n TxSendParamsSol,\n TxSendParamsSrb,\n TxSendParamsSui,\n TxSendParamsTrx,\n TxSwapParams,\n TxSwapParamsEvm,\n TxSwapParamsSol,\n TxSwapParamsSrb,\n TxSwapParamsSui,\n TxSwapParamsTrx,\n} from \"./models\"; // 1. OVERLOADS\n\n// 1. OVERLOADS\nexport function formatAddress(address: string, from: ChainType, to: ChainType.EVM | ChainType.SUI): string;\nexport function formatAddress(address: string, from: ChainType, to: ChainType.TRX): Buffer;\nexport function formatAddress(address: string, from: ChainType, to: ChainType.SOLANA | ChainType.SRB): number[];\nexport function formatAddress(address: string, from: ChainType, to: ChainType): string | number[] | Buffer;\n\n// 2. COMMON Realization\nexport function formatAddress(address: string, from: ChainType, to: ChainType): string | number[] | Buffer {\n let buffer: Buffer;\n switch (from) {\n case ChainType.EVM: {\n buffer = evmAddressToBuffer32(address);\n break;\n }\n case ChainType.SOLANA: {\n buffer = new PublicKey(address).toBuffer();\n break;\n }\n case ChainType.TRX: {\n buffer = tronAddressToBuffer32(address);\n break;\n }\n case ChainType.SRB: {\n buffer = new Address(address).toBuffer();\n break;\n }\n case ChainType.SUI: {\n buffer = evmAddressToBuffer32(address);\n break;\n }\n case ChainType.ALG: {\n buffer = algAddressToBuffer32(address);\n break;\n }\n }\n\n switch (to) {\n case ChainType.EVM: {\n return \"0x\" + buffer.toString(\"hex\");\n }\n case ChainType.SOLANA: {\n return Array.from(buffer);\n }\n case ChainType.TRX: {\n return buffer;\n }\n case ChainType.SRB: {\n return buffer.toJSON().data;\n }\n case ChainType.SUI: {\n return \"0x\" + buffer.toString(\"hex\");\n }\n case ChainType.ALG: {\n return buffer;\n }\n }\n}\n\nexport function normalizeSuiHex(hex: string): string {\n return hex.replace(/^0x/i, \"\");\n}\n\nexport function hexToBuffer(hex: string): Buffer {\n return Buffer.from(hex.replace(/^0x/i, \"\"), \"hex\");\n}\n\nexport function evmAddressToBuffer32(address: string): Buffer {\n const length = 32;\n const buff = hexToBuffer(address);\n return Buffer.concat([Buffer.alloc(length - buff.length, 0), buff], length);\n}\n\nexport function algAddressToBuffer32(address: string): Buffer {\n if (algosdk.isValidAddress(address)) {\n return Buffer.from(AlgoAddress.fromString(address).publicKey);\n }\n\n if (/^\\d+$/.test(address)) {\n let hex = BigInt(address).toString(16);\n hex = hex.padStart(64, \"0\");\n return Buffer.from(hex, \"hex\");\n }\n throw new SdkError(`Unexpected Alg address: ${address}`);\n}\n\nexport function tronAddressToBuffer32(address: string): Buffer {\n const ethAddress = tronAddressToEthAddress(address);\n const buffer = hexToBuffer(ethAddress);\n return bufferToSize(buffer, 32);\n}\n\nexport function tronAddressToEthAddress(address: string): string {\n const bytes = TronWebUtils.crypto.decodeBase58Address(address);\n if (!bytes) return \"\";\n return TronWebUtils.bytes.byteArray2hexStr(bytes).replace(/^41/, \"0x\");\n}\n\nfunction bufferToSize(buffer: Buffer, size: number): Buffer {\n if (buffer.length >= size) {\n return buffer;\n }\n const result = Buffer.alloc(size, 0);\n buffer.copy(result, size - buffer.length);\n return result;\n}\n\nexport function getTokenByTokenAddress(\n chainDetailsMap: ChainDetailsMap,\n chainSymbol: string,\n tokenAddress: string\n): TokenWithChainDetails {\n const chainDetail = chainDetailsMap[chainSymbol];\n if (!chainDetail) {\n throw new SdkError(\"Cannot find chain detail for \" + chainSymbol);\n }\n const token = chainDetail.tokens.find((value) => value.tokenAddress.toUpperCase() === tokenAddress.toUpperCase());\n if (!token) {\n throw new SdkError(\"Cannot find token info about token \" + tokenAddress + \" on chain \" + chainSymbol);\n }\n return token;\n}\n\nexport function getNonce(): Buffer {\n return randomBytes(32);\n}\n\nexport function getNonceBigInt(): bigint {\n const bigint = randomBytes(32).readBigInt64BE();\n if (bigint < 0) {\n return bigint * -1n;\n }\n return bigint;\n}\n\n// 1. OVERLOADS\nexport function prepareTxSwapParams(\n bridgeChainType: ChainType.EVM | ChainType.SUI,\n params: SwapParams\n): TxSwapParamsEvm | TxSwapParamsSui;\nexport function prepareTxSwapParams(bridgeChainType: ChainType.TRX, params: SwapParams): TxSwapParamsTrx;\nexport function prepareTxSwapParams(\n bridgeChainType: ChainType.SOLANA | ChainType.SRB,\n params: SwapParams\n): TxSwapParamsSol | TxSwapParamsSrb;\nexport function prepareTxSwapParams(bridgeChainType: ChainType, params: SwapParams): TxSwapParams;\n\n// 2. COMMON Realization\nexport function prepareTxSwapParams(bridgeChainType: ChainType, params: SwapParams): TxSwapParams {\n const txSwapParams = {} as TxSwapParams;\n const sourceToken = params.sourceToken;\n txSwapParams.amount = convertFloatAmountToInt(params.amount, sourceToken.decimals).toFixed();\n txSwapParams.contractAddress = sourceToken.bridgeAddress;\n txSwapParams.fromAccountAddress = params.fromAccountAddress;\n switch (bridgeChainType) {\n case ChainType.SUI: {\n if (!sourceToken.originTokenAddress) {\n throw new SdkError(\"SUI sourceToken must contain 'originTokenAddress'\");\n }\n txSwapParams.fromTokenAddress = sourceToken.originTokenAddress;\n break;\n }\n case ChainType.ALG: {\n txSwapParams.fromTokenAddress = sourceToken.tokenAddress;\n break;\n }\n default: {\n txSwapParams.fromTokenAddress = formatAddress(sourceToken.tokenAddress, bridgeChainType, bridgeChainType);\n }\n }\n txSwapParams.toAccountAddress = params.toAccountAddress;\n switch (bridgeChainType) {\n case ChainType.SUI: {\n if (!params.destinationToken.originTokenAddress) {\n throw new SdkError(\"SUI destinationToken must contain 'originTokenAddress'\");\n }\n txSwapParams.toTokenAddress = params.destinationToken.originTokenAddress;\n break;\n }\n case ChainType.ALG: {\n txSwapParams.toTokenAddress = params.destinationToken.tokenAddress;\n break;\n }\n default: {\n txSwapParams.toTokenAddress = formatAddress(\n params.destinationToken.tokenAddress,\n bridgeChainType,\n bridgeChainType\n );\n }\n }\n txSwapParams.minimumReceiveAmount = params.minimumReceiveAmount\n ? convertFloatAmountToInt(params.minimumReceiveAmount, params.destinationToken.decimals).toFixed()\n : \"0\";\n return txSwapParams;\n}\n\n// 1. OVERLOADS\nexport function prepareTxSendParams(\n bridgeChainType: ChainType.EVM | ChainType.SUI,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParamsEvm | TxSendParamsSui>;\nexport function prepareTxSendParams(\n bridgeChainType: ChainType.TRX,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParamsTrx>;\nexport function prepareTxSendParams(\n bridgeChainType: ChainType.ALG,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParamsAlg>;\nexport function prepareTxSendParams(\n bridgeChainType: ChainType.SOLANA | ChainType.SRB,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParamsSol | TxSendParamsSrb>;\nexport function prepareTxSendParams(\n bridgeChainType: ChainType,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParams>;\n\n// 2. COMMON Realization\nexport async function prepareTxSendParams(\n bridgeChainType: ChainType,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParams> {\n const txSendParams = {} as TxSendParams;\n\n txSendParams.fromChainId = params.sourceToken.allbridgeChainId;\n txSendParams.fromChainSymbol = params.sourceToken.chainSymbol;\n const toChainType = Chains.getChainProperty(params.destinationToken.chainSymbol).chainType;\n if (bridgeChainType === ChainType.SUI) {\n if (!params.sourceToken.originTokenAddress) {\n throw new SdkError(\"SUI token must contain 'originTokenAddress'\");\n }\n txSendParams.fromTokenAddress = params.sourceToken.originTokenAddress;\n } else {\n txSendParams.fromTokenAddress = params.sourceToken.tokenAddress;\n }\n\n txSendParams.toChainId = params.destinationToken.allbridgeChainId;\n txSendParams.toTokenAddress = params.destinationToken.tokenAddress;\n\n if (params.gasFeePaymentMethod === FeePaymentMethod.WITH_STABLECOIN) {\n txSendParams.gasFeePaymentMethod = FeePaymentMethod.WITH_STABLECOIN;\n } else {\n // default FeePaymentMethod.WITH_NATIVE_CURRENCY\n txSendParams.gasFeePaymentMethod = FeePaymentMethod.WITH_NATIVE_CURRENCY;\n }\n const sourceToken = params.sourceToken;\n\n switch (params.messenger) {\n case Messenger.CCTP:\n if (!sourceToken.cctpAddress || !params.destinationToken.cctpAddress) {\n throw new CCTPDoesNotSupportedError(\"Such route does not support CCTP protocol\");\n }\n txSendParams.contractAddress = sourceToken.cctpAddress;\n break;\n case Messenger.CCTP_V2:\n if (!sourceToken.cctpV2Address || !params.destinationToken.cctpV2Address) {\n throw new CCTPDoesNotSupportedError(\"Such route does not support CCTP V2 protocol\");\n }\n txSendParams.contractAddress = sourceToken.cctpV2Address;\n\n break;\n case Messenger.OFT:\n if (\n !sourceToken.oftBridgeAddress ||\n !params.destinationToken.oftBridgeAddress ||\n sourceToken.oftId !== params.destinationToken.oftId\n ) {\n throw new OFTDoesNotSupportedError(\"Such route does not support OFT protocol\");\n }\n txSendParams.contractAddress = sourceToken.oftBridgeAddress;\n break;\n case Messenger.ALLBRIDGE:\n case Messenger.WORMHOLE:\n txSendParams.contractAddress = sourceToken.bridgeAddress;\n break;\n }\n\n txSendParams.messenger = params.messenger;\n txSendParams.fromAccountAddress = params.fromAccountAddress;\n txSendParams.amount = convertFloatAmountToInt(params.amount, sourceToken.decimals).toFixed();\n\n //Fee\n let { fee, feeFormat } = params;\n if (!fee) {\n const gasFeeOptions = await getGasFeeOptions(\n params.sourceToken,\n txSendParams.toChainId,\n txSendParams.messenger,\n api\n );\n\n const gasFeeOption = gasFeeOptions[txSendParams.gasFeePaymentMethod];\n if (!gasFeeOption) {\n throw new InvalidGasFeePaymentOptionError();\n }\n fee = gasFeeOption[AmountFormat.INT];\n feeFormat = AmountFormat.INT;\n }\n if (feeFormat == AmountFormat.FLOAT) {\n switch (txSendParams.gasFeePaymentMethod) {\n case FeePaymentMethod.WITH_NATIVE_CURRENCY:\n txSendParams.fee = convertFloatAmountToInt(fee, Chains.getChainDecimalsByType(sourceToken.chainType)).toFixed(\n 0\n );\n break;\n case FeePaymentMethod.WITH_STABLECOIN:\n txSendParams.fee = convertFloatAmountToInt(fee, sourceToken.decimals).toFixed(0);\n break;\n }\n } else {\n txSendParams.fee = fee;\n }\n\n //ExtraGas\n const { extraGas, extraGasFormat } = params;\n if (extraGas && +extraGas > 0) {\n const extraGasLimits = await getExtraGasMaxLimits(\n sourceToken,\n params.destinationToken,\n txSendParams.messenger,\n api\n );\n\n let extraGasDecimals: number;\n let extraGasDestRate: Big;\n switch (txSendParams.gasFeePaymentMethod) {\n case FeePaymentMethod.WITH_NATIVE_CURRENCY:\n extraGasDecimals = Chains.getChainDecimalsByType(sourceToken.chainType);\n extraGasDestRate = Big(extraGasLimits.exchangeRate);\n break;\n case FeePaymentMethod.WITH_STABLECOIN:\n extraGasDecimals = sourceToken.decimals;\n extraGasDestRate = Big(extraGasLimits.exchangeRate).div(extraGasLimits.sourceNativeTokenPrice);\n break;\n }\n\n switch (extraGasFormat ?? AmountFormat.INT) {\n case AmountFormat.FLOAT: {\n txSendParams.extraGas = convertFloatAmountToInt(extraGas, extraGasDecimals).toFixed(0);\n\n const extraGasDestFloat = extraGasDestRate.mul(extraGas);\n txSendParams.extraGasDest = convertFloatAmountToInt(\n extraGasDestFloat,\n Chains.getChainDecimalsByType(params.destinationToken.chainType)\n ).toFixed(0, Big.roundDown);\n break;\n }\n case AmountFormat.INT: {\n txSendParams.extraGas = extraGas;\n\n const extraGasFloat = convertIntAmountToFloat(\n txSendParams.extraGas,\n Chains.getChainDecimalsByType(sourceToken.chainType)\n );\n const extraGasDestFloat = extraGasDestRate.mul(extraGasFloat);\n txSendParams.extraGasDest = convertFloatAmountToInt(\n extraGasDestFloat,\n Chains.getChainDecimalsByType(params.destinationToken.chainType)\n ).toFixed(0, Big.roundDown);\n break;\n }\n }\n\n validateExtraGasNotExceeded(txSendParams.extraGas, txSendParams.gasFeePaymentMethod, extraGasLimits);\n }\n\n if (![ChainType.SUI, ChainType.ALG].includes(bridgeChainType)) {\n txSendParams.fromTokenAddress = formatAddress(txSendParams.fromTokenAddress, bridgeChainType, bridgeChainType);\n }\n txSendParams.toAccountAddress = formatAddress(params.toAccountAddress, toChainType, bridgeChainType);\n txSendParams.toTokenAddress = formatAddress(txSendParams.toTokenAddress, toChainType, bridgeChainType);\n if (txSendParams.gasFeePaymentMethod == FeePaymentMethod.WITH_STABLECOIN) {\n validateAmountEnough(txSendParams.amount, sourceToken.decimals, txSendParams.fee, txSendParams.extraGas);\n }\n return txSendParams;\n}\n\nfunction validateAmountEnough(\n amountInt: BigSource,\n decimals: number,\n feeInt: BigSource,\n extraGasInt: BigSource | undefined\n) {\n const amountTotal = Big(amountInt)\n .minus(feeInt)\n .minus(extraGasInt ?? 0);\n if (amountTotal.lte(0)) {\n throw new AmountNotEnoughError(\n `Amount not enough to pay fee, ${convertIntAmountToFloat(\n Big(amountTotal).minus(1).neg(),\n decimals\n ).toFixed()} stables is missing`\n );\n }\n}\n\nexport async function getGasFeeOptions(\n sourceChainToken: TokenWithChainDetails,\n destinationAllbridgeChainId: number,\n messenger: Messenger,\n api: AllbridgeCoreClient\n): Promise<GasFeeOptions> {\n const transactionCostResponse = await api.getReceiveTransactionCost({\n sourceChainId: sourceChainToken.allbridgeChainId,\n destinationChainId: destinationAllbridgeChainId,\n messenger,\n sourceToken: sourceChainToken.tokenAddress,\n });\n\n const gasFeeOptions: GasFeeOptions = {\n [FeePaymentMethod.WITH_NATIVE_CURRENCY]: {\n [AmountFormat.INT]: transactionCostResponse.fee,\n [AmountFormat.FLOAT]: convertIntAmountToFloat(\n transactionCostResponse.fee,\n Chains.getChainDecimalsByType(sourceChainToken.chainType)\n ).toFixed(),\n },\n adminFeeShareWithExtras: transactionCostResponse.adminFeeShareWithExtras,\n };\n if (transactionCostResponse.sourceNativeTokenPrice) {\n const gasFeeIntWithStables = convertAmountPrecision(\n new Big(transactionCostResponse.fee).mul(transactionCostResponse.sourceNativeTokenPrice),\n Chains.getChainDecimalsByType(sourceChainToken.chainType),\n sourceChainToken.decimals\n ).toFixed(0, Big.roundUp);\n gasFeeOptions[FeePaymentMethod.WITH_STABLECOIN] = {\n [AmountFormat.INT]: gasFeeIntWithStables,\n [AmountFormat.FLOAT]: convertIntAmountToFloat(gasFeeIntWithStables, sourceChainToken.decimals).toFixed(),\n };\n }\n\n return gasFeeOptions;\n}\n\nfunction validateExtraGasNotExceeded(\n extraGasInt: string,\n gasFeePaymentMethod: FeePaymentMethod,\n extraGasLimits: ExtraGasMaxLimitResponse\n) {\n const extraGasMaxLimit = extraGasLimits.extraGasMax[gasFeePaymentMethod];\n if (!extraGasMaxLimit) {\n throw new InvalidGasFeePaymentOptionError(`Impossible to pay extra gas by '${gasFeePaymentMethod}' payment method`);\n }\n const extraGasMaxIntLimit = extraGasMaxLimit[AmountFormat.INT];\n if (Big(extraGasInt).gt(extraGasMaxIntLimit)) {\n throw new ExtraGasMaxLimitExceededError(\n `Extra gas ${extraGasInt} in int format, exceeded limit ${extraGasMaxIntLimit} for '${gasFeePaymentMethod}' payment method`\n );\n }\n}\n\nexport async function getExtraGasMaxLimits(\n sourceChainToken: TokenWithChainDetails,\n destinationChainToken: TokenWithChainDetails,\n messenger: Messenger,\n api: AllbridgeCoreClient\n): Promise<ExtraGasMaxLimitResponse> {\n const extraGasMaxLimits: ExtraGasMaxLimits = {};\n const transactionCostResponse = await api.getReceiveTransactionCost({\n sourceChainId: sourceChainToken.allbridgeChainId,\n destinationChainId: destinationChainToken.allbridgeChainId,\n messenger,\n sourceToken: sourceChainToken.tokenAddress,\n });\n const maxAmount = destinationChainToken.txCostAmount.maxAmount;\n const maxAmountFloat = convertIntAmountToFloat(\n maxAmount,\n Chains.getChainDecimalsByType(destinationChainToken.chainType)\n ).toFixed();\n const maxAmountFloatInSourceNative = Big(maxAmountFloat)\n .div(transactionCostResponse.exchangeRate)\n .toFixed(Chains.getChainDecimalsByType(sourceChainToken.chainType), Big.roundDown);\n const maxAmountInSourceNative = convertFloatAmountToInt(\n maxAmountFloatInSourceNative,\n Chains.getChainDecimalsByType(sourceChainToken.chainType)\n ).toFixed(0);\n extraGasMaxLimits[FeePaymentMethod.WITH_NATIVE_CURRENCY] = {\n [AmountFormat.INT]: maxAmountInSourceNative,\n [AmountFormat.FLOAT]: maxAmountFloatInSourceNative,\n };\n if (transactionCostResponse.sourceNativeTokenPrice) {\n const maxAmountFloatInStable = Big(maxAmountFloatInSourceNative)\n .mul(transactionCostResponse.sourceNativeTokenPrice)\n .toFixed(sourceChainToken.decimals, Big.roundDown);\n extraGasMaxLimits[FeePaymentMethod.WITH_STABLECOIN] = {\n [AmountFormat.INT]: convertFloatAmountToInt(maxAmountFloatInStable, sourceChainToken.decimals).toFixed(0),\n [AmountFormat.FLOAT]: maxAmountFloatInStable,\n };\n }\n return {\n extraGasMax: extraGasMaxLimits,\n destinationChain: {\n gasAmountMax: {\n [AmountFormat.INT]: maxAmount,\n [AmountFormat.FLOAT]: maxAmountFloat,\n },\n swap: {\n [AmountFormat.INT]: destinationChainToken.txCostAmount.swap,\n [AmountFormat.FLOAT]: convertIntAmountToFloat(\n destinationChainToken.txCostAmount.swap,\n Chains.getChainDecimalsByType(destinationChainToken.chainType)\n ).toFixed(),\n },\n transfer: {\n [AmountFormat.INT]: destinationChainToken.txCostAmount.transfer,\n [AmountFormat.FLOAT]: convertIntAmountToFloat(\n destinationChainToken.txCostAmount.transfer,\n Chains.getChainDecimalsByType(destinationChainToken.chainType)\n ).toFixed(),\n },\n },\n exchangeRate: transactionCostResponse.exchangeRate,\n sourceNativeTokenPrice: transactionCostResponse.sourceNativeTokenPrice,\n };\n}\n\nexport function isSendParams(params: SwapParams | SendParams): params is SendParams {\n return params.sourceToken.chainSymbol !== params.destinationToken.chainSymbol;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/services/bridge/utils.ts"],"names":[],"mappings":";;;;;AAkDA,sCA0CC;AAED,0CAEC;AAED,kCAEC;AAED,oDAIC;AAED,sDAIC;AAED,0DAIC;AAWD,wDAcC;AAED,4BAEC;AAED,wCAMC;AAeD,kDA2BC;AAyBD,kDA8JC;AAqBD,4CAoCC;AAmBD,oDA+DC;AAED,oCAEC;AA3gBD,6CAA4C;AAC5C,sDAA+C;AAC/C,mCAAwC;AACxC,8DAAsC;AACtC,qCAAgD;AAChD,yCAAsC;AACtC,yEAAiE;AAEjE,iDAO0B;AAC1B,yCAQsB;AAEtB,yDAAmH;AAuBnH,wBAAwB;AACxB,SAAgB,aAAa,CAAC,OAAe,EAAE,IAAe,EAAE,EAAa;IAC3E,IAAI,MAAc,CAAC;IACnB,QAAQ,IAAI,EAAE,CAAC;QACb,KAAK,kBAAS,CAAC,GAAG,CAAC,CAAC,CAAC;YACnB,MAAM,GAAG,oBAAoB,CAAC,OAAO,CAAC,CAAC;YACvC,MAAM;QACR,CAAC;QACD,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,EAAE,iBAAiB;QAC9B,gBAAgB,EAAE;YAChB,YAAY,EAAE;gBACZ,CAAC,qBAAY,CAAC,GAAG,CAAC,EAAE,SAAS;gBAC7B,CAAC,qBAAY,CAAC,KAAK,CAAC,EAAE,cAAc;aACrC;YACD,IAAI,EAAE;gBACJ,CAAC,qBAAY,CAAC,GAAG,CAAC,EAAE,qBAAqB,CAAC,YAAY,CAAC,IAAI;gBAC3D,CAAC,qBAAY,CAAC,KAAK,CAAC,EAAE,IAAA,qCAAuB,EAC3C,qBAAqB,CAAC,YAAY,CAAC,IAAI,EACvC,eAAM,CAAC,sBAAsB,CAAC,qBAAqB,CAAC,SAAS,CAAC,CAC/D,CAAC,OAAO,EAAE;aACZ;YACD,QAAQ,EAAE;gBACR,CAAC,qBAAY,CAAC,GAAG,CAAC,EAAE,qBAAqB,CAAC,YAAY,CAAC,QAAQ;gBAC/D,CAAC,qBAAY,CAAC,KAAK,CAAC,EAAE,IAAA,qCAAuB,EAC3C,qBAAqB,CAAC,YAAY,CAAC,QAAQ,EAC3C,eAAM,CAAC,sBAAsB,CAAC,qBAAqB,CAAC,SAAS,CAAC,CAC/D,CAAC,OAAO,EAAE;aACZ;SACF;QACD,YAAY,EAAE,uBAAuB,CAAC,YAAY;QAClD,sBAAsB,EAAE,uBAAuB,CAAC,sBAAsB;KACvE,CAAC;AACJ,CAAC;AAED,SAAgB,YAAY,CAAC,MAA+B;IAC1D,OAAO,MAAM,CAAC,WAAW,CAAC,WAAW,KAAK,MAAM,CAAC,gBAAgB,CAAC,WAAW,CAAC;AAChF,CAAC","sourcesContent":["import { PublicKey } from \"@solana/web3.js\";\nimport { Address } from \"@stellar/stellar-sdk\";\nimport { Big, BigSource } from \"big.js\";\nimport randomBytes from \"randombytes\";\nimport { utils as TronWebUtils } from \"tronweb\";\nimport { Chains } from \"../../chains\";\nimport { Messenger } from \"../../client/core-api/core-api.model\";\nimport { AllbridgeCoreClient } from \"../../client/core-api/core-client-base\";\nimport {\n AmountNotEnoughError,\n CCTPDoesNotSupportedError,\n ExtraGasMaxLimitExceededError,\n InvalidGasFeePaymentOptionError,\n OFTDoesNotSupportedError,\n SdkError,\n} from \"../../exceptions\";\nimport {\n AmountFormat,\n ChainType,\n ExtraGasMaxLimitResponse,\n ExtraGasMaxLimits,\n FeePaymentMethod,\n GasFeeOptions,\n SwapParams,\n} from \"../../models\";\nimport { ChainDetailsMap, TokenWithChainDetails } from \"../../tokens-info\";\nimport { convertAmountPrecision, convertFloatAmountToInt, convertIntAmountToFloat } from \"../../utils/calculation\";\nimport {\n SendParams,\n TxSendParams,\n TxSendParamsEvm,\n TxSendParamsSol,\n TxSendParamsSrb,\n TxSendParamsSui,\n TxSendParamsTrx,\n TxSwapParams,\n TxSwapParamsEvm,\n TxSwapParamsSol,\n TxSwapParamsSrb,\n TxSwapParamsSui,\n TxSwapParamsTrx,\n} from \"./models\"; // 1. OVERLOADS\n\n// 1. OVERLOADS\nexport function formatAddress(address: string, from: ChainType, to: ChainType.EVM | ChainType.SUI): string;\nexport function formatAddress(address: string, from: ChainType, to: ChainType.TRX): Buffer;\nexport function formatAddress(address: string, from: ChainType, to: ChainType.SOLANA | ChainType.SRB): number[];\nexport function formatAddress(address: string, from: ChainType, to: ChainType): string | number[] | Buffer;\n\n// 2. COMMON Realization\nexport function formatAddress(address: string, from: ChainType, to: ChainType): string | number[] | Buffer {\n let buffer: Buffer;\n switch (from) {\n case ChainType.EVM: {\n buffer = evmAddressToBuffer32(address);\n break;\n }\n case ChainType.SOLANA: {\n buffer = new PublicKey(address).toBuffer();\n break;\n }\n case ChainType.TRX: {\n buffer = tronAddressToBuffer32(address);\n break;\n }\n case ChainType.SRB: {\n buffer = new Address(address).toBuffer();\n break;\n }\n case ChainType.SUI: {\n buffer = evmAddressToBuffer32(address);\n break;\n }\n }\n\n switch (to) {\n case ChainType.EVM: {\n return \"0x\" + buffer.toString(\"hex\");\n }\n case ChainType.SOLANA: {\n return Array.from(buffer);\n }\n case ChainType.TRX: {\n return buffer;\n }\n case ChainType.SRB: {\n return buffer.toJSON().data;\n }\n case ChainType.SUI: {\n return \"0x\" + buffer.toString(\"hex\");\n }\n }\n}\n\nexport function normalizeSuiHex(hex: string): string {\n return hex.replace(/^0x/i, \"\");\n}\n\nexport function hexToBuffer(hex: string): Buffer {\n return Buffer.from(hex.replace(/^0x/i, \"\"), \"hex\");\n}\n\nexport function evmAddressToBuffer32(address: string): Buffer {\n const length = 32;\n const buff = hexToBuffer(address);\n return Buffer.concat([Buffer.alloc(length - buff.length, 0), buff], length);\n}\n\nexport function tronAddressToBuffer32(address: string): Buffer {\n const ethAddress = tronAddressToEthAddress(address);\n const buffer = hexToBuffer(ethAddress);\n return bufferToSize(buffer, 32);\n}\n\nexport function tronAddressToEthAddress(address: string): string {\n const bytes = TronWebUtils.crypto.decodeBase58Address(address);\n if (!bytes) return \"\";\n return TronWebUtils.bytes.byteArray2hexStr(bytes).replace(/^41/, \"0x\");\n}\n\nfunction bufferToSize(buffer: Buffer, size: number): Buffer {\n if (buffer.length >= size) {\n return buffer;\n }\n const result = Buffer.alloc(size, 0);\n buffer.copy(result, size - buffer.length);\n return result;\n}\n\nexport function getTokenByTokenAddress(\n chainDetailsMap: ChainDetailsMap,\n chainSymbol: string,\n tokenAddress: string\n): TokenWithChainDetails {\n const chainDetail = chainDetailsMap[chainSymbol];\n if (!chainDetail) {\n throw new SdkError(\"Cannot find chain detail for \" + chainSymbol);\n }\n const token = chainDetail.tokens.find((value) => value.tokenAddress.toUpperCase() === tokenAddress.toUpperCase());\n if (!token) {\n throw new SdkError(\"Cannot find token info about token \" + tokenAddress + \" on chain \" + chainSymbol);\n }\n return token;\n}\n\nexport function getNonce(): Buffer {\n return randomBytes(32);\n}\n\nexport function getNonceBigInt(): bigint {\n const bigint = randomBytes(32).readBigInt64BE();\n if (bigint < 0) {\n return bigint * -1n;\n }\n return bigint;\n}\n\n// 1. OVERLOADS\nexport function prepareTxSwapParams(\n bridgeChainType: ChainType.EVM | ChainType.SUI,\n params: SwapParams\n): TxSwapParamsEvm | TxSwapParamsSui;\nexport function prepareTxSwapParams(bridgeChainType: ChainType.TRX, params: SwapParams): TxSwapParamsTrx;\nexport function prepareTxSwapParams(\n bridgeChainType: ChainType.SOLANA | ChainType.SRB,\n params: SwapParams\n): TxSwapParamsSol | TxSwapParamsSrb;\nexport function prepareTxSwapParams(bridgeChainType: ChainType, params: SwapParams): TxSwapParams;\n\n// 2. COMMON Realization\nexport function prepareTxSwapParams(bridgeChainType: ChainType, params: SwapParams): TxSwapParams {\n const txSwapParams = {} as TxSwapParams;\n const sourceToken = params.sourceToken;\n txSwapParams.amount = convertFloatAmountToInt(params.amount, sourceToken.decimals).toFixed();\n txSwapParams.contractAddress = sourceToken.bridgeAddress;\n txSwapParams.fromAccountAddress = params.fromAccountAddress;\n if (bridgeChainType === ChainType.SUI) {\n if (!sourceToken.originTokenAddress) {\n throw new SdkError(\"SUI sourceToken must contain 'originTokenAddress'\");\n }\n txSwapParams.fromTokenAddress = sourceToken.originTokenAddress;\n } else {\n txSwapParams.fromTokenAddress = formatAddress(sourceToken.tokenAddress, bridgeChainType, bridgeChainType);\n }\n txSwapParams.toAccountAddress = params.toAccountAddress;\n if (bridgeChainType === ChainType.SUI) {\n if (!params.destinationToken.originTokenAddress) {\n throw new SdkError(\"SUI destinationToken must contain 'originTokenAddress'\");\n }\n txSwapParams.toTokenAddress = params.destinationToken.originTokenAddress;\n } else {\n txSwapParams.toTokenAddress = formatAddress(params.destinationToken.tokenAddress, bridgeChainType, bridgeChainType);\n }\n txSwapParams.minimumReceiveAmount = params.minimumReceiveAmount\n ? convertFloatAmountToInt(params.minimumReceiveAmount, params.destinationToken.decimals).toFixed()\n : \"0\";\n return txSwapParams;\n}\n\n// 1. OVERLOADS\nexport function prepareTxSendParams(\n bridgeChainType: ChainType.EVM | ChainType.SUI,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParamsEvm | TxSendParamsSui>;\nexport function prepareTxSendParams(\n bridgeChainType: ChainType.TRX,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParamsTrx>;\nexport function prepareTxSendParams(\n bridgeChainType: ChainType.SOLANA | ChainType.SRB,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParamsSol | TxSendParamsSrb>;\nexport function prepareTxSendParams(\n bridgeChainType: ChainType,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParams>;\n\n// 2. COMMON Realization\nexport async function prepareTxSendParams(\n bridgeChainType: ChainType,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParams> {\n const txSendParams = {} as TxSendParams;\n\n txSendParams.fromChainId = params.sourceToken.allbridgeChainId;\n txSendParams.fromChainSymbol = params.sourceToken.chainSymbol;\n const toChainType = Chains.getChainProperty(params.destinationToken.chainSymbol).chainType;\n if (bridgeChainType === ChainType.SUI) {\n if (!params.sourceToken.originTokenAddress) {\n throw new SdkError(\"SUI token must contain 'originTokenAddress'\");\n }\n txSendParams.fromTokenAddress = params.sourceToken.originTokenAddress;\n } else {\n txSendParams.fromTokenAddress = params.sourceToken.tokenAddress;\n }\n\n txSendParams.toChainId = params.destinationToken.allbridgeChainId;\n txSendParams.toTokenAddress = params.destinationToken.tokenAddress;\n\n if (params.gasFeePaymentMethod === FeePaymentMethod.WITH_STABLECOIN) {\n txSendParams.gasFeePaymentMethod = FeePaymentMethod.WITH_STABLECOIN;\n } else {\n // default FeePaymentMethod.WITH_NATIVE_CURRENCY\n txSendParams.gasFeePaymentMethod = FeePaymentMethod.WITH_NATIVE_CURRENCY;\n }\n const sourceToken = params.sourceToken;\n\n switch (params.messenger) {\n case Messenger.CCTP:\n if (!sourceToken.cctpAddress || !params.destinationToken.cctpAddress) {\n throw new CCTPDoesNotSupportedError(\"Such route does not support CCTP protocol\");\n }\n txSendParams.contractAddress = sourceToken.cctpAddress;\n break;\n case Messenger.CCTP_V2:\n if (!sourceToken.cctpV2Address || !params.destinationToken.cctpV2Address) {\n throw new CCTPDoesNotSupportedError(\"Such route does not support CCTP V2 protocol\");\n }\n txSendParams.contractAddress = sourceToken.cctpV2Address;\n\n break;\n case Messenger.OFT:\n if (\n !sourceToken.oftBridgeAddress ||\n !params.destinationToken.oftBridgeAddress ||\n sourceToken.oftId !== params.destinationToken.oftId\n ) {\n throw new OFTDoesNotSupportedError(\"Such route does not support OFT protocol\");\n }\n txSendParams.contractAddress = sourceToken.oftBridgeAddress;\n break;\n case Messenger.ALLBRIDGE:\n case Messenger.WORMHOLE:\n txSendParams.contractAddress = sourceToken.bridgeAddress;\n break;\n }\n\n txSendParams.messenger = params.messenger;\n txSendParams.fromAccountAddress = params.fromAccountAddress;\n txSendParams.amount = convertFloatAmountToInt(params.amount, sourceToken.decimals).toFixed();\n\n //Fee\n let { fee, feeFormat } = params;\n if (!fee) {\n const gasFeeOptions = await getGasFeeOptions(\n params.sourceToken,\n txSendParams.toChainId,\n txSendParams.messenger,\n api\n );\n\n const gasFeeOption = gasFeeOptions[txSendParams.gasFeePaymentMethod];\n if (!gasFeeOption) {\n throw new InvalidGasFeePaymentOptionError();\n }\n fee = gasFeeOption[AmountFormat.INT];\n feeFormat = AmountFormat.INT;\n }\n if (feeFormat == AmountFormat.FLOAT) {\n switch (txSendParams.gasFeePaymentMethod) {\n case FeePaymentMethod.WITH_NATIVE_CURRENCY:\n txSendParams.fee = convertFloatAmountToInt(fee, Chains.getChainDecimalsByType(sourceToken.chainType)).toFixed(\n 0\n );\n break;\n case FeePaymentMethod.WITH_STABLECOIN:\n txSendParams.fee = convertFloatAmountToInt(fee, sourceToken.decimals).toFixed(0);\n break;\n }\n } else {\n txSendParams.fee = fee;\n }\n\n //ExtraGas\n const { extraGas, extraGasFormat } = params;\n if (extraGas && +extraGas > 0) {\n const extraGasLimits = await getExtraGasMaxLimits(\n sourceToken,\n params.destinationToken,\n txSendParams.messenger,\n api\n );\n\n let extraGasDecimals: number;\n let extraGasDestRate: Big;\n switch (txSendParams.gasFeePaymentMethod) {\n case FeePaymentMethod.WITH_NATIVE_CURRENCY:\n extraGasDecimals = Chains.getChainDecimalsByType(sourceToken.chainType);\n extraGasDestRate = Big(extraGasLimits.exchangeRate);\n break;\n case FeePaymentMethod.WITH_STABLECOIN:\n extraGasDecimals = sourceToken.decimals;\n extraGasDestRate = Big(extraGasLimits.exchangeRate).div(extraGasLimits.sourceNativeTokenPrice);\n break;\n }\n\n switch (extraGasFormat ?? AmountFormat.INT) {\n case AmountFormat.FLOAT: {\n txSendParams.extraGas = convertFloatAmountToInt(extraGas, extraGasDecimals).toFixed(0);\n\n const extraGasDestFloat = extraGasDestRate.mul(extraGas);\n txSendParams.extraGasDest = convertFloatAmountToInt(\n extraGasDestFloat,\n Chains.getChainDecimalsByType(params.destinationToken.chainType)\n ).toFixed(0, Big.roundDown);\n break;\n }\n case AmountFormat.INT: {\n txSendParams.extraGas = extraGas;\n\n const extraGasFloat = convertIntAmountToFloat(\n txSendParams.extraGas,\n Chains.getChainDecimalsByType(sourceToken.chainType)\n );\n const extraGasDestFloat = extraGasDestRate.mul(extraGasFloat);\n txSendParams.extraGasDest = convertFloatAmountToInt(\n extraGasDestFloat,\n Chains.getChainDecimalsByType(params.destinationToken.chainType)\n ).toFixed(0, Big.roundDown);\n break;\n }\n }\n\n validateExtraGasNotExceeded(txSendParams.extraGas, txSendParams.gasFeePaymentMethod, extraGasLimits);\n }\n\n if (bridgeChainType !== ChainType.SUI) {\n txSendParams.fromTokenAddress = formatAddress(txSendParams.fromTokenAddress, bridgeChainType, bridgeChainType);\n }\n txSendParams.toAccountAddress = formatAddress(params.toAccountAddress, toChainType, bridgeChainType);\n txSendParams.toTokenAddress = formatAddress(txSendParams.toTokenAddress, toChainType, bridgeChainType);\n if (txSendParams.gasFeePaymentMethod == FeePaymentMethod.WITH_STABLECOIN) {\n validateAmountEnough(txSendParams.amount, sourceToken.decimals, txSendParams.fee, txSendParams.extraGas);\n }\n return txSendParams;\n}\n\nfunction validateAmountEnough(\n amountInt: BigSource,\n decimals: number,\n feeInt: BigSource,\n extraGasInt: BigSource | undefined\n) {\n const amountTotal = Big(amountInt)\n .minus(feeInt)\n .minus(extraGasInt ?? 0);\n if (amountTotal.lte(0)) {\n throw new AmountNotEnoughError(\n `Amount not enough to pay fee, ${convertIntAmountToFloat(\n Big(amountTotal).minus(1).neg(),\n decimals\n ).toFixed()} stables is missing`\n );\n }\n}\n\nexport async function getGasFeeOptions(\n sourceChainToken: TokenWithChainDetails,\n destinationAllbridgeChainId: number,\n messenger: Messenger,\n api: AllbridgeCoreClient\n): Promise<GasFeeOptions> {\n const transactionCostResponse = await api.getReceiveTransactionCost({\n sourceChainId: sourceChainToken.allbridgeChainId,\n destinationChainId: destinationAllbridgeChainId,\n messenger,\n sourceToken: sourceChainToken.tokenAddress,\n });\n\n const gasFeeOptions: GasFeeOptions = {\n [FeePaymentMethod.WITH_NATIVE_CURRENCY]: {\n [AmountFormat.INT]: transactionCostResponse.fee,\n [AmountFormat.FLOAT]: convertIntAmountToFloat(\n transactionCostResponse.fee,\n Chains.getChainDecimalsByType(sourceChainToken.chainType)\n ).toFixed(),\n },\n adminFeeShareWithExtras: transactionCostResponse.adminFeeShareWithExtras,\n };\n if (transactionCostResponse.sourceNativeTokenPrice) {\n const gasFeeIntWithStables = convertAmountPrecision(\n new Big(transactionCostResponse.fee).mul(transactionCostResponse.sourceNativeTokenPrice),\n Chains.getChainDecimalsByType(sourceChainToken.chainType),\n sourceChainToken.decimals\n ).toFixed(0, Big.roundUp);\n gasFeeOptions[FeePaymentMethod.WITH_STABLECOIN] = {\n [AmountFormat.INT]: gasFeeIntWithStables,\n [AmountFormat.FLOAT]: convertIntAmountToFloat(gasFeeIntWithStables, sourceChainToken.decimals).toFixed(),\n };\n }\n\n return gasFeeOptions;\n}\n\nfunction validateExtraGasNotExceeded(\n extraGasInt: string,\n gasFeePaymentMethod: FeePaymentMethod,\n extraGasLimits: ExtraGasMaxLimitResponse\n) {\n const extraGasMaxLimit = extraGasLimits.extraGasMax[gasFeePaymentMethod];\n if (!extraGasMaxLimit) {\n throw new InvalidGasFeePaymentOptionError(`Impossible to pay extra gas by '${gasFeePaymentMethod}' payment method`);\n }\n const extraGasMaxIntLimit = extraGasMaxLimit[AmountFormat.INT];\n if (Big(extraGasInt).gt(extraGasMaxIntLimit)) {\n throw new ExtraGasMaxLimitExceededError(\n `Extra gas ${extraGasInt} in int format, exceeded limit ${extraGasMaxIntLimit} for '${gasFeePaymentMethod}' payment method`\n );\n }\n}\n\nexport async function getExtraGasMaxLimits(\n sourceChainToken: TokenWithChainDetails,\n destinationChainToken: TokenWithChainDetails,\n messenger: Messenger,\n api: AllbridgeCoreClient\n): Promise<ExtraGasMaxLimitResponse> {\n const extraGasMaxLimits: ExtraGasMaxLimits = {};\n const transactionCostResponse = await api.getReceiveTransactionCost({\n sourceChainId: sourceChainToken.allbridgeChainId,\n destinationChainId: destinationChainToken.allbridgeChainId,\n messenger,\n sourceToken: sourceChainToken.tokenAddress,\n });\n const maxAmount = destinationChainToken.txCostAmount.maxAmount;\n const maxAmountFloat = convertIntAmountToFloat(\n maxAmount,\n Chains.getChainDecimalsByType(destinationChainToken.chainType)\n ).toFixed();\n const maxAmountFloatInSourceNative = Big(maxAmountFloat)\n .div(transactionCostResponse.exchangeRate)\n .toFixed(Chains.getChainDecimalsByType(sourceChainToken.chainType), Big.roundDown);\n const maxAmountInSourceNative = convertFloatAmountToInt(\n maxAmountFloatInSourceNative,\n Chains.getChainDecimalsByType(sourceChainToken.chainType)\n ).toFixed(0);\n extraGasMaxLimits[FeePaymentMethod.WITH_NATIVE_CURRENCY] = {\n [AmountFormat.INT]: maxAmountInSourceNative,\n [AmountFormat.FLOAT]: maxAmountFloatInSourceNative,\n };\n if (transactionCostResponse.sourceNativeTokenPrice) {\n const maxAmountFloatInStable = Big(maxAmountFloatInSourceNative)\n .mul(transactionCostResponse.sourceNativeTokenPrice)\n .toFixed(sourceChainToken.decimals, Big.roundDown);\n extraGasMaxLimits[FeePaymentMethod.WITH_STABLECOIN] = {\n [AmountFormat.INT]: convertFloatAmountToInt(maxAmountFloatInStable, sourceChainToken.decimals).toFixed(0),\n [AmountFormat.FLOAT]: maxAmountFloatInStable,\n };\n }\n return {\n extraGasMax: extraGasMaxLimits,\n destinationChain: {\n gasAmountMax: {\n [AmountFormat.INT]: maxAmount,\n [AmountFormat.FLOAT]: maxAmountFloat,\n },\n swap: {\n [AmountFormat.INT]: destinationChainToken.txCostAmount.swap,\n [AmountFormat.FLOAT]: convertIntAmountToFloat(\n destinationChainToken.txCostAmount.swap,\n Chains.getChainDecimalsByType(destinationChainToken.chainType)\n ).toFixed(),\n },\n transfer: {\n [AmountFormat.INT]: destinationChainToken.txCostAmount.transfer,\n [AmountFormat.FLOAT]: convertIntAmountToFloat(\n destinationChainToken.txCostAmount.transfer,\n Chains.getChainDecimalsByType(destinationChainToken.chainType)\n ).toFixed(),\n },\n },\n exchangeRate: transactionCostResponse.exchangeRate,\n sourceNativeTokenPrice: transactionCostResponse.sourceNativeTokenPrice,\n };\n}\n\nexport function isSendParams(params: SwapParams | SendParams): params is SendParams {\n return params.sourceToken.chainSymbol !== params.destinationToken.chainSymbol;\n}\n"]}
|
|
@@ -5,7 +5,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.DefaultLiquidityPoolService = void 0;
|
|
7
7
|
exports.getChainPoolService = getChainPoolService;
|
|
8
|
-
const algokit_utils_1 = require("@algorandfoundation/algokit-utils");
|
|
9
8
|
const big_js_1 = require("big.js");
|
|
10
9
|
const timed_cache_1 = __importDefault(require("timed-cache"));
|
|
11
10
|
const tronweb_1 = require("tronweb");
|
|
@@ -16,7 +15,6 @@ const calculation_1 = require("../../utils/calculation");
|
|
|
16
15
|
const constants_1 = require("../../utils/calculation/constants");
|
|
17
16
|
const utils_1 = require("../../utils/utils");
|
|
18
17
|
const calculation_2 = require("../utils/calculation");
|
|
19
|
-
const alg_1 = require("./alg");
|
|
20
18
|
const evm_1 = require("./evm");
|
|
21
19
|
const raw_pool_transaction_builder_1 = require("./raw-pool-transaction-builder");
|
|
22
20
|
const sol_1 = require("./sol");
|
|
@@ -135,20 +133,6 @@ function getChainPoolService(chainSymbol, api, nodeRpcUrlsConfig, params, provid
|
|
|
135
133
|
case index_1.ChainType.SUI: {
|
|
136
134
|
return new sui_1.SuiPoolService(nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol), api);
|
|
137
135
|
}
|
|
138
|
-
case index_1.ChainType.ALG: {
|
|
139
|
-
if (provider) {
|
|
140
|
-
const algod = provider;
|
|
141
|
-
const algorand = algokit_utils_1.AlgorandClient.fromClients({ algod });
|
|
142
|
-
return new alg_1.AlgPoolService(algorand, api);
|
|
143
|
-
}
|
|
144
|
-
else {
|
|
145
|
-
const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);
|
|
146
|
-
const algorand = algokit_utils_1.AlgorandClient.fromConfig({
|
|
147
|
-
algodConfig: { server: nodeRpcUrl },
|
|
148
|
-
});
|
|
149
|
-
return new alg_1.AlgPoolService(algorand, api);
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
136
|
}
|
|
153
137
|
}
|
|
154
138
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/services/liquidity-pool/index.ts"],"names":[],"mappings":";;;;;;AA0NA,kDAoDC;AA9QD,qEAAmE;AAEnE,mCAA6B;AAC7B,8DAAgC;AAChC,qCAAkC;AAClC,+BAAmD;AAEnD,yCAAsC;AAGtC,uCAAgF;AAEhF,yDAAuF;AACvF,iEAAqE;AACrE,6CAAiF;AAGjF,sDAAmF;AACnF,+BAAuC;AACvC,+BAAuC;AAEvC,iFAA6G;AAC7G,+BAA0C;AAC1C,+BAAuC;AACvC,+BAAuC;AACvC,+BAAwC;AA4FxC,MAAa,2BAA2B;IAK5B;IACA;IACA;IACA;IAP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CAAC,CAAC;gBACvD,OAAO,IAAI,oBAAc,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;YAC3C,CAAC;iBAAM,CAAC;gBACN,MAAM,UAAU,GAAG,iBAAiB,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;gBAChE,MAAM,QAAQ,GAAG,8BAAc,CAAC,UAAU,CAAC;oBACzC,WAAW,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE;iBACpC,CAAC,CAAC;gBACH,OAAO,IAAI,oBAAc,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;YAC3C,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { AlgorandClient } from \"@algorandfoundation/algokit-utils\";\nimport { Algodv2 } from \"algosdk\";\nimport { Big } from \"big.js\";\nimport Cache from \"timed-cache\";\nimport { TronWeb } from \"tronweb\";\nimport { FMT_BYTES, FMT_NUMBER, Web3 } from \"web3\";\nimport { NodeRpcUrlsConfig } from \"..\";\nimport { Chains } from \"../../chains\";\nimport { AllbridgeCoreClient } from \"../../client/core-api/core-client-base\";\nimport { AllbridgeCoreClientFiltered } from \"../../client/core-api/core-client-filtered\";\nimport { AllbridgeCoreSdkOptions, ChainType, EssentialWeb3 } from \"../../index\";\nimport { PoolInfo, PoolKeyObject, TokenWithChainDetails } from \"../../tokens-info\";\nimport { convertIntAmountToFloat, fromSystemPrecision } from \"../../utils/calculation\";\nimport { SYSTEM_PRECISION } from \"../../utils/calculation/constants\";\nimport { validateAmountDecimals, validateAmountGtZero } from \"../../utils/utils\";\nimport { Provider, TransactionResponse } from \"../models\";\nimport { TokenService } from \"../token\";\nimport { depositAmountToVUsd, vUsdToWithdrawalAmount } from \"../utils/calculation\";\nimport { AlgPoolService } from \"./alg\";\nimport { EvmPoolService } from \"./evm\";\nimport { ApproveParams, ChainPoolService, CheckAllowanceParams, GetAllowanceParams, UserBalanceInfo } from \"./models\";\nimport { DefaultRawPoolTransactionBuilder, RawPoolTransactionBuilder } from \"./raw-pool-transaction-builder\";\nimport { SolanaPoolService } from \"./sol\";\nimport { SrbPoolService } from \"./srb\";\nimport { SuiPoolService } from \"./sui\";\nimport { TronPoolService } from \"./trx\";\n\nexport interface LiquidityPoolService {\n rawTxBuilder: RawPoolTransactionBuilder;\n\n /**\n * Get amount of tokens approved for poolInfo\n * @param provider - will be used to access the network\n * @param params See {@link GetAllowanceParams}\n * @returns the amount of approved tokens\n */\n getAllowance(provider: Provider, params: GetAllowanceParams): Promise<string>;\n\n /**\n * Get amount of tokens approved for poolInfo\n * @param params See {@link GetAllowanceParams}\n * @returns the amount of approved tokens\n */\n getAllowance(params: GetAllowanceParams): Promise<string>;\n\n /**\n * Check if the amount of approved tokens is enough\n * @param provider - will be used to access the network\n * @param params See {@link CheckAllowanceParams}\n * @returns true if the amount of approved tokens is enough to make a transfer\n */\n checkAllowance(provider: Provider, params: CheckAllowanceParams): Promise<boolean>;\n\n /**\n * Check if the amount of approved tokens is enough\n * @param params See {@link CheckAllowanceParams}\n * @returns true if the amount of approved tokens is enough to make a transfer\n */\n checkAllowance(params: CheckAllowanceParams): Promise<boolean>;\n\n /**\n * @deprecated Use {@link rawTxBuilder}.{@link RawPoolTransactionBuilder.approve}<p>\n * Approve tokens usage by another address on chains\n * <p>\n * For ETH/USDT: due to specificity of the USDT contract:<br/>\n * If the current allowance is not 0, this function will perform an additional transaction to set allowance to 0 before setting the new allowance value.\n * @param provider - will be used to access the network\n * @param approveData\n */\n approve(provider: Provider, approveData: ApproveParams): Promise<TransactionResponse>;\n\n /**\n * Calculates the amount of LP tokens that will be deposited\n * @param amount The float amount of tokens that will be sent\n * @param token\n * @param provider - will be used to access the network\n * @returns amount\n */\n getAmountToBeDeposited(amount: string, token: TokenWithChainDetails, provider?: Provider): Promise<string>;\n\n /**\n * Calculates the amount of tokens will be withdrawn\n * @param amount The float amount of tokens that will be sent\n * @param accountAddress\n * @param token\n * @param provider - will be used to access the network\n * @returns amount\n */\n getAmountToBeWithdrawn(\n amount: string,\n accountAddress: string,\n token: TokenWithChainDetails,\n provider?: Provider\n ): Promise<string>;\n\n /**\n * Get User Balance Info on Liquidity poolInfo\n * @param accountAddress\n * @param token\n * @param provider\n * @returns UserBalanceInfo\n */\n getUserBalanceInfo(\n accountAddress: string,\n token: TokenWithChainDetails,\n provider?: Provider\n ): Promise<UserBalanceInfo>;\n\n /**\n * Gets information about the poolInfo from chain\n * @param token\n * @param provider - will be used to access the network\n * @returns poolInfo\n */\n getPoolInfoFromChain(token: TokenWithChainDetails, provider?: Provider): Promise<Required<PoolInfo>>;\n}\n\nexport class DefaultLiquidityPoolService implements LiquidityPoolService {\n public rawTxBuilder: RawPoolTransactionBuilder;\n private cache: Cache<PoolInfo>;\n\n constructor(\n private api: AllbridgeCoreClientFiltered,\n private nodeRpcUrlsConfig: NodeRpcUrlsConfig,\n private params: AllbridgeCoreSdkOptions,\n private tokenService: TokenService\n ) {\n this.rawTxBuilder = new DefaultRawPoolTransactionBuilder(api, nodeRpcUrlsConfig, this.params, tokenService);\n const ttl = params.cachePoolInfoChainSec > 0 ? params.cachePoolInfoChainSec * 1000 : 20 * 1000;\n this.cache = new Cache<PoolInfo>({ defaultTtl: ttl });\n }\n\n async getAllowance(a: Provider | GetAllowanceParams, b?: GetAllowanceParams): Promise<string> {\n if (b) {\n const provider = a as Provider;\n const params = b;\n return await this.tokenService.getAllowance({ ...params, spender: params.token.poolAddress }, provider);\n } else {\n const params = a as GetAllowanceParams;\n return await this.tokenService.getAllowance({ ...params, spender: params.token.poolAddress });\n }\n }\n\n async checkAllowance(a: Provider | CheckAllowanceParams, b?: CheckAllowanceParams): Promise<boolean> {\n if (b) {\n const provider = a as Provider;\n const params = b;\n return this.tokenService.checkAllowance({ ...params, spender: params.token.poolAddress }, provider);\n } else {\n const params = a as CheckAllowanceParams;\n return this.tokenService.checkAllowance({ ...params, spender: params.token.poolAddress });\n }\n }\n\n async approve(provider: Provider, approveData: ApproveParams): Promise<TransactionResponse> {\n return this.tokenService.approve(provider, { ...approveData, spender: approveData.token.poolAddress });\n }\n\n async getAmountToBeDeposited(amount: string, token: TokenWithChainDetails, provider?: Provider): Promise<string> {\n validateAmountGtZero(amount);\n validateAmountDecimals(\"amount\", amount, token.decimals);\n const pool = await this.getPoolInfoFromChain(token, provider);\n const { vUsdBalance, tokenBalance, aValue, dValue } = pool;\n const vUsd = depositAmountToVUsd(amount, aValue, dValue, tokenBalance, vUsdBalance);\n return convertIntAmountToFloat(vUsd, SYSTEM_PRECISION).toFixed();\n }\n\n async getAmountToBeWithdrawn(\n amount: string,\n accountAddress: string,\n token: TokenWithChainDetails,\n provider?: Provider\n ): Promise<string> {\n validateAmountGtZero(amount);\n validateAmountDecimals(\"amount\", amount, token.decimals);\n const pool = await this.getPoolInfoFromChain(token, provider);\n const tokenAmountInSP = vUsdToWithdrawalAmount(amount);\n const tokenAmount = fromSystemPrecision(tokenAmountInSP, token.decimals);\n const userBalanceInfo = await this.getUserBalanceInfo(accountAddress, token, provider);\n const earned = userBalanceInfo.earned(pool) || \"0\";\n const commonAmount = Big(tokenAmount).plus(earned).toFixed();\n return convertIntAmountToFloat(commonAmount, token.decimals).toFixed();\n }\n\n async getUserBalanceInfo(\n accountAddress: string,\n token: TokenWithChainDetails,\n provider?: Provider\n ): Promise<UserBalanceInfo> {\n return getChainPoolService(\n token.chainSymbol,\n this.api,\n this.nodeRpcUrlsConfig,\n this.params,\n provider\n ).getUserBalanceInfo(accountAddress, token);\n }\n\n async getPoolInfoFromChain(token: TokenWithChainDetails, provider?: Provider): Promise<PoolInfo> {\n const poolKey: PoolKeyObject = { chainSymbol: token.chainSymbol, poolAddress: token.poolAddress };\n const fromCache = this.cache.get(poolKey);\n if (fromCache) {\n return fromCache;\n } else {\n const poolInfo = await getChainPoolService(\n token.chainSymbol,\n this.api,\n this.nodeRpcUrlsConfig,\n this.params,\n provider\n ).getPoolInfoFromChain(token);\n this.cache.put(poolKey, poolInfo);\n this.api.cachePut({ chainSymbol: token.chainSymbol, poolAddress: token.poolAddress }, poolInfo);\n return poolInfo;\n }\n }\n}\n\nexport function getChainPoolService(\n chainSymbol: string,\n api: AllbridgeCoreClient,\n nodeRpcUrlsConfig: NodeRpcUrlsConfig,\n params: AllbridgeCoreSdkOptions,\n provider?: Provider\n): ChainPoolService {\n switch (Chains.getChainProperty(chainSymbol).chainType) {\n case ChainType.EVM: {\n if (provider) {\n return new EvmPoolService(provider as EssentialWeb3, api);\n } else {\n const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);\n const web3 = new Web3(nodeRpcUrl);\n web3.defaultReturnFormat = { number: FMT_NUMBER.STR, bytes: FMT_BYTES.HEX };\n return new EvmPoolService(web3, api);\n }\n }\n case ChainType.TRX: {\n const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);\n const tronJsonRpc = params.tronJsonRpc;\n if (provider) {\n return new TronPoolService(provider as TronWeb, api, tronJsonRpc);\n } else {\n const tronWeb = new TronWeb({ fullHost: nodeRpcUrl });\n return new TronPoolService(tronWeb, api, tronJsonRpc);\n }\n }\n case ChainType.SOLANA: {\n const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);\n return new SolanaPoolService(nodeRpcUrl, api);\n }\n case ChainType.SRB: {\n return new SrbPoolService(nodeRpcUrlsConfig, params, api);\n }\n case ChainType.SUI: {\n return new SuiPoolService(nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol), api);\n }\n case ChainType.ALG: {\n if (provider) {\n const algod = provider as Algodv2;\n const algorand = AlgorandClient.fromClients({ algod });\n return new AlgPoolService(algorand, api);\n } else {\n const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);\n const algorand = AlgorandClient.fromConfig({\n algodConfig: { server: nodeRpcUrl },\n });\n return new AlgPoolService(algorand, api);\n }\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/services/liquidity-pool/index.ts"],"names":[],"mappings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G,CAAC,CAAC,CAAC;YACnB,OAAO,IAAI,oBAAc,CAAC,iBAAiB,CAAC,aAAa,CAAC,WAAW,CAAC,EAAE,GAAG,CAAC,CAAC;QAC/E,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { Big } from \"big.js\";\nimport Cache from \"timed-cache\";\nimport { TronWeb } from \"tronweb\";\nimport { FMT_BYTES, FMT_NUMBER, Web3 } from \"web3\";\nimport { NodeRpcUrlsConfig } from \"..\";\nimport { Chains } from \"../../chains\";\nimport { AllbridgeCoreClient } from \"../../client/core-api/core-client-base\";\nimport { AllbridgeCoreClientFiltered } from \"../../client/core-api/core-client-filtered\";\nimport { AllbridgeCoreSdkOptions, ChainType, EssentialWeb3 } from \"../../index\";\nimport { PoolInfo, PoolKeyObject, TokenWithChainDetails } from \"../../tokens-info\";\nimport { convertIntAmountToFloat, fromSystemPrecision } from \"../../utils/calculation\";\nimport { SYSTEM_PRECISION } from \"../../utils/calculation/constants\";\nimport { validateAmountDecimals, validateAmountGtZero } from \"../../utils/utils\";\nimport { Provider, TransactionResponse } from \"../models\";\nimport { TokenService } from \"../token\";\nimport { depositAmountToVUsd, vUsdToWithdrawalAmount } from \"../utils/calculation\";\nimport { EvmPoolService } from \"./evm\";\nimport { ApproveParams, ChainPoolService, CheckAllowanceParams, GetAllowanceParams, UserBalanceInfo } from \"./models\";\nimport { DefaultRawPoolTransactionBuilder, RawPoolTransactionBuilder } from \"./raw-pool-transaction-builder\";\nimport { SolanaPoolService } from \"./sol\";\nimport { SrbPoolService } from \"./srb\";\nimport { SuiPoolService } from \"./sui\";\nimport { TronPoolService } from \"./trx\";\n\nexport interface LiquidityPoolService {\n rawTxBuilder: RawPoolTransactionBuilder;\n\n /**\n * Get amount of tokens approved for poolInfo\n * @param provider - will be used to access the network\n * @param params See {@link GetAllowanceParams}\n * @returns the amount of approved tokens\n */\n getAllowance(provider: Provider, params: GetAllowanceParams): Promise<string>;\n\n /**\n * Get amount of tokens approved for poolInfo\n * @param params See {@link GetAllowanceParams}\n * @returns the amount of approved tokens\n */\n getAllowance(params: GetAllowanceParams): Promise<string>;\n\n /**\n * Check if the amount of approved tokens is enough\n * @param provider - will be used to access the network\n * @param params See {@link CheckAllowanceParams}\n * @returns true if the amount of approved tokens is enough to make a transfer\n */\n checkAllowance(provider: Provider, params: CheckAllowanceParams): Promise<boolean>;\n\n /**\n * Check if the amount of approved tokens is enough\n * @param params See {@link CheckAllowanceParams}\n * @returns true if the amount of approved tokens is enough to make a transfer\n */\n checkAllowance(params: CheckAllowanceParams): Promise<boolean>;\n\n /**\n * @deprecated Use {@link rawTxBuilder}.{@link RawPoolTransactionBuilder.approve}<p>\n * Approve tokens usage by another address on chains\n * <p>\n * For ETH/USDT: due to specificity of the USDT contract:<br/>\n * If the current allowance is not 0, this function will perform an additional transaction to set allowance to 0 before setting the new allowance value.\n * @param provider - will be used to access the network\n * @param approveData\n */\n approve(provider: Provider, approveData: ApproveParams): Promise<TransactionResponse>;\n\n /**\n * Calculates the amount of LP tokens that will be deposited\n * @param amount The float amount of tokens that will be sent\n * @param token\n * @param provider - will be used to access the network\n * @returns amount\n */\n getAmountToBeDeposited(amount: string, token: TokenWithChainDetails, provider?: Provider): Promise<string>;\n\n /**\n * Calculates the amount of tokens will be withdrawn\n * @param amount The float amount of tokens that will be sent\n * @param accountAddress\n * @param token\n * @param provider - will be used to access the network\n * @returns amount\n */\n getAmountToBeWithdrawn(\n amount: string,\n accountAddress: string,\n token: TokenWithChainDetails,\n provider?: Provider\n ): Promise<string>;\n\n /**\n * Get User Balance Info on Liquidity poolInfo\n * @param accountAddress\n * @param token\n * @param provider\n * @returns UserBalanceInfo\n */\n getUserBalanceInfo(\n accountAddress: string,\n token: TokenWithChainDetails,\n provider?: Provider\n ): Promise<UserBalanceInfo>;\n\n /**\n * Gets information about the poolInfo from chain\n * @param token\n * @param provider - will be used to access the network\n * @returns poolInfo\n */\n getPoolInfoFromChain(token: TokenWithChainDetails, provider?: Provider): Promise<Required<PoolInfo>>;\n}\n\nexport class DefaultLiquidityPoolService implements LiquidityPoolService {\n public rawTxBuilder: RawPoolTransactionBuilder;\n private cache: Cache<PoolInfo>;\n\n constructor(\n private api: AllbridgeCoreClientFiltered,\n private nodeRpcUrlsConfig: NodeRpcUrlsConfig,\n private params: AllbridgeCoreSdkOptions,\n private tokenService: TokenService\n ) {\n this.rawTxBuilder = new DefaultRawPoolTransactionBuilder(api, nodeRpcUrlsConfig, this.params, tokenService);\n const ttl = params.cachePoolInfoChainSec > 0 ? params.cachePoolInfoChainSec * 1000 : 20 * 1000;\n this.cache = new Cache<PoolInfo>({ defaultTtl: ttl });\n }\n\n async getAllowance(a: Provider | GetAllowanceParams, b?: GetAllowanceParams): Promise<string> {\n if (b) {\n const provider = a as Provider;\n const params = b;\n return await this.tokenService.getAllowance({ ...params, spender: params.token.poolAddress }, provider);\n } else {\n const params = a as GetAllowanceParams;\n return await this.tokenService.getAllowance({ ...params, spender: params.token.poolAddress });\n }\n }\n\n async checkAllowance(a: Provider | CheckAllowanceParams, b?: CheckAllowanceParams): Promise<boolean> {\n if (b) {\n const provider = a as Provider;\n const params = b;\n return this.tokenService.checkAllowance({ ...params, spender: params.token.poolAddress }, provider);\n } else {\n const params = a as CheckAllowanceParams;\n return this.tokenService.checkAllowance({ ...params, spender: params.token.poolAddress });\n }\n }\n\n async approve(provider: Provider, approveData: ApproveParams): Promise<TransactionResponse> {\n return this.tokenService.approve(provider, { ...approveData, spender: approveData.token.poolAddress });\n }\n\n async getAmountToBeDeposited(amount: string, token: TokenWithChainDetails, provider?: Provider): Promise<string> {\n validateAmountGtZero(amount);\n validateAmountDecimals(\"amount\", amount, token.decimals);\n const pool = await this.getPoolInfoFromChain(token, provider);\n const { vUsdBalance, tokenBalance, aValue, dValue } = pool;\n const vUsd = depositAmountToVUsd(amount, aValue, dValue, tokenBalance, vUsdBalance);\n return convertIntAmountToFloat(vUsd, SYSTEM_PRECISION).toFixed();\n }\n\n async getAmountToBeWithdrawn(\n amount: string,\n accountAddress: string,\n token: TokenWithChainDetails,\n provider?: Provider\n ): Promise<string> {\n validateAmountGtZero(amount);\n validateAmountDecimals(\"amount\", amount, token.decimals);\n const pool = await this.getPoolInfoFromChain(token, provider);\n const tokenAmountInSP = vUsdToWithdrawalAmount(amount);\n const tokenAmount = fromSystemPrecision(tokenAmountInSP, token.decimals);\n const userBalanceInfo = await this.getUserBalanceInfo(accountAddress, token, provider);\n const earned = userBalanceInfo.earned(pool) || \"0\";\n const commonAmount = Big(tokenAmount).plus(earned).toFixed();\n return convertIntAmountToFloat(commonAmount, token.decimals).toFixed();\n }\n\n async getUserBalanceInfo(\n accountAddress: string,\n token: TokenWithChainDetails,\n provider?: Provider\n ): Promise<UserBalanceInfo> {\n return getChainPoolService(\n token.chainSymbol,\n this.api,\n this.nodeRpcUrlsConfig,\n this.params,\n provider\n ).getUserBalanceInfo(accountAddress, token);\n }\n\n async getPoolInfoFromChain(token: TokenWithChainDetails, provider?: Provider): Promise<PoolInfo> {\n const poolKey: PoolKeyObject = { chainSymbol: token.chainSymbol, poolAddress: token.poolAddress };\n const fromCache = this.cache.get(poolKey);\n if (fromCache) {\n return fromCache;\n } else {\n const poolInfo = await getChainPoolService(\n token.chainSymbol,\n this.api,\n this.nodeRpcUrlsConfig,\n this.params,\n provider\n ).getPoolInfoFromChain(token);\n this.cache.put(poolKey, poolInfo);\n this.api.cachePut({ chainSymbol: token.chainSymbol, poolAddress: token.poolAddress }, poolInfo);\n return poolInfo;\n }\n }\n}\n\nexport function getChainPoolService(\n chainSymbol: string,\n api: AllbridgeCoreClient,\n nodeRpcUrlsConfig: NodeRpcUrlsConfig,\n params: AllbridgeCoreSdkOptions,\n provider?: Provider\n): ChainPoolService {\n switch (Chains.getChainProperty(chainSymbol).chainType) {\n case ChainType.EVM: {\n if (provider) {\n return new EvmPoolService(provider as EssentialWeb3, api);\n } else {\n const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);\n const web3 = new Web3(nodeRpcUrl);\n web3.defaultReturnFormat = { number: FMT_NUMBER.STR, bytes: FMT_BYTES.HEX };\n return new EvmPoolService(web3, api);\n }\n }\n case ChainType.TRX: {\n const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);\n const tronJsonRpc = params.tronJsonRpc;\n if (provider) {\n return new TronPoolService(provider as TronWeb, api, tronJsonRpc);\n } else {\n const tronWeb = new TronWeb({ fullHost: nodeRpcUrl });\n return new TronPoolService(tronWeb, api, tronJsonRpc);\n }\n }\n case ChainType.SOLANA: {\n const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);\n return new SolanaPoolService(nodeRpcUrl, api);\n }\n case ChainType.SRB: {\n return new SrbPoolService(nodeRpcUrlsConfig, params, api);\n }\n case ChainType.SUI: {\n return new SuiPoolService(nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol), api);\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/services/liquidity-pool/sui/index.ts"],"names":[],"mappings":";;;AAAA,+CAA8E;AAC9E,2DAA0E;AAC1E,6DAAwD;AAExD,oDAAmE;AAEnE,4DAAwE;AAExE,iEAA8D;AAC9D,oDAAqD;AACrD,kFAM4D;AAC5D,kEAA4D;AAC5D,0EAA2E;AAC3E,iDAA4D;AAC5D,yDAAmE;AACnE,+CAA+C;AAC/C,sCAMmB;AAEnB,MAAa,cAAe,SAAQ,yBAAgB;IAMzC;IACA;IANT,SAAS,GAAkB,uBAAS,CAAC,GAAG,CAAC;IAExB,MAAM,CAAY;IAEnC,YACS,SAAiB,EACjB,GAAwB;QAE/B,KAAK,EAAE,CAAC;QAHD,cAAS,GAAT,SAAS,CAAQ;QACjB,QAAG,GAAH,GAAG,CAAqB;QAG/B,IAAI,CAAC,MAAM,GAAG,IAAI,kBAAS,CAAC;YAC1B,GAAG,EAAE,SAAS;SACf,CAAC,CAAC;IACL,CAAC;I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,MAAM,MAAM,GAAG,IAAA,uBAAW,EAAC,EAAE,EAAE,SAAS,EAAE;YACxC,MAAM,EAAE,YAAY,CAAC,mBAAmB;YACxC,WAAW,EAAE,UAAU;SACxB,CAAC,CAAC;QAEH,MAAM,KAAK,GAAiB,MAAM,IAAA,kCAAsB,EAAC,CAAC,MAAiC,EAAE,EAAE,CAC7F,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC;YACnB,KAAK,EAAE,MAAM,CAAC,cAAc;YAC5B,QAAQ,EAAE,MAAM,CAAC,KAAK,CAAC,kBAAkB;YACzC,MAAM;SACP,CAAC,CACH,CAAC;QAEF,IAAI,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;YACb,EAAE,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,YAAY,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;QACjD,CAAC;aAAM,CAAC;YACN,EAAE,CAAC,eAAe,CAAC,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,cAAc,CAAC,CAAC;QACtD,CAAC;QACD,OAAO,MAAM,EAAE,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;IAClD,CAAC;CACF;AAzPD,wCAyPC","sourcesContent":["import { CoinStruct, SuiObjectResponse, SuiClient } from \"@mysten/sui/client\";\nimport { Transaction, TransactionResult } from \"@mysten/sui/transactions\";\nimport { ChainType } from \"../../../chains/chain.enums\";\nimport { AllbridgeCoreClient } from \"../../../client/core-api/core-client-base\";\nimport { InvalidAmountError, SdkError } from \"../../../exceptions\";\nimport { PoolInfo, TokenWithChainDetails } from \"../../../tokens-info\";\nimport { calculatePoolInfoImbalance } from \"../../../utils/calculation\";\nimport { RawSuiTransaction } from \"../../models\";\nimport { phantom } from \"../../models/sui/_framework/reified\";\nimport { setAddress } from \"../../models/sui/bridge\";\nimport {\n claimReward,\n deposit,\n newUserDeposit,\n pool,\n withdraw,\n} from \"../../models/sui/bridge/bridge-interface/functions\";\nimport { Pool } from \"../../models/sui/bridge/pool/structs\";\nimport { UserDeposit } from \"../../models/sui/bridge/user-deposit/structs\";\nimport { getCoinsWithAmounts } from \"../../utils/sui/coins\";\nimport { fetchAllPagesRecursive } from \"../../utils/sui/paginated\";\nimport { suiView } from \"../../utils/sui/view\";\nimport {\n ChainPoolService,\n LiquidityPoolsParams,\n LiquidityPoolsParamsWithAmount,\n UserBalance,\n UserBalanceInfo,\n} from \"../models\";\n\nexport class SuiPoolService extends ChainPoolService {\n chainType: ChainType.SUI = ChainType.SUI;\n\n private readonly client: SuiClient;\n\n constructor(\n public suiRpcUrl: string,\n public api: AllbridgeCoreClient\n ) {\n super();\n this.client = new SuiClient({\n url: suiRpcUrl,\n });\n }\n\n async getUserBalanceInfo(accountAddress: string, token: TokenWithChainDetails): Promise<UserBalanceInfo> {\n if (!token.originTokenAddress) {\n throw new SdkError(\"SUI token must contain 'originTokenAddress'\");\n }\n const suiAddresses = token.suiAddresses;\n if (!suiAddresses) {\n throw new SdkError(\"SUI token must contain 'suiAddresses'\");\n }\n setAddress(suiAddresses.bridgeAddress, suiAddresses.bridgeAddressOrigin);\n\n const deposits = await this.fetchDeposits(accountAddress, token.originTokenAddress);\n const total = deposits.reduce(\n (total, element) => {\n if (element.data) {\n total.lpAmount += BigInt((element.data.content as any).fields.lp_amount);\n total.rewardDebt += BigInt((element.data.content as any).fields.reward_debt);\n return total;\n } else {\n throw new SdkError(\"Deposits fetch failed\");\n }\n },\n { lpAmount: BigInt(0), rewardDebt: BigInt(0) }\n );\n return new UserBalance({ lpAmount: total.lpAmount.toString(), rewardDebt: total.rewardDebt.toString() });\n }\n\n private async fetchDeposits(accountAddress: string, tokenAddress: string): Promise<SuiObjectResponse[]> {\n return await fetchAllPagesRecursive((cursor: string | null | undefined) =>\n this.client.getOwnedObjects({\n owner: accountAddress,\n filter: { StructType: UserDeposit.phantom(phantom(tokenAddress)).phantomType },\n options: { showContent: true },\n cursor,\n })\n );\n }\n\n async getPoolInfoFromChain(token: TokenWithChainDetails): Promise<PoolInfo> {\n const suiAddresses = token.suiAddresses;\n if (!suiAddresses) {\n throw new SdkError(\"SUI token must contain 'suiAddresses'\");\n }\n setAddress(suiAddresses.bridgeAddress, suiAddresses.bridgeAddressOrigin);\n\n if (!token.originTokenAddress) {\n throw new SdkError(\"SUI token must contain 'originTokenAddress'\");\n }\n\n const P = 48;\n const tx = new Transaction();\n pool(tx, token.originTokenAddress, suiAddresses.bridgeObjectAddress);\n const res = await suiView(this.client, tx, Pool.reified(phantom(token.originTokenAddress)));\n\n const tokenBalance = res.state.tokenBalance;\n const vUsdBalance = res.state.vusdBalance;\n const imbalance = calculatePoolInfoImbalance({ tokenBalance, vUsdBalance });\n\n return {\n dValue: res.state.d,\n aValue: res.state.a,\n totalLpAmount: res.rewards.lpSupply,\n vUsdBalance: vUsdBalance,\n tokenBalance: tokenBalance,\n accRewardPerShareP: res.rewards.accRewardPerShareP,\n p: P,\n imbalance,\n };\n }\n\n async buildRawTransactionDeposit(params: LiquidityPoolsParamsWithAmount): Promise<RawSuiTransaction> {\n const suiAddresses = params.token.suiAddresses;\n if (!suiAddresses) {\n throw new SdkError(\"SUI token must contain 'suiAddresses'\");\n }\n setAddress(suiAddresses.bridgeAddress, suiAddresses.bridgeAddressOrigin);\n\n if (!params.token.originTokenAddress) {\n throw new SdkError(\"SUI token must contain 'originTokenAddress'\");\n }\n const coins: CoinStruct[] = await fetchAllPagesRecursive((cursor: string | null | undefined) =>\n this.client.getCoins({\n owner: params.accountAddress,\n coinType: params.token.originTokenAddress,\n cursor,\n })\n );\n if (coins.length === 0 || !coins[0]) {\n throw new InvalidAmountError(\"No coins to deposit\");\n }\n const firstCoin = coins[0];\n\n const tx = new Transaction();\n tx.setSender(params.accountAddress);\n const { depositObj, isNewDeposit } = await this.getDepositObject(\n params.accountAddress,\n params.token.originTokenAddress,\n tx\n );\n const [amountCoin] = getCoinsWithAmounts([params.amount], coins, tx);\n if (!amountCoin) {\n throw new InvalidAmountError(\"No coins to deposit\");\n }\n if (!params.token.originTokenAddress) {\n throw new SdkError(\"SUI token must contain 'originTokenAddress'\");\n }\n const rewards = deposit(tx, params.token.originTokenAddress, {\n bridge: suiAddresses.bridgeObjectAddress,\n userDeposit: depositObj,\n coin: amountCoin,\n });\n tx.mergeCoins(firstCoin.coinObjectId, [rewards]);\n if (isNewDeposit) {\n tx.transferObjects([depositObj], params.accountAddress);\n }\n return await tx.toJSON({ client: this.client });\n }\n\n private async getDepositObject(\n accountAddress: string,\n tokenAddress: string,\n tx: Transaction\n ): Promise<{\n depositObj: string | TransactionResult;\n isNewDeposit: boolean;\n }> {\n const deposits = await this.fetchDeposits(accountAddress, tokenAddress);\n if (deposits.length === 0 || !deposits[0]) {\n const tokenType = phantom(tokenAddress).phantomType;\n const depositObj = newUserDeposit(tx, tokenType);\n return { depositObj, isNewDeposit: true };\n } else {\n if (deposits[0].data?.objectId) {\n return { depositObj: deposits[0].data.objectId, isNewDeposit: false };\n } else {\n throw new SdkError(\"Something went wrong while deposit\");\n }\n }\n }\n\n async buildRawTransactionWithdraw(params: LiquidityPoolsParamsWithAmount): Promise<RawSuiTransaction> {\n const suiAddresses = params.token.suiAddresses;\n if (!suiAddresses) {\n throw new SdkError(\"SUI token must contain 'suiAddresses'\");\n }\n setAddress(suiAddresses.bridgeAddress, suiAddresses.bridgeAddressOrigin);\n\n if (!params.token.originTokenAddress) {\n throw new SdkError(\"SUI token must contain 'originTokenAddress'\");\n }\n const tokenType = phantom(params.token.originTokenAddress).phantomType;\n\n const tx = new Transaction();\n tx.setSender(params.accountAddress);\n\n const { depositObj, isNewDeposit } = await this.getDepositObject(\n params.accountAddress,\n params.token.originTokenAddress,\n tx\n );\n if (isNewDeposit) {\n throw new InvalidAmountError(\"No deposit found\");\n }\n\n const rewards = withdraw(tx, tokenType, {\n bridge: suiAddresses.bridgeObjectAddress,\n userDeposit: depositObj,\n amountLp: BigInt(params.amount),\n });\n\n const coins: CoinStruct[] = await fetchAllPagesRecursive((cursor: string | null | undefined) =>\n this.client.getCoins({\n owner: params.accountAddress,\n coinType: params.token.originTokenAddress,\n cursor,\n })\n );\n\n if (!rewards[0] || !rewards[1]) {\n throw new SdkError(\"No rewards found\");\n }\n\n if (coins[0]) {\n tx.mergeCoins(coins[0].coinObjectId, [rewards[0], rewards[1]]);\n } else {\n tx.mergeCoins(rewards[0], [rewards[1]]);\n tx.transferObjects([rewards[0]], params.accountAddress);\n }\n return await tx.toJSON({ client: this.client });\n }\n\n async buildRawTransactionClaimRewards(params: LiquidityPoolsParams): Promise<RawSuiTransaction> {\n const suiAddresses = params.token.suiAddresses;\n if (!suiAddresses) {\n throw new SdkError(\"SUI token must contain 'suiAddresses'\");\n }\n setAddress(suiAddresses.bridgeAddress, suiAddresses.bridgeAddressOrigin);\n\n if (!params.token.originTokenAddress) {\n throw new SdkError(\"SUI token must contain 'originTokenAddress'\");\n }\n const tokenType = phantom(params.token.originTokenAddress).phantomType;\n\n const tx = new Transaction();\n tx.setSender(params.accountAddress);\n\n const { depositObj, isNewDeposit } = await this.getDepositObject(\n params.accountAddress,\n params.token.originTokenAddress,\n tx\n );\n if (isNewDeposit) {\n throw new InvalidAmountError(\"No deposit found\");\n }\n\n const reward = claimReward(tx, tokenType, {\n bridge: suiAddresses.bridgeObjectAddress,\n userDeposit: depositObj,\n });\n\n const coins: CoinStruct[] = await fetchAllPagesRecursive((cursor: string | null | undefined) =>\n this.client.getCoins({\n owner: params.accountAddress,\n coinType: params.token.originTokenAddress,\n cursor,\n })\n );\n\n if (coins[0]) {\n tx.mergeCoins(coins[0].coinObjectId, [reward]);\n } else {\n tx.transferObjects([reward], params.accountAddress);\n }\n return await tx.toJSON({ client: this.client });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/services/liquidity-pool/sui/index.ts"],"names":[],"mappings":";;;AAAA,+CAA+C;AAE/C,2DAA0E;AAC1E,6DAAwD;AAExD,oDAAmE;AA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C;IAClD,CAAC;CACF;AAzPD,wCAyPC","sourcesContent":["import { SuiClient } from \"@mysten/sui/client\";\nimport { CoinStruct, SuiObjectResponse } from \"@mysten/sui/src/client/types/generated\";\nimport { Transaction, TransactionResult } from \"@mysten/sui/transactions\";\nimport { ChainType } from \"../../../chains/chain.enums\";\nimport { AllbridgeCoreClient } from \"../../../client/core-api/core-client-base\";\nimport { InvalidAmountError, SdkError } from \"../../../exceptions\";\nimport { PoolInfo, TokenWithChainDetails } from \"../../../tokens-info\";\nimport { calculatePoolInfoImbalance } from \"../../../utils/calculation\";\nimport { RawSuiTransaction } from \"../../models\";\nimport { phantom } from \"../../models/sui/_framework/reified\";\nimport { setAddress } from \"../../models/sui/bridge\";\nimport {\n claimReward,\n deposit,\n newUserDeposit,\n pool,\n withdraw,\n} from \"../../models/sui/bridge/bridge-interface/functions\";\nimport { Pool } from \"../../models/sui/bridge/pool/structs\";\nimport { UserDeposit } from \"../../models/sui/bridge/user-deposit/structs\";\nimport { getCoinsWithAmounts } from \"../../utils/sui/coins\";\nimport { fetchAllPagesRecursive } from \"../../utils/sui/paginated\";\nimport { suiView } from \"../../utils/sui/view\";\nimport {\n ChainPoolService,\n LiquidityPoolsParams,\n LiquidityPoolsParamsWithAmount,\n UserBalance,\n UserBalanceInfo,\n} from \"../models\";\n\nexport class SuiPoolService extends ChainPoolService {\n chainType: ChainType.SUI = ChainType.SUI;\n\n private readonly client: SuiClient;\n\n constructor(\n public suiRpcUrl: string,\n public api: AllbridgeCoreClient\n ) {\n super();\n this.client = new SuiClient({\n url: suiRpcUrl,\n });\n }\n\n async getUserBalanceInfo(accountAddress: string, token: TokenWithChainDetails): Promise<UserBalanceInfo> {\n if (!token.originTokenAddress) {\n throw new SdkError(\"SUI token must contain 'originTokenAddress'\");\n }\n const suiAddresses = token.suiAddresses;\n if (!suiAddresses) {\n throw new SdkError(\"SUI token must contain 'suiAddresses'\");\n }\n setAddress(suiAddresses.bridgeAddress, suiAddresses.bridgeAddressOrigin);\n\n const deposits = await this.fetchDeposits(accountAddress, token.originTokenAddress);\n const total = deposits.reduce(\n (total, element) => {\n if (element.data) {\n total.lpAmount += BigInt((element.data.content as any).fields.lp_amount);\n total.rewardDebt += BigInt((element.data.content as any).fields.reward_debt);\n return total;\n } else {\n throw new SdkError(\"Deposits fetch failed\");\n }\n },\n { lpAmount: BigInt(0), rewardDebt: BigInt(0) }\n );\n return new UserBalance({ lpAmount: total.lpAmount.toString(), rewardDebt: total.rewardDebt.toString() });\n }\n\n private async fetchDeposits(accountAddress: string, tokenAddress: string): Promise<SuiObjectResponse[]> {\n return await fetchAllPagesRecursive((cursor: string | null | undefined) =>\n this.client.getOwnedObjects({\n owner: accountAddress,\n filter: { StructType: UserDeposit.phantom(phantom(tokenAddress)).phantomType },\n options: { showContent: true },\n cursor,\n })\n );\n }\n\n async getPoolInfoFromChain(token: TokenWithChainDetails): Promise<PoolInfo> {\n const suiAddresses = token.suiAddresses;\n if (!suiAddresses) {\n throw new SdkError(\"SUI token must contain 'suiAddresses'\");\n }\n setAddress(suiAddresses.bridgeAddress, suiAddresses.bridgeAddressOrigin);\n\n if (!token.originTokenAddress) {\n throw new SdkError(\"SUI token must contain 'originTokenAddress'\");\n }\n\n const P = 48;\n const tx = new Transaction();\n pool(tx, token.originTokenAddress, suiAddresses.bridgeObjectAddress);\n const res = await suiView(this.client, tx, Pool.reified(phantom(token.originTokenAddress)));\n\n const tokenBalance = res.state.tokenBalance;\n const vUsdBalance = res.state.vusdBalance;\n const imbalance = calculatePoolInfoImbalance({ tokenBalance, vUsdBalance });\n\n return {\n dValue: res.state.d,\n aValue: res.state.a,\n totalLpAmount: res.rewards.lpSupply,\n vUsdBalance: vUsdBalance,\n tokenBalance: tokenBalance,\n accRewardPerShareP: res.rewards.accRewardPerShareP,\n p: P,\n imbalance,\n };\n }\n\n async buildRawTransactionDeposit(params: LiquidityPoolsParamsWithAmount): Promise<RawSuiTransaction> {\n const suiAddresses = params.token.suiAddresses;\n if (!suiAddresses) {\n throw new SdkError(\"SUI token must contain 'suiAddresses'\");\n }\n setAddress(suiAddresses.bridgeAddress, suiAddresses.bridgeAddressOrigin);\n\n if (!params.token.originTokenAddress) {\n throw new SdkError(\"SUI token must contain 'originTokenAddress'\");\n }\n const coins: CoinStruct[] = await fetchAllPagesRecursive((cursor: string | null | undefined) =>\n this.client.getCoins({\n owner: params.accountAddress,\n coinType: params.token.originTokenAddress,\n cursor,\n })\n );\n if (coins.length === 0 || !coins[0]) {\n throw new InvalidAmountError(\"No coins to deposit\");\n }\n const firstCoin = coins[0];\n\n const tx = new Transaction();\n tx.setSender(params.accountAddress);\n const { depositObj, isNewDeposit } = await this.getDepositObject(\n params.accountAddress,\n params.token.originTokenAddress,\n tx\n );\n const [amountCoin] = getCoinsWithAmounts([params.amount], coins, tx);\n if (!amountCoin) {\n throw new InvalidAmountError(\"No coins to deposit\");\n }\n if (!params.token.originTokenAddress) {\n throw new SdkError(\"SUI token must contain 'originTokenAddress'\");\n }\n const rewards = deposit(tx, params.token.originTokenAddress, {\n bridge: suiAddresses.bridgeObjectAddress,\n userDeposit: depositObj,\n coin: amountCoin,\n });\n tx.mergeCoins(firstCoin.coinObjectId, [rewards]);\n if (isNewDeposit) {\n tx.transferObjects([depositObj], params.accountAddress);\n }\n return await tx.toJSON({ client: this.client });\n }\n\n private async getDepositObject(\n accountAddress: string,\n tokenAddress: string,\n tx: Transaction\n ): Promise<{\n depositObj: string | TransactionResult;\n isNewDeposit: boolean;\n }> {\n const deposits = await this.fetchDeposits(accountAddress, tokenAddress);\n if (deposits.length === 0 || !deposits[0]) {\n const tokenType = phantom(tokenAddress).phantomType;\n const depositObj = newUserDeposit(tx, tokenType);\n return { depositObj, isNewDeposit: true };\n } else {\n if (deposits[0].data?.objectId) {\n return { depositObj: deposits[0].data.objectId, isNewDeposit: false };\n } else {\n throw new SdkError(\"Something went wrong while deposit\");\n }\n }\n }\n\n async buildRawTransactionWithdraw(params: LiquidityPoolsParamsWithAmount): Promise<RawSuiTransaction> {\n const suiAddresses = params.token.suiAddresses;\n if (!suiAddresses) {\n throw new SdkError(\"SUI token must contain 'suiAddresses'\");\n }\n setAddress(suiAddresses.bridgeAddress, suiAddresses.bridgeAddressOrigin);\n\n if (!params.token.originTokenAddress) {\n throw new SdkError(\"SUI token must contain 'originTokenAddress'\");\n }\n const tokenType = phantom(params.token.originTokenAddress).phantomType;\n\n const tx = new Transaction();\n tx.setSender(params.accountAddress);\n\n const { depositObj, isNewDeposit } = await this.getDepositObject(\n params.accountAddress,\n params.token.originTokenAddress,\n tx\n );\n if (isNewDeposit) {\n throw new InvalidAmountError(\"No deposit found\");\n }\n\n const rewards = withdraw(tx, tokenType, {\n bridge: suiAddresses.bridgeObjectAddress,\n userDeposit: depositObj,\n amountLp: BigInt(params.amount),\n });\n\n const coins: CoinStruct[] = await fetchAllPagesRecursive((cursor: string | null | undefined) =>\n this.client.getCoins({\n owner: params.accountAddress,\n coinType: params.token.originTokenAddress,\n cursor,\n })\n );\n\n if (!rewards[0] || !rewards[1]) {\n throw new SdkError(\"No rewards found\");\n }\n\n if (coins[0]) {\n tx.mergeCoins(coins[0].coinObjectId, [rewards[0], rewards[1]]);\n } else {\n tx.mergeCoins(rewards[0], [rewards[1]]);\n tx.transferObjects([rewards[0]], params.accountAddress);\n }\n return await tx.toJSON({ client: this.client });\n }\n\n async buildRawTransactionClaimRewards(params: LiquidityPoolsParams): Promise<RawSuiTransaction> {\n const suiAddresses = params.token.suiAddresses;\n if (!suiAddresses) {\n throw new SdkError(\"SUI token must contain 'suiAddresses'\");\n }\n setAddress(suiAddresses.bridgeAddress, suiAddresses.bridgeAddressOrigin);\n\n if (!params.token.originTokenAddress) {\n throw new SdkError(\"SUI token must contain 'originTokenAddress'\");\n }\n const tokenType = phantom(params.token.originTokenAddress).phantomType;\n\n const tx = new Transaction();\n tx.setSender(params.accountAddress);\n\n const { depositObj, isNewDeposit } = await this.getDepositObject(\n params.accountAddress,\n params.token.originTokenAddress,\n tx\n );\n if (isNewDeposit) {\n throw new InvalidAmountError(\"No deposit found\");\n }\n\n const reward = claimReward(tx, tokenType, {\n bridge: suiAddresses.bridgeObjectAddress,\n userDeposit: depositObj,\n });\n\n const coins: CoinStruct[] = await fetchAllPagesRecursive((cursor: string | null | undefined) =>\n this.client.getCoins({\n owner: params.accountAddress,\n coinType: params.token.originTokenAddress,\n cursor,\n })\n );\n\n if (coins[0]) {\n tx.mergeCoins(coins[0].coinObjectId, [reward]);\n } else {\n tx.transferObjects([reward], params.accountAddress);\n }\n return await tx.toJSON({ client: this.client });\n }\n}\n"]}
|