@reown/appkit-core-react-native 0.0.0-accounts-canary.1-20251023174733

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 (234) hide show
  1. package/lib/commonjs/controllers/ApiController.js +410 -0
  2. package/lib/commonjs/controllers/ApiController.js.map +1 -0
  3. package/lib/commonjs/controllers/AssetController.js +30 -0
  4. package/lib/commonjs/controllers/AssetController.js.map +1 -0
  5. package/lib/commonjs/controllers/BlockchainApiController.js +384 -0
  6. package/lib/commonjs/controllers/BlockchainApiController.js.map +1 -0
  7. package/lib/commonjs/controllers/ConnectionsController.js +425 -0
  8. package/lib/commonjs/controllers/ConnectionsController.js.map +1 -0
  9. package/lib/commonjs/controllers/EnsController.js +37 -0
  10. package/lib/commonjs/controllers/EnsController.js.map +1 -0
  11. package/lib/commonjs/controllers/EventsController.js +122 -0
  12. package/lib/commonjs/controllers/EventsController.js.map +1 -0
  13. package/lib/commonjs/controllers/LogController.js +188 -0
  14. package/lib/commonjs/controllers/LogController.js.map +1 -0
  15. package/lib/commonjs/controllers/ModalController.js +68 -0
  16. package/lib/commonjs/controllers/ModalController.js.map +1 -0
  17. package/lib/commonjs/controllers/OnRampController.js +502 -0
  18. package/lib/commonjs/controllers/OnRampController.js.map +1 -0
  19. package/lib/commonjs/controllers/OptionsController.js +96 -0
  20. package/lib/commonjs/controllers/OptionsController.js.map +1 -0
  21. package/lib/commonjs/controllers/PublicStateController.js +33 -0
  22. package/lib/commonjs/controllers/PublicStateController.js.map +1 -0
  23. package/lib/commonjs/controllers/RouterController.js +63 -0
  24. package/lib/commonjs/controllers/RouterController.js.map +1 -0
  25. package/lib/commonjs/controllers/SendController.js +192 -0
  26. package/lib/commonjs/controllers/SendController.js.map +1 -0
  27. package/lib/commonjs/controllers/SnackController.js +83 -0
  28. package/lib/commonjs/controllers/SnackController.js.map +1 -0
  29. package/lib/commonjs/controllers/SwapController.js +674 -0
  30. package/lib/commonjs/controllers/SwapController.js.map +1 -0
  31. package/lib/commonjs/controllers/ThemeController.js +45 -0
  32. package/lib/commonjs/controllers/ThemeController.js.map +1 -0
  33. package/lib/commonjs/controllers/TransactionsController.js +118 -0
  34. package/lib/commonjs/controllers/TransactionsController.js.map +1 -0
  35. package/lib/commonjs/controllers/WcController.js +73 -0
  36. package/lib/commonjs/controllers/WcController.js.map +1 -0
  37. package/lib/commonjs/features/reown-authentication/ReownAuthentication.js +272 -0
  38. package/lib/commonjs/features/reown-authentication/ReownAuthentication.js.map +1 -0
  39. package/lib/commonjs/features/reown-authentication/ReownAuthenticationMessenger.js +48 -0
  40. package/lib/commonjs/features/reown-authentication/ReownAuthenticationMessenger.js.map +1 -0
  41. package/lib/commonjs/features/reown-authentication/index.js +28 -0
  42. package/lib/commonjs/features/reown-authentication/index.js.map +1 -0
  43. package/lib/commonjs/index.js +202 -0
  44. package/lib/commonjs/index.js.map +1 -0
  45. package/lib/commonjs/package.json +1 -0
  46. package/lib/commonjs/utils/ApiUtil.js +43 -0
  47. package/lib/commonjs/utils/ApiUtil.js.map +1 -0
  48. package/lib/commonjs/utils/AssetUtil.js +27 -0
  49. package/lib/commonjs/utils/AssetUtil.js.map +1 -0
  50. package/lib/commonjs/utils/ConstantsUtil.js +226 -0
  51. package/lib/commonjs/utils/ConstantsUtil.js.map +1 -0
  52. package/lib/commonjs/utils/CoreHelperUtil.js +298 -0
  53. package/lib/commonjs/utils/CoreHelperUtil.js.map +1 -0
  54. package/lib/commonjs/utils/EventUtil.js +25 -0
  55. package/lib/commonjs/utils/EventUtil.js.map +1 -0
  56. package/lib/commonjs/utils/FetchUtil.js +158 -0
  57. package/lib/commonjs/utils/FetchUtil.js.map +1 -0
  58. package/lib/commonjs/utils/LogUtils.js +131 -0
  59. package/lib/commonjs/utils/LogUtils.js.map +1 -0
  60. package/lib/commonjs/utils/StorageUtil.js +319 -0
  61. package/lib/commonjs/utils/StorageUtil.js.map +1 -0
  62. package/lib/commonjs/utils/SwapApiUtil.js +75 -0
  63. package/lib/commonjs/utils/SwapApiUtil.js.map +1 -0
  64. package/lib/commonjs/utils/SwapCalculationUtil.js +97 -0
  65. package/lib/commonjs/utils/SwapCalculationUtil.js.map +1 -0
  66. package/lib/commonjs/utils/WalletUtil.js +23 -0
  67. package/lib/commonjs/utils/WalletUtil.js.map +1 -0
  68. package/lib/module/controllers/ApiController.js +407 -0
  69. package/lib/module/controllers/ApiController.js.map +1 -0
  70. package/lib/module/controllers/AssetController.js +27 -0
  71. package/lib/module/controllers/AssetController.js.map +1 -0
  72. package/lib/module/controllers/BlockchainApiController.js +381 -0
  73. package/lib/module/controllers/BlockchainApiController.js.map +1 -0
  74. package/lib/module/controllers/ConnectionsController.js +422 -0
  75. package/lib/module/controllers/ConnectionsController.js.map +1 -0
  76. package/lib/module/controllers/EnsController.js +34 -0
  77. package/lib/module/controllers/EnsController.js.map +1 -0
  78. package/lib/module/controllers/EventsController.js +118 -0
  79. package/lib/module/controllers/EventsController.js.map +1 -0
  80. package/lib/module/controllers/LogController.js +185 -0
  81. package/lib/module/controllers/LogController.js.map +1 -0
  82. package/lib/module/controllers/ModalController.js +65 -0
  83. package/lib/module/controllers/ModalController.js.map +1 -0
  84. package/lib/module/controllers/OnRampController.js +499 -0
  85. package/lib/module/controllers/OnRampController.js.map +1 -0
  86. package/lib/module/controllers/OptionsController.js +93 -0
  87. package/lib/module/controllers/OptionsController.js.map +1 -0
  88. package/lib/module/controllers/PublicStateController.js +30 -0
  89. package/lib/module/controllers/PublicStateController.js.map +1 -0
  90. package/lib/module/controllers/RouterController.js +60 -0
  91. package/lib/module/controllers/RouterController.js.map +1 -0
  92. package/lib/module/controllers/SendController.js +189 -0
  93. package/lib/module/controllers/SendController.js.map +1 -0
  94. package/lib/module/controllers/SnackController.js +80 -0
  95. package/lib/module/controllers/SnackController.js.map +1 -0
  96. package/lib/module/controllers/SwapController.js +671 -0
  97. package/lib/module/controllers/SwapController.js.map +1 -0
  98. package/lib/module/controllers/ThemeController.js +42 -0
  99. package/lib/module/controllers/ThemeController.js.map +1 -0
  100. package/lib/module/controllers/TransactionsController.js +115 -0
  101. package/lib/module/controllers/TransactionsController.js.map +1 -0
  102. package/lib/module/controllers/WcController.js +70 -0
  103. package/lib/module/controllers/WcController.js.map +1 -0
  104. package/lib/module/features/reown-authentication/ReownAuthentication.js +268 -0
  105. package/lib/module/features/reown-authentication/ReownAuthentication.js.map +1 -0
  106. package/lib/module/features/reown-authentication/ReownAuthenticationMessenger.js +43 -0
  107. package/lib/module/features/reown-authentication/ReownAuthenticationMessenger.js.map +1 -0
  108. package/lib/module/features/reown-authentication/index.js +5 -0
  109. package/lib/module/features/reown-authentication/index.js.map +1 -0
  110. package/lib/module/index.js +38 -0
  111. package/lib/module/index.js.map +1 -0
  112. package/lib/module/utils/ApiUtil.js +39 -0
  113. package/lib/module/utils/ApiUtil.js.map +1 -0
  114. package/lib/module/utils/AssetUtil.js +23 -0
  115. package/lib/module/utils/AssetUtil.js.map +1 -0
  116. package/lib/module/utils/ConstantsUtil.js +222 -0
  117. package/lib/module/utils/ConstantsUtil.js.map +1 -0
  118. package/lib/module/utils/CoreHelperUtil.js +294 -0
  119. package/lib/module/utils/CoreHelperUtil.js.map +1 -0
  120. package/lib/module/utils/EventUtil.js +21 -0
  121. package/lib/module/utils/EventUtil.js.map +1 -0
  122. package/lib/module/utils/FetchUtil.js +154 -0
  123. package/lib/module/utils/FetchUtil.js.map +1 -0
  124. package/lib/module/utils/LogUtils.js +121 -0
  125. package/lib/module/utils/LogUtils.js.map +1 -0
  126. package/lib/module/utils/StorageUtil.js +315 -0
  127. package/lib/module/utils/StorageUtil.js.map +1 -0
  128. package/lib/module/utils/SwapApiUtil.js +71 -0
  129. package/lib/module/utils/SwapApiUtil.js.map +1 -0
  130. package/lib/module/utils/SwapCalculationUtil.js +94 -0
  131. package/lib/module/utils/SwapCalculationUtil.js.map +1 -0
  132. package/lib/module/utils/WalletUtil.js +19 -0
  133. package/lib/module/utils/WalletUtil.js.map +1 -0
  134. package/lib/typescript/controllers/ApiController.d.ts +40 -0
  135. package/lib/typescript/controllers/ApiController.d.ts.map +1 -0
  136. package/lib/typescript/controllers/AssetController.d.ts +12 -0
  137. package/lib/typescript/controllers/AssetController.d.ts.map +1 -0
  138. package/lib/typescript/controllers/BlockchainApiController.d.ts +55 -0
  139. package/lib/typescript/controllers/BlockchainApiController.d.ts.map +1 -0
  140. package/lib/typescript/controllers/ConnectionsController.d.ts +47 -0
  141. package/lib/typescript/controllers/ConnectionsController.d.ts.map +1 -0
  142. package/lib/typescript/controllers/EnsController.d.ts +10 -0
  143. package/lib/typescript/controllers/EnsController.d.ts.map +1 -0
  144. package/lib/typescript/controllers/EventsController.d.ts +25 -0
  145. package/lib/typescript/controllers/EventsController.d.ts.map +1 -0
  146. package/lib/typescript/controllers/LogController.d.ts +65 -0
  147. package/lib/typescript/controllers/LogController.d.ts.map +1 -0
  148. package/lib/typescript/controllers/ModalController.d.ts +17 -0
  149. package/lib/typescript/controllers/ModalController.d.ts.map +1 -0
  150. package/lib/typescript/controllers/OnRampController.d.ts +55 -0
  151. package/lib/typescript/controllers/OnRampController.d.ts.map +1 -0
  152. package/lib/typescript/controllers/OptionsController.d.ts +46 -0
  153. package/lib/typescript/controllers/OptionsController.d.ts.map +1 -0
  154. package/lib/typescript/controllers/PublicStateController.d.ts +12 -0
  155. package/lib/typescript/controllers/PublicStateController.d.ts.map +1 -0
  156. package/lib/typescript/controllers/RouterController.d.ts +21 -0
  157. package/lib/typescript/controllers/RouterController.d.ts.map +1 -0
  158. package/lib/typescript/controllers/SendController.d.ts +39 -0
  159. package/lib/typescript/controllers/SendController.d.ts.map +1 -0
  160. package/lib/typescript/controllers/SnackController.d.ts +20 -0
  161. package/lib/typescript/controllers/SnackController.d.ts.map +1 -0
  162. package/lib/typescript/controllers/SwapController.d.ts +116 -0
  163. package/lib/typescript/controllers/SwapController.d.ts.map +1 -0
  164. package/lib/typescript/controllers/ThemeController.d.ts +14 -0
  165. package/lib/typescript/controllers/ThemeController.d.ts.map +1 -0
  166. package/lib/typescript/controllers/TransactionsController.d.ts +21 -0
  167. package/lib/typescript/controllers/TransactionsController.d.ts.map +1 -0
  168. package/lib/typescript/controllers/WcController.d.ts +27 -0
  169. package/lib/typescript/controllers/WcController.d.ts.map +1 -0
  170. package/lib/typescript/features/reown-authentication/ReownAuthentication.d.ts +174 -0
  171. package/lib/typescript/features/reown-authentication/ReownAuthentication.d.ts.map +1 -0
  172. package/lib/typescript/features/reown-authentication/ReownAuthenticationMessenger.d.ts +16 -0
  173. package/lib/typescript/features/reown-authentication/ReownAuthenticationMessenger.d.ts.map +1 -0
  174. package/lib/typescript/features/reown-authentication/index.d.ts +3 -0
  175. package/lib/typescript/features/reown-authentication/index.d.ts.map +1 -0
  176. package/lib/typescript/index.d.ts +29 -0
  177. package/lib/typescript/index.d.ts.map +1 -0
  178. package/lib/typescript/utils/ApiUtil.d.ts +7 -0
  179. package/lib/typescript/utils/ApiUtil.d.ts.map +1 -0
  180. package/lib/typescript/utils/AssetUtil.d.ts +6 -0
  181. package/lib/typescript/utils/AssetUtil.d.ts.map +1 -0
  182. package/lib/typescript/utils/ConstantsUtil.d.ts +79 -0
  183. package/lib/typescript/utils/ConstantsUtil.d.ts.map +1 -0
  184. package/lib/typescript/utils/CoreHelperUtil.d.ts +43 -0
  185. package/lib/typescript/utils/CoreHelperUtil.d.ts.map +1 -0
  186. package/lib/typescript/utils/EventUtil.d.ts +5 -0
  187. package/lib/typescript/utils/EventUtil.d.ts.map +1 -0
  188. package/lib/typescript/utils/FetchUtil.d.ts +29 -0
  189. package/lib/typescript/utils/FetchUtil.d.ts.map +1 -0
  190. package/lib/typescript/utils/LogUtils.d.ts +15 -0
  191. package/lib/typescript/utils/LogUtils.d.ts.map +1 -0
  192. package/lib/typescript/utils/StorageUtil.d.ts +36 -0
  193. package/lib/typescript/utils/StorageUtil.d.ts.map +1 -0
  194. package/lib/typescript/utils/SwapApiUtil.d.ts +11 -0
  195. package/lib/typescript/utils/SwapApiUtil.d.ts.map +1 -0
  196. package/lib/typescript/utils/SwapCalculationUtil.d.ts +24 -0
  197. package/lib/typescript/utils/SwapCalculationUtil.d.ts.map +1 -0
  198. package/lib/typescript/utils/WalletUtil.d.ts +5 -0
  199. package/lib/typescript/utils/WalletUtil.d.ts.map +1 -0
  200. package/package.json +57 -0
  201. package/readme.md +9 -0
  202. package/src/controllers/ApiController.ts +454 -0
  203. package/src/controllers/AssetController.ts +32 -0
  204. package/src/controllers/BlockchainApiController.ts +418 -0
  205. package/src/controllers/ConnectionsController.ts +575 -0
  206. package/src/controllers/EnsController.ts +41 -0
  207. package/src/controllers/EventsController.ts +146 -0
  208. package/src/controllers/LogController.ts +250 -0
  209. package/src/controllers/ModalController.ts +68 -0
  210. package/src/controllers/OnRampController.ts +698 -0
  211. package/src/controllers/OptionsController.ts +143 -0
  212. package/src/controllers/PublicStateController.ts +37 -0
  213. package/src/controllers/RouterController.ts +112 -0
  214. package/src/controllers/SendController.ts +270 -0
  215. package/src/controllers/SnackController.ts +95 -0
  216. package/src/controllers/SwapController.ts +863 -0
  217. package/src/controllers/ThemeController.ts +47 -0
  218. package/src/controllers/TransactionsController.ts +150 -0
  219. package/src/controllers/WcController.ts +93 -0
  220. package/src/features/reown-authentication/ReownAuthentication.ts +475 -0
  221. package/src/features/reown-authentication/ReownAuthenticationMessenger.ts +80 -0
  222. package/src/features/reown-authentication/index.ts +2 -0
  223. package/src/index.ts +70 -0
  224. package/src/utils/ApiUtil.ts +50 -0
  225. package/src/utils/AssetUtil.ts +27 -0
  226. package/src/utils/ConstantsUtil.ts +303 -0
  227. package/src/utils/CoreHelperUtil.ts +377 -0
  228. package/src/utils/EventUtil.ts +22 -0
  229. package/src/utils/FetchUtil.ts +164 -0
  230. package/src/utils/LogUtils.ts +179 -0
  231. package/src/utils/StorageUtil.ts +405 -0
  232. package/src/utils/SwapApiUtil.ts +101 -0
  233. package/src/utils/SwapCalculationUtil.ts +145 -0
  234. package/src/utils/WalletUtil.ts +14 -0
@@ -0,0 +1,671 @@
1
+ "use strict";
2
+
3
+ import { subscribeKey as subKey } from 'valtio/utils';
4
+ import { proxy, subscribe as sub } from 'valtio';
5
+ import { NumberUtil } from '@reown/appkit-common-react-native';
6
+ import { ConstantsUtil } from '../utils/ConstantsUtil';
7
+ import { SwapApiUtil } from '../utils/SwapApiUtil';
8
+ import { BlockchainApiController } from './BlockchainApiController';
9
+ import { OptionsController } from './OptionsController';
10
+ import { SwapCalculationUtil } from '../utils/SwapCalculationUtil';
11
+ import { SnackController } from './SnackController';
12
+ import { LogController } from './LogController';
13
+ import { RouterController } from './RouterController';
14
+ import { CoreHelperUtil } from '../utils/CoreHelperUtil';
15
+ import { TransactionsController } from './TransactionsController';
16
+ import { EventsController } from './EventsController';
17
+ import { ConnectionsController } from './ConnectionsController';
18
+
19
+ // -- Constants ---------------------------------------- //
20
+ export const INITIAL_GAS_LIMIT = 150000;
21
+ export const TO_AMOUNT_DECIMALS = 6;
22
+
23
+ // -- Types --------------------------------------------- //
24
+
25
+ class TransactionError extends Error {
26
+ constructor(message, shortMessage) {
27
+ super(message);
28
+ this.name = 'TransactionError';
29
+ this.shortMessage = shortMessage;
30
+ }
31
+ }
32
+ // -- State --------------------------------------------- //
33
+ const initialState = {
34
+ // Loading states
35
+ loadingTokens: false,
36
+ loadingPrices: false,
37
+ loadingQuote: false,
38
+ loadingApprovalTransaction: false,
39
+ loadingBuildTransaction: false,
40
+ loadingTransaction: false,
41
+ // Error states
42
+ fetchError: false,
43
+ // Approval & Swap transaction states
44
+ approvalTransaction: undefined,
45
+ swapTransaction: undefined,
46
+ transactionError: undefined,
47
+ // Input values
48
+ sourceToken: undefined,
49
+ sourceTokenAmount: '',
50
+ sourceTokenPriceInUSD: 0,
51
+ toToken: undefined,
52
+ toTokenAmount: '',
53
+ toTokenPriceInUSD: 0,
54
+ networkPrice: '0',
55
+ networkTokenSymbol: '',
56
+ inputError: undefined,
57
+ // Request values
58
+ slippage: ConstantsUtil.CONVERT_SLIPPAGE_TOLERANCE,
59
+ // Tokens
60
+ tokens: undefined,
61
+ popularTokens: undefined,
62
+ suggestedTokens: undefined,
63
+ foundTokens: undefined,
64
+ myTokensWithBalance: undefined,
65
+ tokensPriceMap: {},
66
+ // Calculations
67
+ gasFee: '0',
68
+ gasPriceInUSD: 0,
69
+ priceImpact: undefined,
70
+ maxSlippage: undefined,
71
+ providerFee: undefined
72
+ };
73
+ const state = proxy({
74
+ ...initialState
75
+ });
76
+
77
+ // -- Controller ---------------------------------------- //
78
+ export const SwapController = {
79
+ state,
80
+ subscribe(callback) {
81
+ return sub(state, () => callback(state));
82
+ },
83
+ subscribeKey(key, callback) {
84
+ return subKey(state, key, callback);
85
+ },
86
+ getParams() {
87
+ const {
88
+ activeAddress,
89
+ activeNamespace,
90
+ activeNetwork,
91
+ connection
92
+ } = ConnectionsController.state;
93
+ const address = CoreHelperUtil.getPlainAddress(activeAddress);
94
+ if (!activeNamespace || !activeNetwork) {
95
+ throw new Error('No active namespace or network found to swap the tokens from.');
96
+ }
97
+ const networkAddress = `${activeNetwork.caipNetworkId}:${ConstantsUtil.NATIVE_TOKEN_ADDRESS[activeNamespace]}`;
98
+ if (!address) {
99
+ throw new Error('No address found to swap the tokens from.');
100
+ }
101
+ const invalidToToken = !state.toToken?.address || !state.toToken?.decimals;
102
+ const invalidSourceToken = !state.sourceToken?.address || !state.sourceToken?.decimals || state.sourceToken.address === state.toToken?.address || !NumberUtil.bigNumber(state.sourceTokenAmount).isGreaterThan(0);
103
+ const invalidSourceTokenAmount = !state.sourceTokenAmount;
104
+ return {
105
+ networkAddress,
106
+ network: activeNetwork,
107
+ fromAddress: address,
108
+ fromCaipAddress: activeAddress,
109
+ sourceTokenAddress: state.sourceToken?.address,
110
+ toTokenAddress: state.toToken?.address,
111
+ toTokenAmount: state.toTokenAmount,
112
+ toTokenDecimals: state.toToken?.decimals,
113
+ sourceTokenAmount: state.sourceTokenAmount,
114
+ sourceTokenDecimals: state.sourceToken?.decimals,
115
+ invalidToToken,
116
+ invalidSourceToken,
117
+ invalidSourceTokenAmount,
118
+ availableToSwap: activeAddress && !invalidToToken && !invalidSourceToken && !invalidSourceTokenAmount,
119
+ isAuthConnector: !!connection?.properties?.provider
120
+ };
121
+ },
122
+ switchTokens() {
123
+ if (state.loadingTokens) {
124
+ return;
125
+ }
126
+ let newSourceToken = state.toToken ? {
127
+ ...state.toToken
128
+ } : undefined;
129
+ const sourceTokenWithBalance = state.myTokensWithBalance?.find(token => token.address === newSourceToken?.address);
130
+ if (sourceTokenWithBalance) {
131
+ newSourceToken = sourceTokenWithBalance;
132
+ }
133
+ const newToToken = state.sourceToken ? {
134
+ ...state.sourceToken
135
+ } : undefined;
136
+ const newSourceTokenAmount = newSourceToken && state.toTokenAmount === '' ? '1' : state.toTokenAmount;
137
+ this.setSourceToken(newSourceToken);
138
+ this.setToToken(newToToken);
139
+ this.setSourceTokenAmount(newSourceTokenAmount);
140
+ this.setToTokenAmount('');
141
+ this.swapTokens();
142
+ },
143
+ async fetchTokens() {
144
+ try {
145
+ const {
146
+ networkAddress
147
+ } = this.getParams();
148
+ state.loadingTokens = true;
149
+ await this.getTokenList();
150
+ await this.getNetworkTokenPrice();
151
+ await this.getMyTokensWithBalance();
152
+ const networkToken = state.tokens?.find(token => token.address === networkAddress);
153
+ if (networkToken) {
154
+ state.networkTokenSymbol = networkToken.symbol;
155
+ }
156
+
157
+ // Set default source token if not set
158
+ if (!state.sourceToken && state.myTokensWithBalance?.length) {
159
+ const sourceToken = state.myTokensWithBalance?.find(token => token.address.startsWith(networkAddress)) || state.myTokensWithBalance?.[0];
160
+ this.setSourceToken(sourceToken);
161
+ this.setSourceTokenAmount('1');
162
+ }
163
+ } catch (error) {
164
+ LogController.sendError(error, 'SwapController.ts', 'initializeState');
165
+ SnackController.showError('Failed to initialize swap');
166
+ RouterController.goBack();
167
+ } finally {
168
+ state.loadingTokens = false;
169
+ }
170
+ },
171
+ async getTokenList() {
172
+ const tokens = await SwapApiUtil.getTokenList();
173
+ state.tokens = tokens;
174
+ state.popularTokens = tokens.sort((aTokenInfo, bTokenInfo) => {
175
+ if (aTokenInfo.symbol < bTokenInfo.symbol) {
176
+ return -1;
177
+ }
178
+ if (aTokenInfo.symbol > bTokenInfo.symbol) {
179
+ return 1;
180
+ }
181
+ return 0;
182
+ });
183
+ state.suggestedTokens = tokens.filter(token => {
184
+ if (ConstantsUtil.SWAP_SUGGESTED_TOKENS.includes(token.symbol)) {
185
+ return true;
186
+ }
187
+ return false;
188
+ }, {});
189
+ },
190
+ async getMyTokensWithBalance(forceUpdate) {
191
+ await ConnectionsController.fetchBalance(forceUpdate);
192
+ const swapBalances = SwapApiUtil.mapBalancesToSwapTokens(ConnectionsController.state.balances);
193
+ if (!swapBalances) {
194
+ return;
195
+ }
196
+ await this.getInitialGasPrice();
197
+ this.setBalances(swapBalances);
198
+ },
199
+ getFilteredPopularTokens(balances) {
200
+ if (!balances) {
201
+ return state.popularTokens;
202
+ }
203
+ return state.popularTokens?.filter(token => !balances.some(t => t.address === token.address));
204
+ },
205
+ setSourceToken(sourceToken) {
206
+ if (!sourceToken) {
207
+ state.sourceToken = sourceToken;
208
+ state.sourceTokenAmount = '';
209
+ state.sourceTokenPriceInUSD = 0;
210
+ return;
211
+ }
212
+ state.sourceToken = sourceToken;
213
+ this.setTokenPrice(sourceToken.address, 'sourceToken');
214
+ },
215
+ setSourceTokenAmount(amount) {
216
+ state.sourceTokenAmount = amount;
217
+ if (amount === '') {
218
+ state.toTokenAmount = '';
219
+ }
220
+ },
221
+ async getAddressPrice(address) {
222
+ const [namespace, chain] = address.split(':');
223
+ const networkId = `${namespace}:${chain}`;
224
+ const existPrice = state.tokensPriceMap[address];
225
+ if (existPrice) {
226
+ return existPrice;
227
+ }
228
+ const response = await BlockchainApiController.fetchTokenPrice({
229
+ projectId: OptionsController.state.projectId,
230
+ addresses: [address],
231
+ caipNetworkId: networkId
232
+ });
233
+ const fungibles = response?.fungibles || [];
234
+ const allTokens = [...(state.tokens || []), ...(state.myTokensWithBalance || [])];
235
+ const symbol = allTokens?.find(token => token.address === address)?.symbol;
236
+ const price = fungibles.find(p => p.symbol.toLowerCase() === symbol?.toLowerCase())?.price || 0;
237
+ const priceAsFloat = parseFloat(price.toString());
238
+ state.tokensPriceMap[address] = priceAsFloat;
239
+ return priceAsFloat;
240
+ },
241
+ async getNetworkTokenPrice() {
242
+ const {
243
+ networkAddress
244
+ } = this.getParams();
245
+ const [namespace, chain] = networkAddress.split(':');
246
+ const networkId = `${namespace}:${chain}`;
247
+ const response = await BlockchainApiController.fetchTokenPrice({
248
+ projectId: OptionsController.state.projectId,
249
+ addresses: [networkAddress],
250
+ caipNetworkId: networkId
251
+ });
252
+ const token = response?.fungibles?.[0];
253
+ const price = token?.price.toString() || '0';
254
+ state.tokensPriceMap[networkAddress] = parseFloat(price);
255
+ state.networkTokenSymbol = token?.symbol || '';
256
+ state.networkPrice = price;
257
+ },
258
+ async getInitialGasPrice() {
259
+ const res = await SwapApiUtil.fetchGasPrice();
260
+ if (!res) {
261
+ return {
262
+ gasPrice: null,
263
+ gasPriceInUsd: null
264
+ };
265
+ }
266
+ const value = res.standard;
267
+ const gasFee = BigInt(value);
268
+ const gasLimit = BigInt(INITIAL_GAS_LIMIT);
269
+ const gasPrice = SwapCalculationUtil.getGasPriceInUSD(state.networkPrice, gasLimit, gasFee);
270
+ state.gasFee = value;
271
+ state.gasPriceInUSD = gasPrice;
272
+ return {
273
+ gasPrice: gasFee,
274
+ gasPriceInUSD: state.gasPriceInUSD
275
+ };
276
+ },
277
+ getProviderFeePrice() {
278
+ return SwapCalculationUtil.getProviderFeePrice(state.sourceTokenAmount, state.sourceTokenPriceInUSD);
279
+ },
280
+ setBalances(balances) {
281
+ state.myTokensWithBalance = balances;
282
+ balances.forEach(token => {
283
+ state.tokensPriceMap[token.address] = token.price || 0;
284
+ });
285
+ },
286
+ setToToken(toToken) {
287
+ if (!toToken) {
288
+ state.toToken = toToken;
289
+ state.toTokenAmount = '';
290
+ state.toTokenPriceInUSD = 0;
291
+ return;
292
+ }
293
+ state.toToken = toToken;
294
+ this.setTokenPrice(toToken.address, 'toToken');
295
+ },
296
+ setToTokenAmount(amount) {
297
+ state.toTokenAmount = amount ? NumberUtil.formatNumberToLocalString(amount, TO_AMOUNT_DECIMALS) : '';
298
+ },
299
+ async setTokenPrice(address, target) {
300
+ let price = state.tokensPriceMap[address] || 0;
301
+ if (!price) {
302
+ state.loadingPrices = true;
303
+ price = await this.getAddressPrice(address);
304
+ }
305
+ if (target === 'sourceToken') {
306
+ state.sourceTokenPriceInUSD = price;
307
+ } else if (target === 'toToken') {
308
+ state.toTokenPriceInUSD = price;
309
+ }
310
+ if (state.loadingPrices) {
311
+ state.loadingPrices = false;
312
+ }
313
+ if (this.getParams().availableToSwap) {
314
+ this.swapTokens();
315
+ }
316
+ },
317
+ // -- Swap ---------------------------------------------- //
318
+ async swapTokens() {
319
+ const address = ConnectionsController.state.activeAddress;
320
+ const sourceToken = state.sourceToken;
321
+ const toToken = state.toToken;
322
+ const haveSourceTokenAmount = NumberUtil.bigNumber(state.sourceTokenAmount).isGreaterThan(0);
323
+ if (!toToken || !sourceToken || state.loadingPrices || !haveSourceTokenAmount || !address) {
324
+ return;
325
+ }
326
+ state.loadingQuote = true;
327
+ const amountDecimal = NumberUtil.bigNumber(state.sourceTokenAmount).multipliedBy(10 ** sourceToken.decimals).integerValue();
328
+ try {
329
+ const quoteResponse = await BlockchainApiController.fetchSwapQuote({
330
+ userAddress: address,
331
+ projectId: OptionsController.state.projectId,
332
+ from: sourceToken.address,
333
+ to: toToken.address,
334
+ gasPrice: state.gasFee,
335
+ amount: amountDecimal.toString()
336
+ });
337
+ const quoteToAmount = quoteResponse?.quotes?.[0]?.toAmount;
338
+ if (!quoteToAmount) {
339
+ state.loadingQuote = false;
340
+ return;
341
+ }
342
+ const toTokenAmount = NumberUtil.bigNumber(quoteToAmount).dividedBy(10 ** toToken.decimals).toString();
343
+ this.setToTokenAmount(toTokenAmount);
344
+ const isInsufficientToken = this.hasInsufficientToken(state.sourceTokenAmount, sourceToken.address);
345
+ if (isInsufficientToken) {
346
+ state.inputError = 'Insufficient balance';
347
+ } else {
348
+ state.inputError = undefined;
349
+ this.setTransactionDetails();
350
+ }
351
+ } catch (error) {
352
+ LogController.sendError(error, 'SwapController.ts', 'getQuote');
353
+ SnackController.showError('Failed to get swap quote');
354
+ } finally {
355
+ state.loadingQuote = false;
356
+ }
357
+ },
358
+ // -- Create Transactions -------------------------------------- //
359
+ async getTransaction() {
360
+ const {
361
+ fromCaipAddress,
362
+ availableToSwap
363
+ } = this.getParams();
364
+ const sourceToken = state.sourceToken;
365
+ const toToken = state.toToken;
366
+ if (!fromCaipAddress || !availableToSwap || !sourceToken || !toToken || state.loadingQuote) {
367
+ return undefined;
368
+ }
369
+ try {
370
+ state.loadingBuildTransaction = true;
371
+ const hasAllowance = await SwapApiUtil.fetchSwapAllowance({
372
+ userAddress: fromCaipAddress,
373
+ tokenAddress: sourceToken.address,
374
+ sourceTokenAmount: state.sourceTokenAmount,
375
+ sourceTokenDecimals: sourceToken.decimals
376
+ });
377
+ let transaction;
378
+ if (hasAllowance) {
379
+ transaction = await this.createSwapTransaction();
380
+ } else {
381
+ transaction = await this.createAllowanceTransaction();
382
+ }
383
+ state.loadingBuildTransaction = false;
384
+ state.fetchError = false;
385
+ return transaction;
386
+ } catch (error) {
387
+ RouterController.goBack();
388
+ SnackController.showError('Failed to check allowance');
389
+ state.loadingBuildTransaction = false;
390
+ state.approvalTransaction = undefined;
391
+ state.swapTransaction = undefined;
392
+ state.fetchError = true;
393
+ return undefined;
394
+ }
395
+ },
396
+ async createAllowanceTransaction() {
397
+ const {
398
+ fromCaipAddress,
399
+ fromAddress,
400
+ sourceTokenAddress,
401
+ toTokenAddress
402
+ } = this.getParams();
403
+ if (!fromCaipAddress || !toTokenAddress) {
404
+ return undefined;
405
+ }
406
+ if (!sourceTokenAddress) {
407
+ throw new Error('createAllowanceTransaction - No source token address found.');
408
+ }
409
+ try {
410
+ const response = await BlockchainApiController.generateApproveCalldata({
411
+ projectId: OptionsController.state.projectId,
412
+ from: sourceTokenAddress,
413
+ to: toTokenAddress,
414
+ userAddress: fromCaipAddress
415
+ });
416
+ if (!response) {
417
+ throw new Error('createAllowanceTransaction - No response from generateApproveCalldata');
418
+ }
419
+ const gasLimit = await ConnectionsController.estimateGas({
420
+ address: fromAddress,
421
+ to: CoreHelperUtil.getPlainAddress(response.tx.to),
422
+ data: response.tx.data
423
+ });
424
+ const transaction = {
425
+ data: response.tx.data,
426
+ to: CoreHelperUtil.getPlainAddress(response.tx.from),
427
+ gas: gasLimit,
428
+ gasPrice: BigInt(response.tx.eip155.gasPrice),
429
+ value: BigInt(response.tx.value),
430
+ toAmount: state.toTokenAmount
431
+ };
432
+ state.swapTransaction = undefined;
433
+ state.approvalTransaction = {
434
+ data: transaction.data,
435
+ to: transaction.to,
436
+ gas: transaction.gas ?? BigInt(0),
437
+ gasPrice: transaction.gasPrice,
438
+ value: transaction.value,
439
+ toAmount: transaction.toAmount
440
+ };
441
+ return {
442
+ data: transaction.data,
443
+ to: transaction.to,
444
+ gas: transaction.gas ?? BigInt(0),
445
+ gasPrice: transaction.gasPrice,
446
+ value: transaction.value,
447
+ toAmount: transaction.toAmount
448
+ };
449
+ } catch (error) {
450
+ RouterController.goBack();
451
+ SnackController.showError('Failed to create approval transaction');
452
+ state.approvalTransaction = undefined;
453
+ state.swapTransaction = undefined;
454
+ state.fetchError = true;
455
+ return undefined;
456
+ }
457
+ },
458
+ async createSwapTransaction() {
459
+ const {
460
+ networkAddress,
461
+ fromCaipAddress,
462
+ sourceTokenAmount
463
+ } = this.getParams();
464
+ const sourceToken = state.sourceToken;
465
+ const toToken = state.toToken;
466
+ if (!fromCaipAddress || !sourceTokenAmount || !sourceToken || !toToken) {
467
+ return undefined;
468
+ }
469
+ const amount = ConnectionsController.parseUnits(sourceTokenAmount, sourceToken.decimals)?.toString();
470
+ try {
471
+ const response = await BlockchainApiController.generateSwapCalldata({
472
+ projectId: OptionsController.state.projectId,
473
+ userAddress: fromCaipAddress,
474
+ from: sourceToken.address,
475
+ to: toToken.address,
476
+ amount: amount
477
+ });
478
+ if (!response) {
479
+ throw new Error('createSwapTransaction - No response from generateSwapCalldata');
480
+ }
481
+ const isSourceNetworkToken = sourceToken.address === networkAddress;
482
+ const gas = BigInt(response.tx.eip155.gas);
483
+ const gasPrice = BigInt(response.tx.eip155.gasPrice);
484
+ const transaction = {
485
+ data: response.tx.data,
486
+ to: CoreHelperUtil.getPlainAddress(response.tx.to),
487
+ gas,
488
+ gasPrice,
489
+ value: isSourceNetworkToken ? BigInt(amount ?? '0') : BigInt('0'),
490
+ toAmount: state.toTokenAmount
491
+ };
492
+ state.gasPriceInUSD = SwapCalculationUtil.getGasPriceInUSD(state.networkPrice, gas, gasPrice);
493
+ state.approvalTransaction = undefined;
494
+ state.swapTransaction = transaction;
495
+ return transaction;
496
+ } catch (error) {
497
+ RouterController.goBack();
498
+ SnackController.showError('Failed to create transaction');
499
+ state.approvalTransaction = undefined;
500
+ state.swapTransaction = undefined;
501
+ state.fetchError = true;
502
+ return undefined;
503
+ }
504
+ },
505
+ async sendTransactionForApproval(data) {
506
+ const {
507
+ fromAddress,
508
+ network
509
+ } = this.getParams();
510
+ state.loadingApprovalTransaction = true;
511
+ SnackController.showLoading('Approve limit increase in your wallet');
512
+ try {
513
+ await ConnectionsController.sendTransaction({
514
+ address: fromAddress,
515
+ to: data.to,
516
+ data: data.data,
517
+ value: BigInt(data.value),
518
+ gasPrice: BigInt(data.gasPrice),
519
+ chainNamespace: ConnectionsController.state.activeNamespace,
520
+ network
521
+ });
522
+ await this.swapTokens();
523
+ await this.getTransaction();
524
+ state.approvalTransaction = undefined;
525
+ } catch (err) {
526
+ const error = err;
527
+ state.transactionError = error?.shortMessage;
528
+ SnackController.showError(error?.shortMessage ?? 'Transaction error');
529
+ } finally {
530
+ state.loadingApprovalTransaction = false;
531
+ }
532
+ },
533
+ async sendTransactionForSwap(data) {
534
+ if (!data) {
535
+ return undefined;
536
+ }
537
+ const {
538
+ fromAddress,
539
+ isAuthConnector,
540
+ network
541
+ } = this.getParams();
542
+ state.loadingTransaction = true;
543
+ const snackbarSuccessMessage = `Swapped ${state.sourceToken?.symbol} to ${state.toToken?.symbol}`;
544
+ SnackController.showLoading('Confirm transaction in your wallet');
545
+ try {
546
+ const forceUpdateAddresses = [state.sourceToken?.address, state.toToken?.address].filter(Boolean);
547
+ const transactionHash = await ConnectionsController.sendTransaction({
548
+ address: fromAddress,
549
+ to: data.to,
550
+ data: data.data,
551
+ gas: data.gas,
552
+ gasPrice: BigInt(data.gasPrice),
553
+ value: data.value,
554
+ chainNamespace: ConnectionsController.state.activeNamespace,
555
+ network
556
+ });
557
+ state.loadingTransaction = false;
558
+ SnackController.showSuccess(snackbarSuccessMessage, true);
559
+ EventsController.sendEvent({
560
+ type: 'track',
561
+ event: 'SWAP_SUCCESS',
562
+ properties: {
563
+ network: ConnectionsController.state.activeNetwork?.caipNetworkId,
564
+ swapFromToken: this.state.sourceToken?.symbol || '',
565
+ swapToToken: this.state.toToken?.symbol || '',
566
+ swapFromAmount: this.state.sourceTokenAmount || '',
567
+ swapToAmount: this.state.toTokenAmount || '',
568
+ isSmartAccount: ConnectionsController.state.accountType === 'smartAccount'
569
+ }
570
+ });
571
+ RouterController.replace(isAuthConnector ? 'Account' : 'AccountDefault');
572
+ SwapController.clearTokens();
573
+ SwapController.getMyTokensWithBalance(forceUpdateAddresses);
574
+ setTimeout(() => {
575
+ if (ConnectionsController.state.activeAddress) {
576
+ TransactionsController.fetchTransactions(ConnectionsController.state.activeAddress, true);
577
+ }
578
+ }, 5000);
579
+ return transactionHash;
580
+ } catch (err) {
581
+ const error = err;
582
+ LogController.sendError(error, 'SwapController.ts', 'sendTransactionForSwap', {
583
+ sourceToken: this.state.sourceToken?.symbol,
584
+ toToken: this.state.toToken?.symbol,
585
+ amount: this.state.sourceTokenAmount
586
+ });
587
+ state.transactionError = error?.shortMessage;
588
+ state.loadingTransaction = false;
589
+ SnackController.showError(error?.shortMessage ?? 'Transaction error');
590
+ EventsController.sendEvent({
591
+ type: 'track',
592
+ event: 'SWAP_ERROR',
593
+ properties: {
594
+ message: error?.shortMessage ?? error?.message ?? 'Unknown',
595
+ network: ConnectionsController.state.activeNetwork?.caipNetworkId,
596
+ swapFromToken: this.state.sourceToken?.symbol || '',
597
+ swapToToken: this.state.toToken?.symbol || '',
598
+ swapFromAmount: this.state.sourceTokenAmount || '',
599
+ swapToAmount: this.state.toTokenAmount || '',
600
+ isSmartAccount: ConnectionsController.state.accountType === 'smartAccount'
601
+ }
602
+ });
603
+ return undefined;
604
+ }
605
+ },
606
+ clearTransactionLoaders() {
607
+ state.loadingApprovalTransaction = false;
608
+ state.loadingBuildTransaction = false;
609
+ state.loadingTransaction = false;
610
+ },
611
+ clearTokens() {
612
+ state.sourceToken = initialState.sourceToken;
613
+ state.sourceTokenAmount = initialState.sourceTokenAmount;
614
+ state.sourceTokenPriceInUSD = initialState.sourceTokenPriceInUSD;
615
+ state.toToken = initialState.toToken;
616
+ state.toTokenAmount = initialState.toTokenAmount;
617
+ state.toTokenPriceInUSD = initialState.toTokenPriceInUSD;
618
+ state.inputError = initialState.inputError;
619
+ state.loadingApprovalTransaction = initialState.loadingApprovalTransaction;
620
+ state.loadingBuildTransaction = initialState.loadingBuildTransaction;
621
+ state.loadingTransaction = initialState.loadingTransaction;
622
+ state.fetchError = initialState.fetchError;
623
+ state.transactionError = initialState.transactionError;
624
+ state.swapTransaction = initialState.swapTransaction;
625
+ state.approvalTransaction = initialState.approvalTransaction;
626
+ },
627
+ resetState() {
628
+ this.clearTokens();
629
+ state.myTokensWithBalance = initialState.myTokensWithBalance;
630
+ state.tokensPriceMap = initialState.tokensPriceMap;
631
+ state.networkPrice = initialState.networkPrice;
632
+ state.networkTokenSymbol = initialState.networkTokenSymbol;
633
+ },
634
+ // -- Checks -------------------------------------------- //
635
+ hasInsufficientToken(sourceTokenAmount, sourceTokenAddress) {
636
+ const {
637
+ balances
638
+ } = ConnectionsController.state;
639
+ const networkToken = balances?.find(t => t.address === undefined);
640
+ const networkBalanceInUSD = networkToken ? NumberUtil.multiply(networkToken.quantity?.numeric ?? '0', networkToken.price).toString() : '0';
641
+ const isInsufficientSourceTokenForSwap = SwapCalculationUtil.isInsufficientSourceTokenForSwap(sourceTokenAmount, sourceTokenAddress, state.myTokensWithBalance);
642
+ let insufficientNetworkTokenForGas = true;
643
+ if (ConnectionsController.state.accountType === 'smartAccount') {
644
+ // Smart Accounts may pay gas in any ERC20 token
645
+ insufficientNetworkTokenForGas = false;
646
+ } else {
647
+ insufficientNetworkTokenForGas = SwapCalculationUtil.isInsufficientNetworkTokenForGas(networkBalanceInUSD, state.gasPriceInUSD);
648
+ }
649
+ return insufficientNetworkTokenForGas || isInsufficientSourceTokenForSwap;
650
+ },
651
+ // -- Calculations -------------------------------------- //
652
+ setTransactionDetails() {
653
+ const {
654
+ toTokenAddress,
655
+ toTokenDecimals
656
+ } = this.getParams();
657
+ if (!toTokenAddress || !toTokenDecimals) {
658
+ return;
659
+ }
660
+ state.gasPriceInUSD = SwapCalculationUtil.getGasPriceInUSD(state.networkPrice, BigInt(state.gasFee), BigInt(INITIAL_GAS_LIMIT));
661
+ state.priceImpact = SwapCalculationUtil.getPriceImpact({
662
+ sourceTokenAmount: state.sourceTokenAmount,
663
+ sourceTokenPriceInUSD: state.sourceTokenPriceInUSD,
664
+ toTokenPriceInUSD: state.toTokenPriceInUSD,
665
+ toTokenAmount: state.toTokenAmount
666
+ });
667
+ state.maxSlippage = SwapCalculationUtil.getMaxSlippage(state.slippage, state.toTokenAmount);
668
+ state.providerFee = SwapCalculationUtil.getProviderFee(state.sourceTokenAmount);
669
+ }
670
+ };
671
+ //# sourceMappingURL=SwapController.js.map