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