@allbridge/bridge-core-sdk 3.26.0 → 3.27.0-alpha.10

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.
Files changed (91) hide show
  1. package/dist/browser/index.js +6 -1
  2. package/dist/browser/index.js.map +4 -4
  3. package/dist/cjs/index.js +6 -1
  4. package/dist/cjs/index.js.map +4 -4
  5. package/dist/esm/index.js +6 -1
  6. package/dist/esm/index.js.map +4 -4
  7. package/dist/src/chains/chain.enums.d.ts +12 -2
  8. package/dist/src/chains/chain.enums.js +10 -0
  9. package/dist/src/chains/chain.enums.js.map +1 -1
  10. package/dist/src/chains/index.js +12 -0
  11. package/dist/src/chains/index.js.map +1 -1
  12. package/dist/src/client/core-api/core-api-mapper.js +2 -0
  13. package/dist/src/client/core-api/core-api-mapper.js.map +1 -1
  14. package/dist/src/client/core-api/core-api.model.d.ts +2 -0
  15. package/dist/src/client/core-api/core-api.model.js.map +1 -1
  16. package/dist/src/configs/mainnet.js +1 -0
  17. package/dist/src/configs/mainnet.js.map +1 -1
  18. package/dist/src/index.d.ts +6 -4
  19. package/dist/src/index.js +5 -11
  20. package/dist/src/index.js.map +1 -1
  21. package/dist/src/services/bridge/alg/index.d.ts +16 -0
  22. package/dist/src/services/bridge/alg/index.js +181 -0
  23. package/dist/src/services/bridge/alg/index.js.map +1 -0
  24. package/dist/src/services/bridge/index.js +21 -0
  25. package/dist/src/services/bridge/index.js.map +1 -1
  26. package/dist/src/services/bridge/models/bridge.model.d.ts +2 -0
  27. package/dist/src/services/bridge/models/bridge.model.js.map +1 -1
  28. package/dist/src/services/bridge/stx/index.d.ts +16 -0
  29. package/dist/src/services/bridge/stx/index.js +127 -0
  30. package/dist/src/services/bridge/stx/index.js.map +1 -0
  31. package/dist/src/services/bridge/sui/index.js.map +1 -1
  32. package/dist/src/services/bridge/utils.d.ts +5 -1
  33. package/dist/src/services/bridge/utils.js +95 -15
  34. package/dist/src/services/bridge/utils.js.map +1 -1
  35. package/dist/src/services/liquidity-pool/alg/index.d.ts +19 -0
  36. package/dist/src/services/liquidity-pool/alg/index.js +134 -0
  37. package/dist/src/services/liquidity-pool/alg/index.js.map +1 -0
  38. package/dist/src/services/liquidity-pool/index.js +21 -0
  39. package/dist/src/services/liquidity-pool/index.js.map +1 -1
  40. package/dist/src/services/liquidity-pool/stx/index.d.ts +21 -0
  41. package/dist/src/services/liquidity-pool/stx/index.js +141 -0
  42. package/dist/src/services/liquidity-pool/stx/index.js.map +1 -0
  43. package/dist/src/services/liquidity-pool/sui/index.js.map +1 -1
  44. package/dist/src/services/liquidity-pool/trx/index.js.map +1 -1
  45. package/dist/src/services/models/alg/BridgeClient.d.ts +2743 -0
  46. package/dist/src/services/models/alg/BridgeClient.js +2685 -0
  47. package/dist/src/services/models/alg/BridgeClient.js.map +1 -0
  48. package/dist/src/services/models/alg/PaddingUtilClient.d.ts +639 -0
  49. package/dist/src/services/models/alg/PaddingUtilClient.js +425 -0
  50. package/dist/src/services/models/alg/PaddingUtilClient.js.map +1 -0
  51. package/dist/src/services/models/alg/PoolClient.d.ts +2268 -0
  52. package/dist/src/services/models/alg/PoolClient.js +2195 -0
  53. package/dist/src/services/models/alg/PoolClient.js.map +1 -0
  54. package/dist/src/services/models/index.d.ts +7 -5
  55. package/dist/src/services/models/index.js.map +1 -1
  56. package/dist/src/services/models/stx/clarigen-types.d.ts +657 -0
  57. package/dist/src/services/models/stx/clarigen-types.js +2296 -0
  58. package/dist/src/services/models/stx/clarigen-types.js.map +1 -0
  59. package/dist/src/services/token/alg/index.d.ts +17 -0
  60. package/dist/src/services/token/alg/index.js +46 -0
  61. package/dist/src/services/token/alg/index.js.map +1 -0
  62. package/dist/src/services/token/index.js +21 -0
  63. package/dist/src/services/token/index.js.map +1 -1
  64. package/dist/src/services/token/stx/index.d.ts +20 -0
  65. package/dist/src/services/token/stx/index.js +59 -0
  66. package/dist/src/services/token/stx/index.js.map +1 -0
  67. package/dist/src/services/token/sui/index.js.map +1 -1
  68. package/dist/src/services/utils/alg/index.d.ts +9 -0
  69. package/dist/src/services/utils/alg/index.js +74 -0
  70. package/dist/src/services/utils/alg/index.js.map +1 -0
  71. package/dist/src/services/utils/stx/get-token-name.d.ts +2 -0
  72. package/dist/src/services/utils/stx/get-token-name.js +15 -0
  73. package/dist/src/services/utils/stx/get-token-name.js.map +1 -0
  74. package/dist/src/services/utils/stx/post-conditions.d.ts +3 -0
  75. package/dist/src/services/utils/stx/post-conditions.js +27 -0
  76. package/dist/src/services/utils/stx/post-conditions.js.map +1 -0
  77. package/dist/src/services/utils/trx/index.js.map +1 -1
  78. package/dist/src/services/yield/index.js +8 -0
  79. package/dist/src/services/yield/index.js.map +1 -1
  80. package/dist/src/tokens-info/tokens-info.model.d.ts +8 -0
  81. package/dist/src/tokens-info/tokens-info.model.js.map +1 -1
  82. package/dist/src/utils/alg/index.d.ts +21 -0
  83. package/dist/src/utils/alg/index.js +67 -0
  84. package/dist/src/utils/alg/index.js.map +1 -0
  85. package/dist/src/utils/index.d.ts +3 -0
  86. package/dist/src/utils/index.js +3 -0
  87. package/dist/src/utils/index.js.map +1 -1
  88. package/dist/src/version.d.ts +1 -1
  89. package/dist/src/version.js +1 -1
  90. package/dist/src/version.js.map +1 -1
  91. package/package.json +9 -2
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AlgPoolService = void 0;
4
+ const algosdk_1 = require("algosdk");
5
+ const chain_enums_1 = require("../../../chains/chain.enums");
6
+ const exceptions_1 = require("../../../exceptions");
7
+ const calculation_1 = require("../../../utils/calculation");
8
+ const PoolClient_1 = require("../../models/alg/PoolClient");
9
+ const alg_1 = require("../../utils/alg");
10
+ const models_1 = require("../models");
11
+ class AlgPoolService extends models_1.ChainPoolService {
12
+ algorand;
13
+ api;
14
+ chainType = chain_enums_1.ChainType.ALG;
15
+ P = 48;
16
+ constructor(algorand, api) {
17
+ super();
18
+ this.algorand = algorand;
19
+ this.api = api;
20
+ }
21
+ async buildRawTransactionClaimRewards(params) {
22
+ const userAccount = params.accountAddress;
23
+ const assetId = BigInt(params.token.tokenAddress);
24
+ const poolId = BigInt(params.token.poolAddress);
25
+ const pool = this.getPool(poolId);
26
+ const composer = this.algorand.newGroup();
27
+ composer.addAppCallMethodCall(await pool.params.claimRewards({
28
+ args: [],
29
+ sender: userAccount,
30
+ extraFee: (0, alg_1.feeForInner)(1),
31
+ assetReferences: [assetId],
32
+ }));
33
+ let { transactions } = await composer.buildTransactions();
34
+ transactions = (0, algosdk_1.assignGroupID)(transactions);
35
+ return (0, alg_1.encodeTxs)(...transactions);
36
+ }
37
+ async buildRawTransactionDeposit(params) {
38
+ const userAccount = params.accountAddress;
39
+ const amount = BigInt(params.amount);
40
+ const assetId = BigInt(params.token.tokenAddress);
41
+ const poolId = BigInt(params.token.poolAddress);
42
+ const pool = this.getPool(poolId);
43
+ const isOptedIn = await (0, alg_1.checkAppOptIn)(poolId, userAccount, this.algorand);
44
+ const onComplete = isOptedIn
45
+ ? algosdk_1.OnApplicationComplete.NoOpOC
46
+ : algosdk_1.OnApplicationComplete.OptInOC;
47
+ const composer = this.algorand.newGroup();
48
+ const assetTransfer = await this.algorand.createTransaction.assetTransfer({
49
+ assetId: assetId,
50
+ amount: amount,
51
+ sender: userAccount,
52
+ receiver: pool.appAddress,
53
+ });
54
+ composer.addAppCallMethodCall(await pool.params.deposit({
55
+ args: { assetTransferRef: assetTransfer },
56
+ sender: userAccount,
57
+ onComplete: onComplete,
58
+ extraFee: (0, alg_1.feeForInner)(5),
59
+ }));
60
+ let { transactions } = await composer.buildTransactions();
61
+ transactions = (0, algosdk_1.assignGroupID)(transactions);
62
+ return (0, alg_1.encodeTxs)(...transactions);
63
+ }
64
+ async buildRawTransactionWithdraw(params) {
65
+ const userAccount = params.accountAddress;
66
+ const amount = BigInt(params.amount);
67
+ const assetId = BigInt(params.token.tokenAddress);
68
+ const poolId = BigInt(params.token.poolAddress);
69
+ const pool = this.getPool(poolId);
70
+ const composer = this.algorand.newGroup();
71
+ composer.addAppCallMethodCall(await pool.params.withdraw({
72
+ args: { amountLp: amount },
73
+ sender: userAccount,
74
+ assetReferences: [assetId],
75
+ extraFee: (0, alg_1.feeForInner)(7),
76
+ }));
77
+ let { transactions } = await composer.buildTransactions();
78
+ transactions = (0, algosdk_1.assignGroupID)(transactions);
79
+ return (0, alg_1.encodeTxs)(...transactions);
80
+ }
81
+ async getPoolInfoFromChain(token) {
82
+ const pool = this.getPool(BigInt(token.poolAddress));
83
+ const all = await pool.state.global.getAll();
84
+ const aValue = all.a?.toString();
85
+ const dValue = all.d?.toString();
86
+ const tokenBalance = all.tokenBalance?.toString();
87
+ const vUsdBalance = all.vUsdBalance?.toString();
88
+ const totalLpAmount = all.totalSupply?.toString();
89
+ const accRewardPerShareP = (0, algosdk_1.bytesToBigInt)(all.accRewardPerShareP?.asByteArray() ?? Uint8Array.from([])).toString();
90
+ if (aValue && dValue && tokenBalance && vUsdBalance && totalLpAmount && accRewardPerShareP) {
91
+ const imbalance = (0, calculation_1.calculatePoolInfoImbalance)({ tokenBalance, vUsdBalance });
92
+ return {
93
+ aValue,
94
+ dValue,
95
+ tokenBalance,
96
+ vUsdBalance,
97
+ totalLpAmount,
98
+ accRewardPerShareP,
99
+ p: this.P,
100
+ imbalance,
101
+ };
102
+ }
103
+ throw new exceptions_1.SdkError("Unable to pool info from chain");
104
+ }
105
+ async getUserBalanceInfo(accountAddress, token) {
106
+ const appId = BigInt(token.poolAddress);
107
+ const pool = this.getPool(appId);
108
+ try {
109
+ const { balance, userRewardDebt } = await pool.state.local(accountAddress).getAll();
110
+ if (balance !== undefined && userRewardDebt !== undefined) {
111
+ return new models_1.UserBalance({
112
+ lpAmount: balance.toString(),
113
+ rewardDebt: userRewardDebt.toString(),
114
+ });
115
+ }
116
+ }
117
+ catch (ignoreError) {
118
+ const info = await this.algorand.account.getInformation(accountAddress);
119
+ const localStates = info.appsLocalState;
120
+ if (localStates) {
121
+ const isOptedIn = localStates.find(({ id: id }) => id === appId);
122
+ if (!isOptedIn) {
123
+ return new models_1.UserBalance({ lpAmount: "0", rewardDebt: "0" });
124
+ }
125
+ }
126
+ }
127
+ throw new exceptions_1.SdkError("Unable to get user balance");
128
+ }
129
+ getPool(appId) {
130
+ return this.algorand.client.getTypedAppClientById(PoolClient_1.PoolClient, { appId });
131
+ }
132
+ }
133
+ exports.AlgPoolService = AlgPoolService;
134
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/services/liquidity-pool/alg/index.ts"],"names":[],"mappings":";;;AACA,qCAA8E;AAC9E,6DAAwD;AAExD,oDAA+C;AAE/C,4DAAwE;AAExE,4DAAyD;AACzD,yCAAwE;AACxE,sCAMmB;AAEnB,MAAa,cAAe,SAAQ,yBAAgB;IAKzC;IACA;IALT,SAAS,GAAkB,uBAAS,CAAC,GAAG,CAAC;IACjC,CAAC,GAAG,EAAE,CAAC;IAEf,YACS,QAAwB,EACxB,GAAwB;QAE/B,KAAK,EAAE,CAAC;QAHD,aAAQ,GAAR,QAAQ,CAAgB;QACxB,QAAG,GAAH,GAAG,CAAqB;IAGjC,CAAC;IAED,KAAK,CAAC,+BAA+B,CAAC,MAA4B;QAChE,MAAM,WAAW,GAAG,MAAM,CAAC,cAAc,CAAC;QAC1C,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QAClD,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;QAChD,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAElC,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAC;QAC1C,QAAQ,CAAC,oBAAoB,CAC3B,MAAM,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC;YAC7B,IAAI,EAAE,EAA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,EAAE,KAAK,EAAE,CAAC,CAAC;IAC3E,CAAC;CACF;AA5ID,wCA4IC","sourcesContent":["import { AlgorandClient } from \"@algorandfoundation/algokit-utils\";\nimport { assignGroupID, bytesToBigInt, OnApplicationComplete } from \"algosdk\";\nimport { ChainType } from \"../../../chains/chain.enums\";\nimport { AllbridgeCoreClient } from \"../../../client/core-api/core-client-base\";\nimport { SdkError } from \"../../../exceptions\";\nimport { PoolInfo, TokenWithChainDetails } from \"../../../tokens-info\";\nimport { calculatePoolInfoImbalance } from \"../../../utils/calculation\";\nimport { RawTransaction } from \"../../models\";\nimport { PoolClient } from \"../../models/alg/PoolClient\";\nimport { checkAppOptIn, encodeTxs, feeForInner } from \"../../utils/alg\";\nimport {\n ChainPoolService,\n LiquidityPoolsParams,\n LiquidityPoolsParamsWithAmount,\n UserBalance,\n UserBalanceInfo,\n} from \"../models\";\n\nexport class AlgPoolService extends ChainPoolService {\n chainType: ChainType.ALG = ChainType.ALG;\n private P = 48;\n\n constructor(\n public algorand: AlgorandClient,\n public api: AllbridgeCoreClient\n ) {\n super();\n }\n\n async buildRawTransactionClaimRewards(params: LiquidityPoolsParams): Promise<RawTransaction> {\n const userAccount = params.accountAddress;\n const assetId = BigInt(params.token.tokenAddress);\n const poolId = BigInt(params.token.poolAddress);\n const pool = this.getPool(poolId);\n\n const composer = this.algorand.newGroup();\n composer.addAppCallMethodCall(\n await pool.params.claimRewards({\n args: [],\n sender: userAccount,\n extraFee: feeForInner(1),\n assetReferences: [assetId],\n })\n );\n let { transactions } = await composer.buildTransactions();\n transactions = assignGroupID(transactions);\n return encodeTxs(...transactions);\n }\n\n async buildRawTransactionDeposit(params: LiquidityPoolsParamsWithAmount): Promise<RawTransaction> {\n const userAccount = params.accountAddress;\n const amount = BigInt(params.amount);\n const assetId = BigInt(params.token.tokenAddress);\n const poolId = BigInt(params.token.poolAddress);\n const pool = this.getPool(poolId);\n\n const isOptedIn = await checkAppOptIn(poolId, userAccount, this.algorand);\n\n const onComplete: OnApplicationComplete.OptInOC | OnApplicationComplete.NoOpOC = isOptedIn\n ? OnApplicationComplete.NoOpOC\n : OnApplicationComplete.OptInOC;\n\n const composer = this.algorand.newGroup();\n\n const assetTransfer = await this.algorand.createTransaction.assetTransfer({\n assetId: assetId,\n amount: amount,\n sender: userAccount,\n receiver: pool.appAddress,\n });\n composer.addAppCallMethodCall(\n await pool.params.deposit({\n args: { assetTransferRef: assetTransfer },\n sender: userAccount,\n onComplete: onComplete,\n extraFee: feeForInner(5),\n })\n );\n\n let { transactions } = await composer.buildTransactions();\n transactions = assignGroupID(transactions);\n return encodeTxs(...transactions);\n }\n\n async buildRawTransactionWithdraw(params: LiquidityPoolsParamsWithAmount): Promise<RawTransaction> {\n const userAccount = params.accountAddress;\n const amount = BigInt(params.amount);\n const assetId = BigInt(params.token.tokenAddress);\n const poolId = BigInt(params.token.poolAddress);\n const pool = this.getPool(poolId);\n\n const composer = this.algorand.newGroup();\n composer.addAppCallMethodCall(\n await pool.params.withdraw({\n args: { amountLp: amount },\n sender: userAccount,\n assetReferences: [assetId],\n extraFee: feeForInner(7),\n })\n );\n\n let { transactions } = await composer.buildTransactions();\n transactions = assignGroupID(transactions);\n return encodeTxs(...transactions);\n }\n\n async getPoolInfoFromChain(token: TokenWithChainDetails): Promise<PoolInfo> {\n const pool = this.getPool(BigInt(token.poolAddress));\n const all = await pool.state.global.getAll();\n const aValue = all.a?.toString();\n const dValue = all.d?.toString();\n const tokenBalance = all.tokenBalance?.toString();\n const vUsdBalance = all.vUsdBalance?.toString();\n const totalLpAmount = all.totalSupply?.toString();\n const accRewardPerShareP = bytesToBigInt(all.accRewardPerShareP?.asByteArray() ?? Uint8Array.from([])).toString();\n if (aValue && dValue && tokenBalance && vUsdBalance && totalLpAmount && accRewardPerShareP) {\n const imbalance = calculatePoolInfoImbalance({ tokenBalance, vUsdBalance });\n return {\n aValue,\n dValue,\n tokenBalance,\n vUsdBalance,\n totalLpAmount,\n accRewardPerShareP,\n p: this.P,\n imbalance,\n };\n }\n throw new SdkError(\"Unable to pool info from chain\");\n }\n\n async getUserBalanceInfo(accountAddress: string, token: TokenWithChainDetails): Promise<UserBalanceInfo> {\n const appId = BigInt(token.poolAddress);\n const pool = this.getPool(appId);\n try {\n const { balance, userRewardDebt } = await pool.state.local(accountAddress).getAll();\n if (balance !== undefined && userRewardDebt !== undefined) {\n return new UserBalance({\n lpAmount: balance.toString(),\n rewardDebt: userRewardDebt.toString(),\n });\n }\n } catch (ignoreError) {\n const info = await this.algorand.account.getInformation(accountAddress);\n const localStates = info.appsLocalState;\n if (localStates) {\n const isOptedIn = localStates.find(({ id: id }) => id === appId);\n if (!isOptedIn) {\n return new UserBalance({ lpAmount: \"0\", rewardDebt: \"0\" });\n }\n }\n }\n throw new SdkError(\"Unable to get user balance\");\n }\n\n private getPool(appId: bigint): PoolClient {\n return this.algorand.client.getTypedAppClientById(PoolClient, { appId });\n }\n}\n"]}
@@ -5,6 +5,7 @@ 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");
8
9
  const big_js_1 = require("big.js");
9
10
  const timed_cache_1 = __importDefault(require("timed-cache"));
10
11
  const tronweb_1 = require("tronweb");
@@ -15,10 +16,12 @@ const calculation_1 = require("../../utils/calculation");
15
16
  const constants_1 = require("../../utils/calculation/constants");
16
17
  const utils_1 = require("../../utils/utils");
17
18
  const calculation_2 = require("../utils/calculation");
19
+ const alg_1 = require("./alg");
18
20
  const evm_1 = require("./evm");
19
21
  const raw_pool_transaction_builder_1 = require("./raw-pool-transaction-builder");
20
22
  const sol_1 = require("./sol");
21
23
  const srb_1 = require("./srb");
24
+ const stx_1 = require("./stx");
22
25
  const sui_1 = require("./sui");
23
26
  const trx_1 = require("./trx");
24
27
  class DefaultLiquidityPoolService {
@@ -133,6 +136,24 @@ function getChainPoolService(chainSymbol, api, nodeRpcUrlsConfig, params, provid
133
136
  case index_1.ChainType.SUI: {
134
137
  return new sui_1.SuiPoolService(nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol), api);
135
138
  }
139
+ case index_1.ChainType.ALG: {
140
+ if (provider) {
141
+ const algod = provider;
142
+ const algorand = algokit_utils_1.AlgorandClient.fromClients({ algod });
143
+ return new alg_1.AlgPoolService(algorand, api);
144
+ }
145
+ else {
146
+ const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);
147
+ const algorand = algokit_utils_1.AlgorandClient.fromConfig({
148
+ algodConfig: { server: nodeRpcUrl },
149
+ });
150
+ return new alg_1.AlgPoolService(algorand, api);
151
+ }
152
+ }
153
+ case index_1.ChainType.STX: {
154
+ const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);
155
+ return new stx_1.StxPoolService(nodeRpcUrl, params, api);
156
+ }
136
157
  }
137
158
  }
138
159
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/services/liquidity-pool/index.ts"],"names":[],"mappings":";;;;;;AAuNA,kDAuCC;AA9PD,mCAA6B;AAC7B,8DAAgC;AAChC,qCAAkC;AAClC,+BAAmD;AAEnD,yCAAsC;AAGtC,uCAAgF;AAEhF,yDAAuF;AACvF,iEAAqE;AACrE,6CAAiF;AAGjF,sDAAmF;AACnF,+BAAuC;AAEvC,iFAA6G;AAC7G,+BAA0C;AAC1C,+BAAuC;AACvC,+BAAuC;AACvC,+BAAwC;AA4FxC,MAAa,2BAA2B;IAK5B;IACA;IACA;IACA;IAPH,YAAY,CAA4B;IACvC,KAAK,CAAkB;IAE/B,YACU,GAAgC,EAChC,iBAAoC,EACpC,MAA+B,EAC/B,YAA0B;QAH1B,QAAG,GAAH,GAAG,CAA6B;QAChC,sBAAiB,GAAjB,iBAAiB,CAAmB;QACpC,WAAM,GAAN,MAAM,CA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CAAC;YAChE,MAAM,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC;YACvC,IAAI,QAAQ,EAAE,CAAC;gBACb,OAAO,IAAI,qBAAe,CAAC,QAAmB,EAAE,GAAG,EAAE,WAAW,CAAC,CAAC;YACpE,CAAC;iBAAM,CAAC;gBACN,MAAM,OAAO,GAAG,IAAI,iBAAO,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC,CAAC;gBACtD,OAAO,IAAI,qBAAe,CAAC,OAAO,EAAE,GAAG,EAAE,WAAW,CAAC,CAAC;YACxD,CAAC;QACH,CAAC;QACD,KAAK,iBAAS,CAAC,MAAM,CAAC,CAAC,CAAC;YACtB,MAAM,UAAU,GAAG,iBAAiB,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;YAChE,OAAO,IAAI,uBAAiB,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;QAChD,CAAC;QACD,KAAK,iBAAS,CAAC,GAAG,CAAC,CAAC,CAAC;YACnB,OAAO,IAAI,oBAAc,CAAC,iBAAiB,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;QAC5D,CAAC;QACD,KAAK,iBAAS,CAAC,GAAG,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
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/services/liquidity-pool/index.ts"],"names":[],"mappings":";;;;;;AA2NA,kDAwDC;AAnRD,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,+BAAuC;AACvC,+BAAwC;AA4FxC,MAAa,2BAA2B;IAK5B;IACA;IACA;IACA;IAPH,YAAY,CAA4B;IACvC,KAAK,CAAkB;IAE/B,YACU,GAAgC,EAChC,iBAAoC,EACpC,MAA+B,EAC/B,YAA0B;QAH1B,QAAG,GAAH,GAAG,CAA6B;QAChC,sBAAiB,GAAjB,iBAAiB,CAAmB;QACpC,WAAM,GAAN,MAAM,CAAyB;QAC/B,iBAAY,GAAZ,YAAY,CAAc;QAElC,IAAI,CAAC,YAAY,GAAG,IAAI,+DAAgC,CAAC,GAAG,EAAE,iBAAiB,EAAE,IAAI,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;QAC5G,MAAM,GAAG,GAAG,MAAM,CAAC,qBAAqB,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,qBAAqB,GAAG,IAAI,CAAC,CAAC,CAAC,EAAE,GAAG,IAAI,CAAC;QAC/F,IAAI,CAAC,KAAK,GAAG,IAAI,qBAAK,CAAW,EAAE,UAAU,EAAE,GAAG,EAAE,CAAC,CAAC;IACxD,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,CAAgC,EAAE,CAAsB;QACzE,IAAI,CAAC,EAAE,CAAC;YACN,MAAM,QAAQ,GAAG,CAAa,CAAC;YAC/B,MAAM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C,CAAC;QAChD,CAAC;QACD,KAAK,iBAAS,CAAC,GAAG,CAAC,CAAC,CAAC;YACnB,OAAO,IAAI,oBAAc,CAAC,iBAAiB,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;QAC5D,CAAC;QACD,KAAK,iBAAS,CAAC,GAAG,CAAC,CAAC,CAAC;YACnB,OAAO,IAAI,oBAAc,CAAC,iBAAiB,CAAC,aAAa,CAAC,WAAW,CAAC,EAAE,GAAG,CAAC,CAAC;QAC/E,CAAC;QACD,KAAK,iBAAS,CAAC,GAAG,CAAC,CAAC,CAAC;YACnB,IAAI,QAAQ,EAAE,CAAC;gBACb,MAAM,KAAK,GAAG,QAAmB,CAAC;gBAClC,MAAM,QAAQ,GAAG,8BAAc,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,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;QACD,KAAK,iBAAS,CAAC,GAAG,CAAC,CAAC,CAAC;YACnB,MAAM,UAAU,GAAG,iBAAiB,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;YAChE,OAAO,IAAI,oBAAc,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;QACrD,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 { StxPoolService } from \"./stx\";\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 case ChainType.STX: {\n const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);\n return new StxPoolService(nodeRpcUrl, params, api);\n }\n }\n}\n"]}
@@ -0,0 +1,21 @@
1
+ import { ChainType } from "../../../chains/chain.enums";
2
+ import { AllbridgeCoreClient } from "../../../client/core-api/core-client-base";
3
+ import { AllbridgeCoreSdkOptions } from "../../../index";
4
+ import { PoolInfo, TokenWithChainDetails } from "../../../tokens-info";
5
+ import { RawStxTransaction } from "../../models";
6
+ import { ChainPoolService, LiquidityPoolsParams, LiquidityPoolsParamsWithAmount, UserBalanceInfo } from "../models";
7
+ export declare class StxPoolService extends ChainPoolService {
8
+ nodeRpcUrl: string;
9
+ params: AllbridgeCoreSdkOptions;
10
+ api: AllbridgeCoreClient;
11
+ chainType: ChainType.STX;
12
+ private P;
13
+ private A;
14
+ private client;
15
+ constructor(nodeRpcUrl: string, params: AllbridgeCoreSdkOptions, api: AllbridgeCoreClient);
16
+ getUserBalanceInfo(accountAddress: string, token: TokenWithChainDetails): Promise<UserBalanceInfo>;
17
+ getPoolInfoFromChain(token: TokenWithChainDetails): Promise<PoolInfo>;
18
+ buildRawTransactionDeposit(params: LiquidityPoolsParamsWithAmount): Promise<RawStxTransaction>;
19
+ buildRawTransactionWithdraw(params: LiquidityPoolsParamsWithAmount): Promise<RawStxTransaction>;
20
+ buildRawTransactionClaimRewards(params: LiquidityPoolsParams): Promise<RawStxTransaction>;
21
+ }
@@ -0,0 +1,141 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StxPoolService = void 0;
4
+ const core_1 = require("@clarigen/core");
5
+ const network_1 = require("@stacks/network");
6
+ const transactions_1 = require("@stacks/transactions");
7
+ const big_js_1 = require("big.js");
8
+ const chain_enums_1 = require("../../../chains/chain.enums");
9
+ const exceptions_1 = require("../../../exceptions");
10
+ const calculation_1 = require("../../../utils/calculation");
11
+ const clarigen_types_1 = require("../../models/stx/clarigen-types");
12
+ const get_token_name_1 = require("../../utils/stx/get-token-name");
13
+ const post_conditions_1 = require("../../utils/stx/post-conditions");
14
+ const models_1 = require("../models");
15
+ class StxPoolService extends models_1.ChainPoolService {
16
+ nodeRpcUrl;
17
+ params;
18
+ api;
19
+ chainType = chain_enums_1.ChainType.STX;
20
+ P = 48;
21
+ A = "20";
22
+ client;
23
+ constructor(nodeRpcUrl, params, api) {
24
+ super();
25
+ this.nodeRpcUrl = nodeRpcUrl;
26
+ this.params = params;
27
+ this.api = api;
28
+ const network = (0, network_1.createNetwork)({
29
+ network: this.params.stxIsTestnet ? "testnet" : "mainnet",
30
+ client: { baseUrl: this.nodeRpcUrl },
31
+ apiKey: this.params.stxHeroApiKey,
32
+ });
33
+ this.client = new core_1.ClarigenClient(network, this.params.stxHeroApiKey);
34
+ }
35
+ async getUserBalanceInfo(accountAddress, token) {
36
+ const pool = (0, core_1.contractFactory)(clarigen_types_1.stacksContracts.pool, token.poolAddress);
37
+ const lpAmount = await this.client.ro(pool.getLpBalance({ user: accountAddress }));
38
+ const rewardDebt = await this.client.ro(pool.getUserRewardDebt({ user: accountAddress }));
39
+ return new models_1.UserBalance({ lpAmount: lpAmount.toString(), rewardDebt: rewardDebt.toString() });
40
+ }
41
+ async getPoolInfoFromChain(token) {
42
+ const pool = (0, core_1.contractFactory)(clarigen_types_1.stacksContracts.pool, token.poolAddress);
43
+ const [dValueRaw, tokenBalanceRaw, vUsdBalanceRaw, totalLpAmountRaw, accRewardPerSharePRaw] = await Promise.all([
44
+ this.client.ro(pool.getD()),
45
+ this.client.ro(pool.getTokenBalance()),
46
+ this.client.ro(pool.getVusdBalance()),
47
+ this.client.ro(pool.getLpTotalSupply()),
48
+ this.client.ro(pool.getAccRewardPerShareP()),
49
+ ]);
50
+ const dValue = dValueRaw.toString();
51
+ const tokenBalance = tokenBalanceRaw.toString();
52
+ const vUsdBalance = vUsdBalanceRaw.toString();
53
+ const totalLpAmount = totalLpAmountRaw.toString();
54
+ const accRewardPerShareP = accRewardPerSharePRaw.toString();
55
+ if (dValue && tokenBalance && vUsdBalance && totalLpAmount && accRewardPerShareP) {
56
+ const imbalance = (0, calculation_1.calculatePoolInfoImbalance)({ tokenBalance, vUsdBalance });
57
+ return {
58
+ aValue: this.A,
59
+ dValue,
60
+ tokenBalance,
61
+ vUsdBalance,
62
+ totalLpAmount,
63
+ accRewardPerShareP,
64
+ p: this.P,
65
+ imbalance,
66
+ };
67
+ }
68
+ throw new exceptions_1.SdkError("Unable to pool info from chain");
69
+ }
70
+ async buildRawTransactionDeposit(params) {
71
+ const pool = (0, core_1.contractFactory)(clarigen_types_1.stacksContracts.pool, params.token.poolAddress);
72
+ const { contractAddress, contractName, functionName, functionArgs } = pool.deposit({
73
+ amount: BigInt(params.amount),
74
+ ftRef: params.token.tokenAddress,
75
+ });
76
+ const privateKey = (0, transactions_1.makeRandomPrivKey)();
77
+ const publicKey = (0, transactions_1.privateKeyToPublic)(privateKey);
78
+ const userPostFungibleCondition = (0, post_conditions_1.getFungiblePostCondition)(params.amount, "lte", params.accountAddress, params.token.tokenAddress, (0, get_token_name_1.getTokenName)(params.token));
79
+ const claimRewardsPostFungibleCondition = (0, post_conditions_1.getFungiblePostCondition)(0, "gte", params.token.poolAddress, params.token.tokenAddress, (0, get_token_name_1.getTokenName)(params.token));
80
+ const txOptions = {
81
+ contractAddress,
82
+ contractName,
83
+ functionName,
84
+ functionArgs,
85
+ publicKey,
86
+ validateWithAbi: true,
87
+ network: this.client.network,
88
+ postConditions: [userPostFungibleCondition, claimRewardsPostFungibleCondition],
89
+ postConditionMode: transactions_1.PostConditionMode.Deny,
90
+ };
91
+ const transaction = await (0, transactions_1.makeUnsignedContractCall)(txOptions);
92
+ return transaction.serialize();
93
+ }
94
+ async buildRawTransactionWithdraw(params) {
95
+ const pool = (0, core_1.contractFactory)(clarigen_types_1.stacksContracts.pool, params.token.poolAddress);
96
+ const { contractAddress, contractName, functionName, functionArgs } = pool.withdraw({
97
+ amountLp: BigInt(params.amount),
98
+ ftRef: params.token.tokenAddress,
99
+ });
100
+ const privateKey = (0, transactions_1.makeRandomPrivKey)();
101
+ const publicKey = (0, transactions_1.privateKeyToPublic)(privateKey);
102
+ const poolPostFungibleCondition = (0, post_conditions_1.getFungiblePostCondition)((0, calculation_1.fromSystemPrecision)(params.amount, params.token.decimals).toFixed(0, big_js_1.Big.roundDown), "gte", params.token.poolAddress, params.token.tokenAddress, (0, get_token_name_1.getTokenName)(params.token));
103
+ const txOptions = {
104
+ contractAddress,
105
+ contractName,
106
+ functionName,
107
+ functionArgs,
108
+ publicKey,
109
+ validateWithAbi: true,
110
+ network: this.client.network,
111
+ postConditions: [poolPostFungibleCondition],
112
+ postConditionMode: transactions_1.PostConditionMode.Deny,
113
+ };
114
+ const transaction = await (0, transactions_1.makeUnsignedContractCall)(txOptions);
115
+ return transaction.serialize();
116
+ }
117
+ async buildRawTransactionClaimRewards(params) {
118
+ const pool = (0, core_1.contractFactory)(clarigen_types_1.stacksContracts.pool, params.token.poolAddress);
119
+ const { contractAddress, contractName, functionName, functionArgs } = pool.claimRewards({
120
+ ftRef: params.token.tokenAddress,
121
+ });
122
+ const privateKey = (0, transactions_1.makeRandomPrivKey)();
123
+ const publicKey = (0, transactions_1.privateKeyToPublic)(privateKey);
124
+ const poolPostFungibleCondition = (0, post_conditions_1.getFungiblePostCondition)(0, "gte", params.token.poolAddress, params.token.tokenAddress, (0, get_token_name_1.getTokenName)(params.token));
125
+ const txOptions = {
126
+ contractAddress,
127
+ contractName,
128
+ functionName,
129
+ functionArgs,
130
+ publicKey,
131
+ validateWithAbi: true,
132
+ network: this.client.network,
133
+ postConditions: [poolPostFungibleCondition],
134
+ postConditionMode: transactions_1.PostConditionMode.Deny,
135
+ };
136
+ const transaction = await (0, transactions_1.makeUnsignedContractCall)(txOptions);
137
+ return transaction.serialize();
138
+ }
139
+ }
140
+ exports.StxPoolService = StxPoolService;
141
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/services/liquidity-pool/stx/index.ts"],"names":[],"mappings":";;;AAAA,yCAAiE;AACjE,6CAAgD;AAChD,uDAK8B;AAC9B,mCAA6B;AAC7B,6DAAwD;AAExD,oDAA+C;AAG/C,4DAA6F;AAE7F,oEAA+E;AAC/E,mEAA8D;AAC9D,qEAA2E;AAC3E,sCAMmB;AAEnB,MAAa,cAAe,SAAQ,yBAAgB;IAQzC;IACA;IACA;IATT,SAAS,GAAkB,uBAAS,CAAC,GAAG,CAAC;IAEjC,CAAC,GAAG,EAAE,CAAC;IACP,CAAC,GAAG,IAAI,CAAC;IACT,MAAM,CAAiB;IAE/B,YACS,UAAkB,EAClB,MAA+B,EAC/B,GAAwB;QAE/B,KAAK,EAAE,CAAC;QAJD,eAAU,GAAV,UAAU,CAAQ;QAClB,WAAM,GAAN,MAAM,CAAyB;QAC/B,QAAG,GAAH,GAAG,CAAqB;QAG/B,MAAM,OAAO,GAAG,IA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YAAY,EAAE,YAAY,EAAE,GAAG,IAAI,CAAC,YAAY,CAAC;YACtF,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,YAAY;SACjC,CAAC,CAAC;QAEH,MAAM,UAAU,GAAG,IAAA,gCAAiB,GAAE,CAAC;QACvC,MAAM,SAAS,GAAG,IAAA,iCAAkB,EAAC,UAAU,CAAC,CAAC;QAEjD,MAAM,yBAAyB,GAAG,IAAA,0CAAwB,EACxD,CAAC,EACD,KAAK,EACL,MAAM,CAAC,KAAK,CAAC,WAAW,EACxB,MAAM,CAAC,KAAK,CAAC,YAAY,EACzB,IAAA,6BAAY,EAAC,MAAM,CAAC,KAAK,CAAC,CAC3B,CAAC;QACF,MAAM,SAAS,GAAG;YAChB,eAAe;YACf,YAAY;YACZ,YAAY;YACZ,YAAY;YACZ,SAAS;YACT,eAAe,EAAE,IAAI;YACrB,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,OAAO;YAC5B,cAAc,EAAE,CAAC,yBAAyB,CAAC;YAC3C,iBAAiB,EAAE,gCAAiB,CAAC,IAAI;SAC1C,CAAC;QACF,MAAM,WAAW,GAAG,MAAM,IAAA,uCAAwB,EAAC,SAAS,CAAC,CAAC;QAC9D,OAAO,WAAW,CAAC,SAAS,EAAE,CAAC;IACjC,CAAC;CACF;AAxKD,wCAwKC","sourcesContent":["import { ClarigenClient, contractFactory } from \"@clarigen/core\";\nimport { createNetwork } from \"@stacks/network\";\nimport {\n makeRandomPrivKey,\n makeUnsignedContractCall,\n PostConditionMode,\n privateKeyToPublic,\n} from \"@stacks/transactions\";\nimport { Big } from \"big.js\";\nimport { ChainType } from \"../../../chains/chain.enums\";\nimport { AllbridgeCoreClient } from \"../../../client/core-api/core-client-base\";\nimport { SdkError } from \"../../../exceptions\";\nimport { AllbridgeCoreSdkOptions } from \"../../../index\";\nimport { PoolInfo, TokenWithChainDetails } from \"../../../tokens-info\";\nimport { calculatePoolInfoImbalance, fromSystemPrecision } from \"../../../utils/calculation\";\nimport { RawStxTransaction } from \"../../models\";\nimport { stacksContracts as contracts } from \"../../models/stx/clarigen-types\";\nimport { getTokenName } from \"../../utils/stx/get-token-name\";\nimport { getFungiblePostCondition } from \"../../utils/stx/post-conditions\";\nimport {\n ChainPoolService,\n LiquidityPoolsParams,\n LiquidityPoolsParamsWithAmount,\n UserBalance,\n UserBalanceInfo,\n} from \"../models\";\n\nexport class StxPoolService extends ChainPoolService {\n chainType: ChainType.STX = ChainType.STX;\n\n private P = 48;\n private A = \"20\";\n private client: ClarigenClient;\n\n constructor(\n public nodeRpcUrl: string,\n public params: AllbridgeCoreSdkOptions,\n public api: AllbridgeCoreClient\n ) {\n super();\n const network = createNetwork({\n network: this.params.stxIsTestnet ? \"testnet\" : \"mainnet\",\n client: { baseUrl: this.nodeRpcUrl },\n apiKey: this.params.stxHeroApiKey,\n });\n this.client = new ClarigenClient(network, this.params.stxHeroApiKey);\n }\n\n async getUserBalanceInfo(accountAddress: string, token: TokenWithChainDetails): Promise<UserBalanceInfo> {\n const pool = contractFactory(contracts.pool, token.poolAddress);\n\n const lpAmount = await this.client.ro(pool.getLpBalance({ user: accountAddress }));\n const rewardDebt = await this.client.ro(pool.getUserRewardDebt({ user: accountAddress }));\n\n return new UserBalance({ lpAmount: lpAmount.toString(), rewardDebt: rewardDebt.toString() });\n }\n\n async getPoolInfoFromChain(token: TokenWithChainDetails): Promise<PoolInfo> {\n const pool = contractFactory(contracts.pool, token.poolAddress);\n\n const [dValueRaw, tokenBalanceRaw, vUsdBalanceRaw, totalLpAmountRaw, accRewardPerSharePRaw] = await Promise.all([\n this.client.ro(pool.getD()),\n this.client.ro(pool.getTokenBalance()),\n this.client.ro(pool.getVusdBalance()),\n this.client.ro(pool.getLpTotalSupply()),\n this.client.ro(pool.getAccRewardPerShareP()),\n ]);\n\n const dValue = dValueRaw.toString();\n const tokenBalance = tokenBalanceRaw.toString();\n const vUsdBalance = vUsdBalanceRaw.toString();\n const totalLpAmount = totalLpAmountRaw.toString();\n const accRewardPerShareP = accRewardPerSharePRaw.toString();\n if (dValue && tokenBalance && vUsdBalance && totalLpAmount && accRewardPerShareP) {\n const imbalance = calculatePoolInfoImbalance({ tokenBalance, vUsdBalance });\n return {\n aValue: this.A,\n dValue,\n tokenBalance,\n vUsdBalance,\n totalLpAmount,\n accRewardPerShareP,\n p: this.P,\n imbalance,\n };\n }\n throw new SdkError(\"Unable to pool info from chain\");\n }\n\n async buildRawTransactionDeposit(params: LiquidityPoolsParamsWithAmount): Promise<RawStxTransaction> {\n const pool = contractFactory(contracts.pool, params.token.poolAddress);\n\n const { contractAddress, contractName, functionName, functionArgs } = pool.deposit({\n amount: BigInt(params.amount),\n ftRef: params.token.tokenAddress,\n });\n\n const privateKey = makeRandomPrivKey();\n const publicKey = privateKeyToPublic(privateKey);\n\n const userPostFungibleCondition = getFungiblePostCondition(\n params.amount,\n \"lte\",\n params.accountAddress,\n params.token.tokenAddress,\n getTokenName(params.token)\n );\n\n const claimRewardsPostFungibleCondition = getFungiblePostCondition(\n 0,\n \"gte\",\n params.token.poolAddress,\n params.token.tokenAddress,\n getTokenName(params.token)\n );\n\n const txOptions = {\n contractAddress,\n contractName,\n functionName,\n functionArgs,\n publicKey,\n validateWithAbi: true,\n network: this.client.network,\n postConditions: [userPostFungibleCondition, claimRewardsPostFungibleCondition],\n postConditionMode: PostConditionMode.Deny,\n };\n const transaction = await makeUnsignedContractCall(txOptions);\n return transaction.serialize();\n }\n\n async buildRawTransactionWithdraw(params: LiquidityPoolsParamsWithAmount): Promise<RawStxTransaction> {\n const pool = contractFactory(contracts.pool, params.token.poolAddress);\n\n const { contractAddress, contractName, functionName, functionArgs } = pool.withdraw({\n amountLp: BigInt(params.amount),\n ftRef: params.token.tokenAddress,\n });\n\n const privateKey = makeRandomPrivKey();\n const publicKey = privateKeyToPublic(privateKey);\n\n const poolPostFungibleCondition = getFungiblePostCondition(\n fromSystemPrecision(params.amount, params.token.decimals).toFixed(0, Big.roundDown),\n \"gte\",\n params.token.poolAddress,\n params.token.tokenAddress,\n getTokenName(params.token)\n );\n const txOptions = {\n contractAddress,\n contractName,\n functionName,\n functionArgs,\n publicKey,\n validateWithAbi: true,\n network: this.client.network,\n postConditions: [poolPostFungibleCondition],\n postConditionMode: PostConditionMode.Deny,\n };\n const transaction = await makeUnsignedContractCall(txOptions);\n return transaction.serialize();\n }\n\n async buildRawTransactionClaimRewards(params: LiquidityPoolsParams): Promise<RawStxTransaction> {\n const pool = contractFactory(contracts.pool, params.token.poolAddress);\n\n const { contractAddress, contractName, functionName, functionArgs } = pool.claimRewards({\n ftRef: params.token.tokenAddress,\n });\n\n const privateKey = makeRandomPrivKey();\n const publicKey = privateKeyToPublic(privateKey);\n\n const poolPostFungibleCondition = getFungiblePostCondition(\n 0,\n \"gte\",\n params.token.poolAddress,\n params.token.tokenAddress,\n getTokenName(params.token)\n );\n const txOptions = {\n contractAddress,\n contractName,\n functionName,\n functionArgs,\n publicKey,\n validateWithAbi: true,\n network: this.client.network,\n postConditions: [poolPostFungibleCondition],\n postConditionMode: PostConditionMode.Deny,\n };\n const transaction = await makeUnsignedContractCall(txOptions);\n return transaction.serialize();\n }\n}\n"]}
@@ -1 +1 @@
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;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,Q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BAAkB,EAC/B,EAAE,CACH,CAAC;QACF,IAAI,YAAY,EAAE,CAAC;YACjB,MAAM,IAAI,+BAAkB,CAAC,kBAAkB,CAAC,CAAC;QACnD,CAAC;QAED,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 { 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}\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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"]}