index.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:get_storage/get_storage.dart';
  4. import 'package:polkawallet_sdk/api/types/balanceData.dart';
  5. import 'package:polkawallet_sdk/api/types/networkParams.dart';
  6. import 'package:polkawallet_sdk/api/types/networkStateData.dart';
  7. import 'package:polkawallet_sdk/plugin/homeNavItem.dart';
  8. import 'package:polkawallet_sdk/plugin/store/balances.dart';
  9. import 'package:polkawallet_sdk/polkawallet_sdk.dart';
  10. import 'package:polkawallet_sdk/service/webViewRunner.dart';
  11. import 'package:polkawallet_sdk/storage/keyring.dart';
  12. import 'package:polkawallet_sdk/storage/keyringEVM.dart';
  13. import 'package:polkawallet_sdk/storage/types/keyPairData.dart';
  14. import 'package:polkawallet_sdk/utils/app.dart';
  15. const String sdk_cache_key = 'polka_wallet_sdk_cache';
  16. const String net_state_cache_key = 'network_state';
  17. const String net_const_cache_key = 'network_const';
  18. const String balance_cache_key = 'balances';
  19. abstract class PolkawalletPlugin implements PolkawalletPluginBase {
  20. /// A plugin has a [WalletSDK] instance for connecting to it's node.
  21. final WalletSDK sdk = WalletSDK();
  22. /// Plugin should retrieve [balances] from sdk
  23. /// for display in Assets page of Polkawallet App.
  24. final balances = BalancesStore();
  25. /// Plugin should provide a list of defaultTokens
  26. /// for users of Polkawallet App.
  27. List<String> get defaultTokens => [];
  28. /// Plugin should provide a list of noneNativeToken
  29. /// for users of Polkawallet App.
  30. List<TokenBalanceData> get noneNativeTokensAll => [];
  31. final recoveryEnabled = false;
  32. final appUtils = AppUtils();
  33. /// The App will display this widget in assets page
  34. Widget? getAggregatedAssetsWidget(
  35. {String priceCurrency = 'USD',
  36. bool hideBalance = false,
  37. double rate = 1.0,
  38. @required Function? onSwitchBack,
  39. @required Function? onSwitchHideBalance}) =>
  40. null;
  41. /// The App will display this widget in native token detail page
  42. /// @param[transferType] = 0 | 1 | 2, (0 = all, 1 = in, 2 = out)
  43. Widget? getNativeTokenTransfers(
  44. {required String address, int transferType = 0}) =>
  45. null;
  46. /// Plugin should retrieve [networkState] & [networkConst] while start
  47. NetworkStateData get networkState {
  48. try {
  49. return NetworkStateData.fromJson(Map<String, dynamic>.from(
  50. _cache.read(_getNetworkCacheKey(net_state_cache_key)) ?? {}));
  51. } catch (err) {
  52. print(err);
  53. }
  54. return NetworkStateData();
  55. }
  56. Map get networkConst =>
  57. _cache.read(_getNetworkCacheKey(net_const_cache_key)) ?? {};
  58. GetStorage get _cache => GetStorage(sdk_cache_key);
  59. String _getNetworkCacheKey(String key) => '${key}_${basic.name}';
  60. String _getBalanceCacheKey(String? pubKey) =>
  61. '${balance_cache_key}_${basic.name}_$pubKey';
  62. Future<void> updateNetworkState() async {
  63. final state = await sdk.api.service.setting.queryNetwork();
  64. if (state != null) {
  65. _cache.write(_getNetworkCacheKey(net_const_cache_key), state["const"]);
  66. _cache.write(_getNetworkCacheKey(net_state_cache_key), state["props"]);
  67. }
  68. }
  69. void _updateBalances(KeyPairData acc, BalanceData data,
  70. {bool isFromCache = false}) {
  71. if (acc.address == data.accountId || isFromCache) {
  72. data.isFromCache = isFromCache;
  73. balances.setBalance(data);
  74. if (!isFromCache) {
  75. _cache.write(_getBalanceCacheKey(acc.pubKey), data.toJson());
  76. }
  77. }
  78. }
  79. /// This method will be called while user request to query balance.
  80. Future<void> updateBalances(KeyPairData acc) async {
  81. if (acc.pubKey == acc.address) {
  82. //eth
  83. final data =
  84. await sdk.api.eth.account.getNativeTokenBalance(acc.address ?? '');
  85. _updateBalances(
  86. acc,
  87. BalanceData()
  88. ..accountId = acc.address
  89. ..freeBalance = data
  90. ..availableBalance = data
  91. ..lockedBalance = '0'
  92. ..reservedBalance = '0');
  93. } else {
  94. final data = await (sdk.api.account.queryBalance(acc.address));
  95. if (data != null) {
  96. _updateBalances(acc, data);
  97. } else {
  98. throw Exception('queryBalance returned null. Address: ${acc.address}');
  99. }
  100. }
  101. }
  102. void loadBalances(KeyPairData acc) {
  103. // do not load balance data from cache if we have no decimals data.
  104. if (networkState.tokenDecimals == null) return;
  105. _updateBalances(
  106. acc,
  107. BalanceData.fromJson(Map<String, dynamic>.from(
  108. _cache.read(_getBalanceCacheKey(acc.pubKey)) ??
  109. {'accountId': acc.address})),
  110. isFromCache: true);
  111. }
  112. /// This method will be called while App switched to a plugin.
  113. /// In this method, the plugin will init [WalletSDK] and start
  114. /// a webView for running `polkadot-js/api`.
  115. Future<void> beforeStart(
  116. Keyring keyring, {
  117. KeyringEVM? keyringEVM,
  118. WebViewRunner? webView,
  119. String? jsCode,
  120. Function? socketDisconnectedAction,
  121. bool isEVM = false,
  122. }) async {
  123. await sdk.init(keyring,
  124. keyringEVM: keyringEVM,
  125. webView: webView,
  126. jsCode: jsCode ?? (await loadJSCode()),
  127. socketDisconnectedAction: socketDisconnectedAction,
  128. isEVM: isEVM);
  129. await (isEVM ? onWillStartEVM(keyringEVM!) : onWillStart(keyring));
  130. }
  131. /// This method will be called while App switched to a plugin.
  132. /// In this method, the plugin will:
  133. /// 1. connect to nodes.
  134. /// 2. retrieve network const & state.
  135. /// 3. subscribe balances & set balancesStore.
  136. Future<NetworkParams?> start(Keyring keyring,
  137. {List<NetworkParams>? nodes,
  138. KeyringEVM? keyringEVM,
  139. NetworkParams? nodeEVM}) async {
  140. if (nodeEVM == null) {
  141. final res = await sdk.api.connectNode(keyring, nodes ?? nodeList);
  142. if (res == null) return null;
  143. keyring.setSS58(res.ss58);
  144. await updateNetworkState();
  145. if (keyring.current.address != null) {
  146. sdk.api.account.subscribeBalance(keyring.current.address,
  147. (BalanceData data) {
  148. _updateBalances(keyring.current, data);
  149. });
  150. }
  151. onStarted(keyring);
  152. return res;
  153. }
  154. final evmRes = await sdk.api.connectEVM(nodeEVM);
  155. if (evmRes == null) return null;
  156. if (keyringEVM?.current.address != null) {
  157. final data = await sdk.api.eth.account
  158. .getNativeTokenBalance(keyringEVM?.current.address ?? '');
  159. _updateBalances(
  160. keyringEVM!.current.toKeyPairData(),
  161. BalanceData()
  162. ..accountId = keyringEVM.current.address
  163. ..freeBalance = data
  164. ..availableBalance = data
  165. ..lockedBalance = '0'
  166. ..reservedBalance = '0');
  167. }
  168. onStartedEVM(keyringEVM!);
  169. return evmRes;
  170. }
  171. /// This method will be called while App user changes account.
  172. Future<void> changeAccount(KeyPairData account) async {
  173. onAccountChanged(account);
  174. if (account.pubKey == account.address) {
  175. //eth
  176. final data = await sdk.api.eth.account
  177. .getNativeTokenBalance(account.address ?? '');
  178. _updateBalances(
  179. account,
  180. BalanceData()
  181. ..accountId = account.address
  182. ..freeBalance = data
  183. ..availableBalance = data
  184. ..lockedBalance = '0'
  185. ..reservedBalance = '0');
  186. } else {
  187. sdk.api.account.unsubscribeBalance();
  188. loadBalances(account);
  189. sdk.api.account.subscribeBalance(account.address, (BalanceData data) {
  190. _updateBalances(account, data);
  191. });
  192. }
  193. }
  194. /// This method will be called before plugin start
  195. Future<void> onWillStart(Keyring keyring) async {
  196. if (keyring.current.address != null) {
  197. loadBalances(keyring.current);
  198. }
  199. }
  200. Future<void> onWillStartEVM(KeyringEVM keyring) async {
  201. if (keyring.current.address != null) {
  202. loadBalances(keyring.current.toKeyPairData());
  203. }
  204. }
  205. /// This method will be called after plugin started
  206. Future<void> onStarted(Keyring keyring) async => null;
  207. /// This method will be called after plugin started
  208. Future<void> onStartedEVM(KeyringEVM keyringEvm) async => null;
  209. /// This method will be called while App user changes account.
  210. /// In this method, the plugin should do:
  211. /// 1. update balance subscription to update balancesStore.
  212. /// 2. update other user state of plugin if needed.
  213. Future<void> onAccountChanged(KeyPairData account) async => null;
  214. /// we don't really need this method, calling webView.launch
  215. /// more than once will cause some exception.
  216. /// We just pass a [webViewParam] instance to the sdk.init function,
  217. /// so the sdk knows how to deal with the webView.
  218. Future<void> dispose() async {
  219. // do nothing
  220. }
  221. }
  222. abstract class PolkawalletPluginBase {
  223. /// A plugin's basic info, including: name, primaryColor and icons.
  224. final basic = PluginBasicData(
  225. name: 'kusama', primaryColor: Colors.black as MaterialColor?);
  226. /// Plugin should define a list of node to connect
  227. /// for users of Polkawallet App.
  228. List<NetworkParams> get nodeList => [];
  229. /// Plugin should provide [tokenIcons]
  230. /// for display in Assets page of Polkawallet App.
  231. final Map<String, Widget> tokenIcons = {};
  232. /// The [getNavItems] method returns a list of [HomeNavItem] which defines
  233. /// the [Widget] to be used in home page of polkawallet App.
  234. List<HomeNavItem> getNavItems(BuildContext context, Keyring keyring) => [];
  235. /// App will add plugin's pages with custom [routes].
  236. Map<String, WidgetBuilder> getRoutes(Keyring keyring) =>
  237. Map<String, WidgetBuilder>();
  238. /// App will inject plugin's [jsCode] into webview to connect.
  239. Future<String>? loadJSCode() => null;
  240. }
  241. class PluginBasicData {
  242. PluginBasicData({
  243. this.name,
  244. this.genesisHash,
  245. this.ss58,
  246. this.primaryColor,
  247. this.gradientColor,
  248. this.backgroundImage,
  249. this.icon,
  250. this.iconDisabled,
  251. this.jsCodeVersion,
  252. this.isTestNet = true,
  253. this.isXCMSupport = false,
  254. this.parachainId,
  255. });
  256. final String? name;
  257. final String? genesisHash;
  258. final int? ss58;
  259. final MaterialColor? primaryColor;
  260. final Color? gradientColor;
  261. /// The image will be displayed in network-select page
  262. final AssetImage? backgroundImage;
  263. /// The icons will be displayed in network-select page
  264. /// in Polkawallet App.
  265. final Widget? icon;
  266. final Widget? iconDisabled;
  267. /// JavaScript code version of your plugin.
  268. ///
  269. /// Polkawallet App will perform hot-update for the js code
  270. /// of your plugin with it.
  271. final int? jsCodeVersion;
  272. /// Your plugin is connected to a para-chain testNet by default.
  273. final bool isTestNet;
  274. /// Whether this para-chain receives assets from relay-chain.
  275. /// should set [parachainId] if [isXCMSupport] enabled.
  276. final bool isXCMSupport;
  277. final String? parachainId;
  278. }