@ouronet/ouronet-core 4.3.6

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 (101) hide show
  1. package/CHANGELOG.md +3043 -0
  2. package/README.md +1940 -0
  3. package/dist/codex/codec.d.ts +77 -0
  4. package/dist/codex/codec.js +123 -0
  5. package/dist/codex/errors.d.ts +14 -0
  6. package/dist/codex/errors.js +20 -0
  7. package/dist/codex/index.d.ts +27 -0
  8. package/dist/codex/index.js +25 -0
  9. package/dist/codex/seedTypeMigration.d.ts +35 -0
  10. package/dist/codex/seedTypeMigration.js +45 -0
  11. package/dist/codex/types.d.ts +100 -0
  12. package/dist/codex/types.js +19 -0
  13. package/dist/constants/index.d.ts +2 -0
  14. package/dist/constants/index.js +3 -0
  15. package/dist/constants/ouronet.d.ts +33 -0
  16. package/dist/constants/ouronet.js +59 -0
  17. package/dist/constants/tokenIds.d.ts +13 -0
  18. package/dist/constants/tokenIds.js +21 -0
  19. package/dist/index.d.ts +18 -0
  20. package/dist/index.js +1 -0
  21. package/dist/interactions/activateFunctions.d.ts +67 -0
  22. package/dist/interactions/activateFunctions.js +154 -0
  23. package/dist/interactions/addLiquidityFunctions.d.ts +140 -0
  24. package/dist/interactions/addLiquidityFunctions.js +485 -0
  25. package/dist/interactions/coilFunctions.d.ts +73 -0
  26. package/dist/interactions/coilFunctions.js +213 -0
  27. package/dist/interactions/crossChainFunctions.d.ts +211 -0
  28. package/dist/interactions/crossChainFunctions.js +463 -0
  29. package/dist/interactions/dexAcquisitionPoolFunctions.d.ts +18 -0
  30. package/dist/interactions/dexAcquisitionPoolFunctions.js +18 -0
  31. package/dist/interactions/dexCollectablesFunctions.d.ts +28 -0
  32. package/dist/interactions/dexCollectablesFunctions.js +227 -0
  33. package/dist/interactions/dexFunctions.d.ts +23 -0
  34. package/dist/interactions/dexFunctions.js +23 -0
  35. package/dist/interactions/dexOrtoFungibleFunctions.d.ts +33 -0
  36. package/dist/interactions/dexOrtoFungibleFunctions.js +171 -0
  37. package/dist/interactions/dexParseFunctions.d.ts +150 -0
  38. package/dist/interactions/dexParseFunctions.js +316 -0
  39. package/dist/interactions/dexSwapPairAdminFunctions.d.ts +75 -0
  40. package/dist/interactions/dexSwapPairAdminFunctions.js +255 -0
  41. package/dist/interactions/dexSwapPairCalcFunctions.d.ts +55 -0
  42. package/dist/interactions/dexSwapPairCalcFunctions.js +218 -0
  43. package/dist/interactions/dexSwapPairDashboardFunctions.d.ts +47 -0
  44. package/dist/interactions/dexSwapPairDashboardFunctions.js +179 -0
  45. package/dist/interactions/dexSwapPairExecuteFunctions.d.ts +40 -0
  46. package/dist/interactions/dexSwapPairExecuteFunctions.js +301 -0
  47. package/dist/interactions/dexSwapPairSmartSwapFunctions.d.ts +25 -0
  48. package/dist/interactions/dexSwapPairSmartSwapFunctions.js +166 -0
  49. package/dist/interactions/dexTrueFungibleFunctions.d.ts +52 -0
  50. package/dist/interactions/dexTrueFungibleFunctions.js +220 -0
  51. package/dist/interactions/dexTypes.d.ts +465 -0
  52. package/dist/interactions/dexTypes.js +6 -0
  53. package/dist/interactions/errors.d.ts +12 -0
  54. package/dist/interactions/errors.js +13 -0
  55. package/dist/interactions/guardFunctions.d.ts +33 -0
  56. package/dist/interactions/guardFunctions.js +110 -0
  57. package/dist/interactions/index.d.ts +1 -0
  58. package/dist/interactions/index.js +20 -0
  59. package/dist/interactions/infoOneFunctions.d.ts +133 -0
  60. package/dist/interactions/infoOneFunctions.js +566 -0
  61. package/dist/interactions/kadenaFunctions.d.ts +11 -0
  62. package/dist/interactions/kadenaFunctions.js +40 -0
  63. package/dist/interactions/kpayFunctions.d.ts +45 -0
  64. package/dist/interactions/kpayFunctions.js +191 -0
  65. package/dist/interactions/ouroAccountFunctions.d.ts +64 -0
  66. package/dist/interactions/ouroAccountFunctions.js +229 -0
  67. package/dist/interactions/ouroBalanceFunctions.d.ts +39 -0
  68. package/dist/interactions/ouroBalanceFunctions.js +100 -0
  69. package/dist/interactions/ouroCoilFunctions.d.ts +33 -0
  70. package/dist/interactions/ouroCoilFunctions.js +190 -0
  71. package/dist/interactions/ouroFunctions.d.ts +23 -0
  72. package/dist/interactions/ouroFunctions.js +23 -0
  73. package/dist/interactions/ouroMovieBoosterFunctions.d.ts +18 -0
  74. package/dist/interactions/ouroMovieBoosterFunctions.js +203 -0
  75. package/dist/interactions/ouroPriceFunctions.d.ts +38 -0
  76. package/dist/interactions/ouroPriceFunctions.js +96 -0
  77. package/dist/interactions/ouroPrimordialsFunctions.d.ts +10 -0
  78. package/dist/interactions/ouroPrimordialsFunctions.js +480 -0
  79. package/dist/interactions/ouroRotateFunctions.d.ts +22 -0
  80. package/dist/interactions/ouroRotateFunctions.js +114 -0
  81. package/dist/interactions/ouroSubCompressFunctions.d.ts +23 -0
  82. package/dist/interactions/ouroSubCompressFunctions.js +191 -0
  83. package/dist/interactions/ouroTransferFunctions.d.ts +14 -0
  84. package/dist/interactions/ouroTransferFunctions.js +87 -0
  85. package/dist/interactions/ouroTypes.d.ts +113 -0
  86. package/dist/interactions/ouroTypes.js +6 -0
  87. package/dist/interactions/ouroUrStoaFunctions.d.ts +16 -0
  88. package/dist/interactions/ouroUrStoaFunctions.js +121 -0
  89. package/dist/interactions/ouroWrapFunctions.d.ts +22 -0
  90. package/dist/interactions/ouroWrapFunctions.js +234 -0
  91. package/dist/interactions/pensionFunctions.d.ts +12 -0
  92. package/dist/interactions/pensionFunctions.js +127 -0
  93. package/dist/interactions/urStoaFunctions.d.ts +104 -0
  94. package/dist/interactions/urStoaFunctions.js +475 -0
  95. package/dist/interactions/wrapFunctions.d.ts +46 -0
  96. package/dist/interactions/wrapFunctions.js +221 -0
  97. package/dist/pact/cfmBuilders.d.ts +807 -0
  98. package/dist/pact/cfmBuilders.js +812 -0
  99. package/dist/pact/index.d.ts +1 -0
  100. package/dist/pact/index.js +10 -0
  101. package/package.json +64 -0
@@ -0,0 +1,301 @@
1
+ /**
2
+ * dexSwapPairExecuteFunctions.ts
3
+ * Swap pair execution (single/multi pool, with/without slippage protection — TS01-C3 module).
4
+ */
5
+ import { KADENA_CHAIN_ID, KADENA_NAMESPACE, STOA_AUTONOMIC_OURONETGASSTATION, KADENA_NETWORK, } from "../constants/index.js";
6
+ import { Pact } from "@stoachain/kadena-stoic-legacy/client";
7
+ import { getFailoverClient } from "@stoachain/stoa-core/network";
8
+ import { universalSignTransaction, fromKeypair } from "@stoachain/stoa-core/signing";
9
+ import { calculateAutoGasLimit } from "@stoachain/stoa-core/gas";
10
+ import { pactRead } from "@stoachain/stoa-core/reads";
11
+ import { safeCreationTime } from "@stoachain/stoa-core/pact";
12
+ import { getLogger } from "@stoachain/stoa-core/observability";
13
+ /**
14
+ * Fetch slippage bounds object for a swap via dirtyRead.
15
+ * Must be called before executing a swap with slippage protection.
16
+ */
17
+ export async function getSlippageBounds(swpair, inputIds, inputAmounts, outputId, slippage) {
18
+ try {
19
+ const pactInputIds = `[${inputIds.map(id => `"${id}"`).join(' ')}]`;
20
+ const pactInputAmounts = `[${inputAmounts.map(amount => {
21
+ const amountStr = typeof amount === 'string' ? amount : amount.toString();
22
+ return amountStr.includes('.') ? amountStr : `${amountStr}.0`;
23
+ }).join(' ')}]`;
24
+ const slippageStr = slippage.toString();
25
+ const slippageDecimal = slippageStr.includes('.') ? slippageStr : `${slippageStr}.0`;
26
+ const pactCode = `(${KADENA_NAMESPACE}.SWPU.UDC_SpawnSlippageBounds "${swpair}" ${pactInputIds} ${pactInputAmounts} "${outputId}" ${slippageDecimal})`;
27
+ const response = await pactRead(pactCode, { tier: "T2" });
28
+ if (!response || !response.result) {
29
+ throw new Error("Failed to retrieve slippage bounds from the transaction.");
30
+ }
31
+ if (response.result.status === "failure") {
32
+ throw new Error(`Slippage bounds query failed: ${response.result.error?.message || "Unknown error"}`);
33
+ }
34
+ return response.result.data;
35
+ }
36
+ catch (error) {
37
+ throw error instanceof Error ? error : new Error("Unknown error occurred fetching slippage bounds");
38
+ }
39
+ }
40
+ /**
41
+ * Execute single swap with slippage protection
42
+ */
43
+ export async function executeSingleSwapWithSlippage(params) {
44
+ try {
45
+ // Format numbers as decimals for Pact (preserve exact user input, just ensure decimal format)
46
+ const inputAmountStr = typeof params.inputAmount === 'string' ? params.inputAmount : params.inputAmount.toString();
47
+ const inputAmountDecimal = inputAmountStr.includes('.') ? inputAmountStr : `${inputAmountStr}.0`;
48
+ // Fetch slippage bounds object from chain before executing
49
+ const slippageBoundsObj = await getSlippageBounds(params.swpair, [params.inputId], [inputAmountDecimal], params.outputId, params.slippage);
50
+ const pactCode = `(${KADENA_NAMESPACE}.TS01-C3.SWP|C_SingleSwapWithSlippage "${params.patronKeypair.address}" "${params.account}" "${params.swpair}" "${params.inputId}" ${inputAmountDecimal} "${params.outputId}" (read-msg 'slippage-bounds))`;
51
+ // Create keyset name for the guard (following OURO pattern)
52
+ const keysetName = `ks`;
53
+ let gasLimit = 100000; // Default gas limit for swap execution (under block limit)
54
+ // Build transaction function
55
+ const buildTransaction = (gasLimitOverride) => {
56
+ return Pact.builder
57
+ .execution(pactCode)
58
+ .addData(keysetName, {
59
+ keys: [params.guardKeypair.publicKey],
60
+ pred: "keys-all",
61
+ })
62
+ .addData('slippage-bounds', slippageBoundsObj)
63
+ .setMeta({
64
+ senderAccount: STOA_AUTONOMIC_OURONETGASSTATION,
65
+ creationTime: safeCreationTime(),
66
+ chainId: KADENA_CHAIN_ID,
67
+ gasLimit: gasLimitOverride || gasLimit,
68
+ })
69
+ .setNetworkId(KADENA_NETWORK)
70
+ .addSigner(params.kadenaKeypair.publicKey, (withCapability) => [
71
+ withCapability(`${KADENA_NAMESPACE}.DALOS.GAS_PAYER`, "", { int: 0 }, { decimal: "0.0" }),
72
+ ])
73
+ .addSigner(params.guardKeypair.publicKey)
74
+ .createTransaction();
75
+ };
76
+ const { dirtyRead, submit } = getFailoverClient(KADENA_CHAIN_ID);
77
+ // First do a simulation to check gas
78
+ let transaction = buildTransaction();
79
+ const simulation = await dirtyRead(transaction);
80
+ // Check if simulation failed
81
+ if (simulation.result.status === "failure") {
82
+ const errorMessage = simulation.result.error?.message || "Transaction simulation failed";
83
+ throw new Error(`Single swap execution failed: ${errorMessage}`);
84
+ }
85
+ // Apply adaptive gas limit from simulation
86
+ const requiredGas = simulation.gas;
87
+ if (requiredGas) {
88
+ // Rebuild with adaptive gas limit
89
+ gasLimit = calculateAutoGasLimit(requiredGas);
90
+ transaction = buildTransaction(gasLimit);
91
+ }
92
+ // Sign the transaction with both keypairs
93
+ const signedTransaction = await universalSignTransaction(transaction, [
94
+ fromKeypair(params.kadenaKeypair),
95
+ fromKeypair(params.guardKeypair),
96
+ ]);
97
+ // Submit the signed transaction
98
+ const result = await submit(signedTransaction);
99
+ return result;
100
+ }
101
+ catch (error) {
102
+ getLogger().error("Single Swap WITH Slippage Error:", error);
103
+ throw error instanceof Error ? error : new Error("Unknown error occurred");
104
+ }
105
+ }
106
+ /**
107
+ * Execute single swap without slippage protection
108
+ */
109
+ export async function executeSingleSwapNoSlippage(params) {
110
+ try {
111
+ // Format numbers as decimals for Pact (preserve exact user input, just ensure decimal format)
112
+ const inputAmountStr = typeof params.inputAmount === 'string' ? params.inputAmount : params.inputAmount.toString();
113
+ const inputAmountDecimal = inputAmountStr.includes('.') ? inputAmountStr : `${inputAmountStr}.0`;
114
+ const pactCode = `(${KADENA_NAMESPACE}.TS01-C3.SWP|C_SingleSwapNoSlippage "${params.patronKeypair.address}" "${params.account}" "${params.swpair}" "${params.inputId}" ${inputAmountDecimal} "${params.outputId}")`;
115
+ // Create keyset name for the guard (following OURO pattern)
116
+ const keysetName = `ks`;
117
+ let gasLimit = 140000; // Default gas limit for swap execution
118
+ // Build transaction function
119
+ const buildTransaction = (gasLimitOverride) => {
120
+ return Pact.builder
121
+ .execution(pactCode)
122
+ .addData(keysetName, {
123
+ keys: [params.guardKeypair.publicKey],
124
+ pred: "keys-all",
125
+ })
126
+ .setMeta({
127
+ senderAccount: STOA_AUTONOMIC_OURONETGASSTATION,
128
+ creationTime: safeCreationTime(),
129
+ chainId: KADENA_CHAIN_ID,
130
+ gasLimit: gasLimitOverride || gasLimit,
131
+ })
132
+ .setNetworkId(KADENA_NETWORK)
133
+ .addSigner(params.kadenaKeypair.publicKey, (withCapability) => [
134
+ withCapability(`${KADENA_NAMESPACE}.DALOS.GAS_PAYER`, "", { int: 0 }, { decimal: "0.0" }),
135
+ ])
136
+ .addSigner(params.guardKeypair.publicKey)
137
+ .createTransaction();
138
+ };
139
+ const { dirtyRead, submit } = getFailoverClient(KADENA_CHAIN_ID);
140
+ // First do a simulation to check gas
141
+ let transaction = buildTransaction();
142
+ const simulation = await dirtyRead(transaction);
143
+ // Check if simulation failed
144
+ if (simulation.result.status === "failure") {
145
+ const errorMessage = simulation.result.error?.message || "Transaction simulation failed";
146
+ throw new Error(`Single swap execution failed: ${errorMessage}`);
147
+ }
148
+ // Apply adaptive gas limit from simulation
149
+ const requiredGas = simulation.gas;
150
+ if (requiredGas) {
151
+ // Rebuild with adaptive gas limit
152
+ gasLimit = calculateAutoGasLimit(requiredGas);
153
+ transaction = buildTransaction(gasLimit);
154
+ }
155
+ // Sign the transaction with both keypairs
156
+ const signedTransaction = await universalSignTransaction(transaction, [
157
+ fromKeypair(params.kadenaKeypair),
158
+ fromKeypair(params.guardKeypair),
159
+ ]);
160
+ // Submit the signed transaction
161
+ const result = await submit(signedTransaction);
162
+ return result;
163
+ }
164
+ catch (error) {
165
+ throw error instanceof Error ? error : new Error("Unknown error occurred");
166
+ }
167
+ }
168
+ /**
169
+ * Execute multi-token swap with slippage protection
170
+ */
171
+ export async function executeMultiSwapWithSlippage(params) {
172
+ try {
173
+ // Format arrays for Pact with decimals (preserve exact user input as strings)
174
+ const pactInputIds = `[${params.inputIds.map(id => `"${id}"`).join(' ')}]`;
175
+ const formattedAmounts = params.inputAmounts.map(amount => {
176
+ const amountStr = typeof amount === 'string' ? amount : amount.toString();
177
+ return amountStr.includes('.') ? amountStr : `${amountStr}.0`;
178
+ });
179
+ const pactInputAmounts = `[${formattedAmounts.join(' ')}]`;
180
+ // Fetch slippage bounds object from chain before executing
181
+ const slippageBoundsObj = await getSlippageBounds(params.swpair, params.inputIds, formattedAmounts, params.outputId, params.slippage);
182
+ const pactCode = `(${KADENA_NAMESPACE}.TS01-C3.SWP|C_MultiSwapWithSlippage "${params.patronKeypair.address}" "${params.account}" "${params.swpair}" ${pactInputIds} ${pactInputAmounts} "${params.outputId}" (read-msg 'slippage-bounds))`;
183
+ // Create keyset name for the guard (following OURO pattern)
184
+ const keysetName = `ks`;
185
+ let gasLimit = 120000; // Default gas limit for multi-swap execution (under block limit)
186
+ // Build transaction function
187
+ const buildTransaction = (gasLimitOverride) => {
188
+ return Pact.builder
189
+ .execution(pactCode)
190
+ .addData(keysetName, {
191
+ keys: [params.guardKeypair.publicKey],
192
+ pred: "keys-all",
193
+ })
194
+ .addData('slippage-bounds', slippageBoundsObj)
195
+ .setMeta({
196
+ senderAccount: STOA_AUTONOMIC_OURONETGASSTATION,
197
+ creationTime: safeCreationTime(),
198
+ chainId: KADENA_CHAIN_ID,
199
+ gasLimit: gasLimitOverride || gasLimit,
200
+ })
201
+ .setNetworkId(KADENA_NETWORK)
202
+ .addSigner(params.kadenaKeypair.publicKey, (withCapability) => [
203
+ withCapability(`${KADENA_NAMESPACE}.DALOS.GAS_PAYER`, "", { int: 0 }, { decimal: "0.0" }),
204
+ ])
205
+ .addSigner(params.guardKeypair.publicKey)
206
+ .createTransaction();
207
+ };
208
+ const { dirtyRead, submit } = getFailoverClient(KADENA_CHAIN_ID);
209
+ // First do a simulation to check gas
210
+ let transaction = buildTransaction();
211
+ const simulation = await dirtyRead(transaction);
212
+ // Check if simulation failed
213
+ if (simulation.result.status === "failure") {
214
+ const errorMessage = simulation.result.error?.message || "Transaction simulation failed";
215
+ throw new Error(`Multi swap execution failed: ${errorMessage}`);
216
+ }
217
+ // Apply adaptive gas limit from simulation
218
+ const requiredGas = simulation.gas;
219
+ if (requiredGas) {
220
+ // Rebuild with adaptive gas limit
221
+ gasLimit = calculateAutoGasLimit(requiredGas);
222
+ transaction = buildTransaction(gasLimit);
223
+ }
224
+ // Sign the transaction with both keypairs
225
+ const signedTransaction = await universalSignTransaction(transaction, [
226
+ fromKeypair(params.kadenaKeypair),
227
+ fromKeypair(params.guardKeypair),
228
+ ]);
229
+ // Submit the signed transaction
230
+ const result = await submit(signedTransaction);
231
+ return result;
232
+ }
233
+ catch (error) {
234
+ throw error instanceof Error ? error : new Error("Unknown error occurred");
235
+ }
236
+ }
237
+ /**
238
+ * Execute multi-token swap without slippage protection
239
+ */
240
+ export async function executeMultiSwapNoSlippage(params) {
241
+ try {
242
+ // Format arrays for Pact with decimals (preserve exact user input as strings)
243
+ const pactInputIds = `[${params.inputIds.map(id => `"${id}"`).join(' ')}]`;
244
+ const pactInputAmounts = `[${params.inputAmounts.map(amount => {
245
+ const amountStr = typeof amount === 'string' ? amount : amount.toString();
246
+ return amountStr.includes('.') ? amountStr : `${amountStr}.0`;
247
+ }).join(' ')}]`;
248
+ const pactCode = `(${KADENA_NAMESPACE}.TS01-C3.SWP|C_MultiSwapNoSlippage "${params.patronKeypair.address}" "${params.account}" "${params.swpair}" ${pactInputIds} ${pactInputAmounts} "${params.outputId}")`;
249
+ // Create keyset name for the guard (following OURO pattern)
250
+ const keysetName = `ks`;
251
+ let gasLimit = 120000; // Default gas limit for multi-swap execution (under block limit)
252
+ // Build transaction function
253
+ const buildTransaction = (gasLimitOverride) => {
254
+ return Pact.builder
255
+ .execution(pactCode)
256
+ .addData(keysetName, {
257
+ keys: [params.guardKeypair.publicKey],
258
+ pred: "keys-all",
259
+ })
260
+ .setMeta({
261
+ senderAccount: STOA_AUTONOMIC_OURONETGASSTATION,
262
+ creationTime: safeCreationTime(),
263
+ chainId: KADENA_CHAIN_ID,
264
+ gasLimit: gasLimitOverride || gasLimit,
265
+ })
266
+ .setNetworkId(KADENA_NETWORK)
267
+ .addSigner(params.kadenaKeypair.publicKey, (withCapability) => [
268
+ withCapability(`${KADENA_NAMESPACE}.DALOS.GAS_PAYER`, "", { int: 0 }, { decimal: "0.0" }),
269
+ ])
270
+ .addSigner(params.guardKeypair.publicKey)
271
+ .createTransaction();
272
+ };
273
+ const { dirtyRead, submit } = getFailoverClient(KADENA_CHAIN_ID);
274
+ // First do a simulation to check gas
275
+ let transaction = buildTransaction();
276
+ const simulation = await dirtyRead(transaction);
277
+ // Check if simulation failed
278
+ if (simulation.result.status === "failure") {
279
+ const errorMessage = simulation.result.error?.message || "Transaction simulation failed";
280
+ throw new Error(`Multi swap execution failed: ${errorMessage}`);
281
+ }
282
+ // Apply adaptive gas limit from simulation
283
+ const requiredGas = simulation.gas;
284
+ if (requiredGas) {
285
+ // Rebuild with adaptive gas limit
286
+ gasLimit = calculateAutoGasLimit(requiredGas);
287
+ transaction = buildTransaction(gasLimit);
288
+ }
289
+ // Sign the transaction with both keypairs
290
+ const signedTransaction = await universalSignTransaction(transaction, [
291
+ fromKeypair(params.kadenaKeypair),
292
+ fromKeypair(params.guardKeypair),
293
+ ]);
294
+ // Submit the signed transaction
295
+ const result = await submit(signedTransaction);
296
+ return result;
297
+ }
298
+ catch (error) {
299
+ throw error instanceof Error ? error : new Error("Unknown error occurred");
300
+ }
301
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * dexSwapPairSmartSwapFunctions.ts
3
+ * Smart-swap routing and multi-hop execution (URC_Hopper, SWPU.UDC_SpawnSmartSwapSlippageBounds, TS01-C3 SmartSwap).
4
+ */
5
+ import type { SmartSwapHopper, SmartSwapSlippageBounds, SmartSwapExecutionParams } from "./dexTypes.js";
6
+ /**
7
+ * Fetch all tokens available across all pools via SWP.URC_AllPoolTokens
8
+ */
9
+ export declare function getAllPoolTokens(): Promise<string[]>;
10
+ /**
11
+ * Preview a smart swap via SWPI.URC_Hopper
12
+ */
13
+ export declare function getSmartSwapHopper(inputId: string, outputId: string, inputAmount: string | number): Promise<SmartSwapHopper | null>;
14
+ /**
15
+ * Get slippage bounds for a smart swap via SWPU.UDC_SpawnSmartSwapSlippageBounds
16
+ */
17
+ export declare function getSmartSwapSlippageBounds(inputId: string, inputAmount: string | number, outputId: string, slippage: number): Promise<SmartSwapSlippageBounds>;
18
+ /**
19
+ * Execute a smart swap with slippage protection
20
+ */
21
+ export declare function executeSmartSwapWithSlippage(params: SmartSwapExecutionParams): Promise<any>;
22
+ /**
23
+ * Execute a smart swap without slippage protection
24
+ */
25
+ export declare function executeSmartSwapNoSlippage(params: SmartSwapExecutionParams): Promise<any>;
@@ -0,0 +1,166 @@
1
+ /**
2
+ * dexSwapPairSmartSwapFunctions.ts
3
+ * Smart-swap routing and multi-hop execution (URC_Hopper, SWPU.UDC_SpawnSmartSwapSlippageBounds, TS01-C3 SmartSwap).
4
+ */
5
+ import { KADENA_CHAIN_ID, KADENA_NAMESPACE, STOA_AUTONOMIC_OURONETGASSTATION, KADENA_NETWORK, } from "../constants/index.js";
6
+ import { Pact } from "@stoachain/kadena-stoic-legacy/client";
7
+ import { getFailoverClient } from "@stoachain/stoa-core/network";
8
+ import { universalSignTransaction, fromKeypair } from "@stoachain/stoa-core/signing";
9
+ import { calculateAutoGasLimit } from "@stoachain/stoa-core/gas";
10
+ import { pactRead } from "@stoachain/stoa-core/reads";
11
+ import { safeCreationTime } from "@stoachain/stoa-core/pact";
12
+ /**
13
+ * Fetch all tokens available across all pools via SWP.URC_AllPoolTokens
14
+ */
15
+ export async function getAllPoolTokens() {
16
+ try {
17
+ const response = await pactRead(`(${KADENA_NAMESPACE}.SWP.URC_AllPoolTokens)`, { tier: "T7" });
18
+ if (!response || !response.result) {
19
+ throw new Error("Failed to retrieve pool tokens from the transaction.");
20
+ }
21
+ if (response.result.status === "failure") {
22
+ throw new Error(`Pool tokens query failed: ${response.result.error?.message || "Unknown error"}`);
23
+ }
24
+ const data = response.result.data;
25
+ return Array.isArray(data) ? data : [];
26
+ }
27
+ catch (error) {
28
+ throw error instanceof Error ? error : new Error("Unknown error occurred");
29
+ }
30
+ }
31
+ /**
32
+ * Preview a smart swap via SWPI.URC_Hopper
33
+ */
34
+ export async function getSmartSwapHopper(inputId, outputId, inputAmount) {
35
+ try {
36
+ const amountStr = typeof inputAmount === "string" ? inputAmount : inputAmount.toString();
37
+ const amountDecimal = amountStr.includes(".") ? amountStr : `${amountStr}.0`;
38
+ const pactCode = `(${KADENA_NAMESPACE}.SWPI.URC_Hopper "${inputId}" "${outputId}" ${amountDecimal})`;
39
+ const response = await pactRead(pactCode, { tier: "T2" });
40
+ if (!response || !response.result) {
41
+ throw new Error("Failed to retrieve smart swap hopper from the transaction.");
42
+ }
43
+ if (response.result.status === "failure") {
44
+ throw new Error(`Smart swap hopper query failed: ${response.result.error?.message || "Unknown error"}`);
45
+ }
46
+ return response.result.data;
47
+ }
48
+ catch (error) {
49
+ throw error instanceof Error ? error : new Error("Unknown error occurred");
50
+ }
51
+ }
52
+ /**
53
+ * Get slippage bounds for a smart swap via SWPU.UDC_SpawnSmartSwapSlippageBounds
54
+ */
55
+ export async function getSmartSwapSlippageBounds(inputId, inputAmount, outputId, slippage) {
56
+ try {
57
+ const amountStr = typeof inputAmount === "string" ? inputAmount : inputAmount.toString();
58
+ const amountDecimal = amountStr.includes(".") ? amountStr : `${amountStr}.0`;
59
+ const slippageStr = slippage.toString();
60
+ const slippageDecimal = slippageStr.includes(".") ? slippageStr : `${slippageStr}.0`;
61
+ const pactCode = `(${KADENA_NAMESPACE}.SWPU.UDC_SpawnSmartSwapSlippageBounds "${inputId}" ${amountDecimal} "${outputId}" ${slippageDecimal})`;
62
+ const response = await pactRead(pactCode, { tier: "T2" });
63
+ if (!response || !response.result) {
64
+ throw new Error("Failed to retrieve smart swap slippage bounds.");
65
+ }
66
+ if (response.result.status === "failure") {
67
+ throw new Error(`Smart swap slippage bounds failed: ${response.result.error?.message || "Unknown error"}`);
68
+ }
69
+ return response.result.data;
70
+ }
71
+ catch (error) {
72
+ throw error instanceof Error ? error : new Error("Unknown error occurred");
73
+ }
74
+ }
75
+ /**
76
+ * Execute a smart swap with slippage protection
77
+ */
78
+ export async function executeSmartSwapWithSlippage(params) {
79
+ try {
80
+ const amountStr = typeof params.inputAmount === "string" ? params.inputAmount : params.inputAmount.toString();
81
+ const amountDecimal = amountStr.includes(".") ? amountStr : `${amountStr}.0`;
82
+ const slippage = params.slippage ?? 5;
83
+ // Fetch slippage bounds before executing
84
+ const slippageObj = await getSmartSwapSlippageBounds(params.inputId, amountDecimal, params.outputId, slippage);
85
+ const pactCode = `(${KADENA_NAMESPACE}.TS01-C3.SWP|C_SmartSwapWithSlippage "${params.patronKeypair.address}" "${params.account}" "${params.inputId}" ${amountDecimal} "${params.outputId}" (read-msg 'slippage-bounds))`;
86
+ const gasLimit = 1500000;
87
+ const buildTx = (gasLimitOverride) => Pact.builder
88
+ .execution(pactCode)
89
+ .addData("ks", {
90
+ keys: [params.guardKeypair.publicKey],
91
+ pred: "keys-all",
92
+ })
93
+ .addData("slippage-bounds", slippageObj)
94
+ .setMeta({
95
+ senderAccount: STOA_AUTONOMIC_OURONETGASSTATION,
96
+ creationTime: safeCreationTime(),
97
+ chainId: KADENA_CHAIN_ID,
98
+ gasLimit: gasLimitOverride ?? gasLimit,
99
+ })
100
+ .setNetworkId(KADENA_NETWORK)
101
+ .addSigner(params.kadenaKeypair.publicKey, (withCapability) => [
102
+ withCapability(`${KADENA_NAMESPACE}.DALOS.GAS_PAYER`, "", { int: 0 }, { decimal: "0.0" }),
103
+ ])
104
+ .addSigner(params.guardKeypair.publicKey)
105
+ .createTransaction();
106
+ const { dirtyRead, submit } = getFailoverClient(KADENA_CHAIN_ID);
107
+ const simulation = await dirtyRead(buildTx());
108
+ if (simulation.result.status === "failure") {
109
+ throw new Error(`Smart swap simulation failed: ${simulation.result.error?.message || "Unknown error"}`);
110
+ }
111
+ const finalGas = simulation.gas ? calculateAutoGasLimit(simulation.gas) : gasLimit;
112
+ const tx = buildTx(finalGas);
113
+ const signedTx = await universalSignTransaction(tx, [
114
+ fromKeypair(params.kadenaKeypair),
115
+ fromKeypair(params.guardKeypair),
116
+ ]);
117
+ return await submit(signedTx);
118
+ }
119
+ catch (error) {
120
+ throw error instanceof Error ? error : new Error("Unknown error occurred");
121
+ }
122
+ }
123
+ /**
124
+ * Execute a smart swap without slippage protection
125
+ */
126
+ export async function executeSmartSwapNoSlippage(params) {
127
+ try {
128
+ const amountStr = typeof params.inputAmount === "string" ? params.inputAmount : params.inputAmount.toString();
129
+ const amountDecimal = amountStr.includes(".") ? amountStr : `${amountStr}.0`;
130
+ const pactCode = `(${KADENA_NAMESPACE}.TS01-C3.SWP|C_SmartSwapNoSlippage "${params.patronKeypair.address}" "${params.account}" "${params.inputId}" ${amountDecimal} "${params.outputId}")`;
131
+ const gasLimit = 1500000;
132
+ const buildTx = (gasLimitOverride) => Pact.builder
133
+ .execution(pactCode)
134
+ .addData("ks", {
135
+ keys: [params.guardKeypair.publicKey],
136
+ pred: "keys-all",
137
+ })
138
+ .setMeta({
139
+ senderAccount: STOA_AUTONOMIC_OURONETGASSTATION,
140
+ creationTime: safeCreationTime(),
141
+ chainId: KADENA_CHAIN_ID,
142
+ gasLimit: gasLimitOverride ?? gasLimit,
143
+ })
144
+ .setNetworkId(KADENA_NETWORK)
145
+ .addSigner(params.kadenaKeypair.publicKey, (withCapability) => [
146
+ withCapability(`${KADENA_NAMESPACE}.DALOS.GAS_PAYER`, "", { int: 0 }, { decimal: "0.0" }),
147
+ ])
148
+ .addSigner(params.guardKeypair.publicKey)
149
+ .createTransaction();
150
+ const { dirtyRead, submit } = getFailoverClient(KADENA_CHAIN_ID);
151
+ const simulation = await dirtyRead(buildTx());
152
+ if (simulation.result.status === "failure") {
153
+ throw new Error(`Smart swap simulation failed: ${simulation.result.error?.message || "Unknown error"}`);
154
+ }
155
+ const finalGas = simulation.gas ? calculateAutoGasLimit(simulation.gas) : gasLimit;
156
+ const tx = buildTx(finalGas);
157
+ const signedTx = await universalSignTransaction(tx, [
158
+ fromKeypair(params.kadenaKeypair),
159
+ fromKeypair(params.guardKeypair),
160
+ ]);
161
+ return await submit(signedTx);
162
+ }
163
+ catch (error) {
164
+ throw error instanceof Error ? error : new Error("Unknown error occurred");
165
+ }
166
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * dexTrueFungibleFunctions.ts
3
+ * True Fungible (TF) entity reads — LP entries, header, entries, native/frozen LP, button state, swpair lookup.
4
+ */
5
+ import type { TrueFungibleLPEntry, TrueFungibleHeaderData, TrueFungibleEntryData, TrueFungibleButtonState } from "./dexTypes.js";
6
+ export declare function getTrueFungibleLPEntry(account: string, swpair: string, izNative: boolean): Promise<TrueFungibleLPEntry | null>;
7
+ export declare function getLPEntries(account: string, swpair: string): Promise<{
8
+ native: TrueFungibleLPEntry | null;
9
+ frozen: TrueFungibleLPEntry | null;
10
+ }>;
11
+ /**
12
+ * Fetch swap pairs owned by a specific Ouronet resident account.
13
+ * Returns a list of swpair IDs that the account can manage.
14
+ */
15
+ export declare function getOwnedSwapPairs(account: string): Promise<string[]>;
16
+ /**
17
+ * Fetch True Fungible header data for an account.
18
+ * Returns global TF count, held TF list/count, managed TF list/count.
19
+ */
20
+ export declare function getTrueFungibleHeader(account: string): Promise<TrueFungibleHeaderData | null>;
21
+ /**
22
+ * Batch-fetch TrueFungibleEntry data for multiple token IDs using the chain mapper function.
23
+ * Works for Native, Frozen, and Reserved tokens (not LP).
24
+ * Uses URC_0008a_TrueFungibleEntryMapper(account, dptfs:[string])
25
+ */
26
+ export declare function getTrueFungibleEntries(account: string, tokenIds: string[]): Promise<(TrueFungibleEntryData | null)[]>;
27
+ /**
28
+ * Batch-fetch Native LP entry data using the chain mapper function.
29
+ * Uses URC_0008b_TrueFungibleNativeLPMapper(account, lp-ids:[string])
30
+ * Accepts LP token IDs directly — chain resolves swpairs internally.
31
+ */
32
+ export declare function getNativeLPEntries(account: string, lpIds: string[]): Promise<(TrueFungibleLPEntry | null)[]>;
33
+ /**
34
+ * Batch-fetch Frozen LP entry data using the chain mapper function.
35
+ * Uses URC_0008b_TrueFungibleFrozenLPMapper(account, lp-ids:[string])
36
+ * Accepts LP token IDs directly — chain resolves swpairs internally.
37
+ */
38
+ export declare function getFrozenLPEntries(account: string, lpIds: string[]): Promise<(TrueFungibleLPEntry | null)[]>;
39
+ /**
40
+ * Get the SWP-Pair ID from an LP token ID.
41
+ * Uses SWP.UR_GetLpSwpair on chain.
42
+ */
43
+ export declare function getSwpairFromLpId(lpId: string): Promise<string | null>;
44
+ /**
45
+ * Batch-fetch SWP-Pair IDs for multiple LP token IDs using a single Pact (map ...) call.
46
+ */
47
+ export declare function getSwpairsFromLpIds(lpIds: string[]): Promise<(string | null)[]>;
48
+ /**
49
+ * Fetch button enable/disable state for a specific token held by an account.
50
+ * Uses URC_0017_TruefungibleButton(account, dptf)
51
+ */
52
+ export declare function getTrueFungibleButtonState(account: string, dptfId: string): Promise<TrueFungibleButtonState | null>;