index.dart 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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/types/keyPairData.dart';
  13. const String sdk_cache_key = 'polka_wallet_sdk_cache';
  14. const String net_state_cache_key = 'network_state';
  15. const String net_const_cache_key = 'network_const';
  16. const String balance_cache_key = 'balances';
  17. abstract class PolkawalletPlugin implements PolkawalletPluginBase {
  18. /// A plugin has a [WalletSDK] instance for connecting to it's node.
  19. final WalletSDK sdk = WalletSDK();
  20. /// Plugin should retrieve [balances] from sdk
  21. /// for display in Assets page of Polkawallet App.
  22. final balances = BalancesStore();
  23. /// Plugin should provide a list of noneNativeToken
  24. /// for users of Polkawallet App.
  25. List<TokenBalanceData> get noneNativeTokensAll => [];
  26. final recoveryEnabled = false;
  27. /// Plugin should retrieve [networkState] & [networkConst] while start
  28. NetworkStateData get networkState {
  29. try {
  30. return NetworkStateData.fromJson(Map<String, dynamic>.from(
  31. _cache.read(_getNetworkCacheKey(net_state_cache_key)) ?? {}));
  32. } catch (err) {
  33. print(err);
  34. }
  35. return NetworkStateData();
  36. }
  37. Map get networkConst =>
  38. _cache.read(_getNetworkCacheKey(net_const_cache_key)) ?? {};
  39. GetStorage get _cache => GetStorage(sdk_cache_key);
  40. String _getNetworkCacheKey(String key) => '${key}_${basic.name}';
  41. String _getBalanceCacheKey(String? pubKey) =>
  42. '${balance_cache_key}_${basic.name}_$pubKey';
  43. Future<void> updateNetworkState() async {
  44. // final state = await Future.wait([
  45. // sdk.api.service.setting.queryNetworkConst(),
  46. // sdk.api.service.setting.queryNetworkProps(),
  47. // ]);
  48. final state = await sdk.api.service.setting.queryNetwork();
  49. if (state != null) {
  50. _cache.write(_getNetworkCacheKey(net_const_cache_key), state["const"]);
  51. _cache.write(_getNetworkCacheKey(net_state_cache_key), state["props"]);
  52. }
  53. }
  54. void _updateBalances(KeyPairData acc, BalanceData data,
  55. {bool isFromCache = false}) {
  56. if (acc.address == data.accountId || isFromCache) {
  57. data.isFromCache = isFromCache;
  58. balances.setBalance(data);
  59. if (!isFromCache) {
  60. _cache.write(_getBalanceCacheKey(acc.pubKey), data.toJson());
  61. }
  62. }
  63. }
  64. /// This method will be called while user request to query balance.
  65. Future<void> updateBalances(KeyPairData acc) async {
  66. final data = await (sdk.api.account.queryBalance(acc.address)
  67. as FutureOr<BalanceData>);
  68. _updateBalances(acc, data);
  69. }
  70. void loadBalances(KeyPairData acc) {
  71. // do not load balance data from cache if we have no decimals data.
  72. if (networkState.tokenDecimals == null) return;
  73. _updateBalances(
  74. acc,
  75. BalanceData.fromJson(Map<String, dynamic>.from(
  76. _cache.read(_getBalanceCacheKey(acc.pubKey)) ??
  77. {'accountId': acc.address})),
  78. isFromCache: true);
  79. }
  80. /// This method will be called while App switched to a plugin.
  81. /// In this method, the plugin will init [WalletSDK] and start
  82. /// a webView for running `polkadot-js/api`.
  83. Future<void> beforeStart(
  84. Keyring keyring, {
  85. WebViewRunner? webView,
  86. String? jsCode,
  87. }) async {
  88. await sdk.init(
  89. keyring,
  90. webView: webView,
  91. jsCode: jsCode ?? (await loadJSCode()),
  92. );
  93. await onWillStart(keyring);
  94. }
  95. /// This method will be called while App switched to a plugin.
  96. /// In this method, the plugin will:
  97. /// 1. connect to nodes.
  98. /// 2. retrieve network const & state.
  99. /// 3. subscribe balances & set balancesStore.
  100. Future<NetworkParams?> start(Keyring keyring,
  101. {List<NetworkParams>? nodes}) async {
  102. final res = await sdk.api.connectNode(keyring, nodes ?? nodeList);
  103. if (res == null) return null;
  104. keyring.setSS58(res.ss58);
  105. await updateNetworkState();
  106. if (keyring.current.address != null) {
  107. sdk.api.account.subscribeBalance(keyring.current.address,
  108. (BalanceData data) {
  109. _updateBalances(keyring.current, data);
  110. });
  111. }
  112. onStarted(keyring);
  113. return res;
  114. }
  115. /// This method will be called while App user changes account.
  116. void changeAccount(KeyPairData account) {
  117. sdk.api.account.unsubscribeBalance();
  118. loadBalances(account);
  119. sdk.api.account.subscribeBalance(account.address, (BalanceData data) {
  120. _updateBalances(account, data);
  121. });
  122. onAccountChanged(account);
  123. }
  124. /// This method will be called before plugin start
  125. Future<void> onWillStart(Keyring keyring) async {
  126. if (keyring.current.address != null) {
  127. loadBalances(keyring.current);
  128. }
  129. }
  130. /// This method will be called after plugin started
  131. Future<void> onStarted(Keyring keyring) async => null;
  132. /// This method will be called while App user changes account.
  133. /// In this method, the plugin should do:
  134. /// 1. update balance subscription to update balancesStore.
  135. /// 2. update other user state of plugin if needed.
  136. Future<void> onAccountChanged(KeyPairData account) async => null;
  137. /// we don't really need this method, calling webView.launch
  138. /// more than once will cause some exception.
  139. /// We just pass a [webViewParam] instance to the sdk.init function,
  140. /// so the sdk knows how to deal with the webView.
  141. Future<void> dispose() async {
  142. // do nothing
  143. }
  144. }
  145. abstract class PolkawalletPluginBase {
  146. /// A plugin's basic info, including: name, primaryColor and icons.
  147. final basic = PluginBasicData(
  148. name: 'kusama', primaryColor: Colors.black as MaterialColor?);
  149. /// Plugin should define a list of node to connect
  150. /// for users of Polkawallet App.
  151. List<NetworkParams> get nodeList => [];
  152. /// Plugin should provide [tokenIcons]
  153. /// for display in Assets page of Polkawallet App.
  154. final Map<String, Widget> tokenIcons = {};
  155. /// The [getNavItems] method returns a list of [HomeNavItem] which defines
  156. /// the [Widget] to be used in home page of polkawallet App.
  157. List<HomeNavItem> getNavItems(BuildContext context, Keyring keyring) => [];
  158. /// App will add plugin's pages with custom [routes].
  159. Map<String, WidgetBuilder> getRoutes(Keyring keyring) =>
  160. Map<String, WidgetBuilder>();
  161. /// App will inject plugin's [jsCode] into webview to connect.
  162. Future<String>? loadJSCode() => null;
  163. }
  164. class PluginBasicData {
  165. PluginBasicData({
  166. this.name,
  167. this.genesisHash,
  168. this.ss58,
  169. this.primaryColor,
  170. this.gradientColor,
  171. this.backgroundImage,
  172. this.icon,
  173. this.iconDisabled,
  174. this.jsCodeVersion,
  175. this.isTestNet = true,
  176. this.isXCMSupport = false,
  177. this.parachainId,
  178. });
  179. final String? name;
  180. final String? genesisHash;
  181. final int? ss58;
  182. final MaterialColor? primaryColor;
  183. final Color? gradientColor;
  184. /// The image will be displayed in network-select page
  185. final AssetImage? backgroundImage;
  186. /// The icons will be displayed in network-select page
  187. /// in Polkawallet App.
  188. final Widget? icon;
  189. final Widget? iconDisabled;
  190. /// JavaScript code version of your plugin.
  191. ///
  192. /// Polkawallet App will perform hot-update for the js code
  193. /// of your plugin with it.
  194. final int? jsCodeVersion;
  195. /// Your plugin is connected to a para-chain testNet by default.
  196. final bool isTestNet;
  197. /// Whether this para-chain receives assets from relay-chain.
  198. /// should set [parachainId] if [isXCMSupport] enabled.
  199. final bool isXCMSupport;
  200. final String? parachainId;
  201. }