index.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. as FutureOr<BalanceData>);
  96. _updateBalances(acc, data);
  97. }
  98. }
  99. void loadBalances(KeyPairData acc) {
  100. // do not load balance data from cache if we have no decimals data.
  101. if (networkState.tokenDecimals == null) return;
  102. _updateBalances(
  103. acc,
  104. BalanceData.fromJson(Map<String, dynamic>.from(
  105. _cache.read(_getBalanceCacheKey(acc.pubKey)) ??
  106. {'accountId': acc.address})),
  107. isFromCache: true);
  108. }
  109. /// This method will be called while App switched to a plugin.
  110. /// In this method, the plugin will init [WalletSDK] and start
  111. /// a webView for running `polkadot-js/api`.
  112. Future<void> beforeStart(
  113. Keyring keyring, {
  114. KeyringEVM? keyringEVM,
  115. WebViewRunner? webView,
  116. String? jsCode,
  117. Function? socketDisconnectedAction,
  118. bool isEVM = false,
  119. }) async {
  120. await sdk.init(keyring,
  121. keyringEVM: keyringEVM,
  122. webView: webView,
  123. jsCode: jsCode ?? (await loadJSCode()),
  124. socketDisconnectedAction: socketDisconnectedAction,
  125. isEVM: isEVM);
  126. await (isEVM ? onWillStartEVM(keyringEVM!) : onWillStart(keyring));
  127. }
  128. /// This method will be called while App switched to a plugin.
  129. /// In this method, the plugin will:
  130. /// 1. connect to nodes.
  131. /// 2. retrieve network const & state.
  132. /// 3. subscribe balances & set balancesStore.
  133. Future<NetworkParams?> start(Keyring keyring,
  134. {List<NetworkParams>? nodes,
  135. Map<String, dynamic>? types,
  136. KeyringEVM? keyringEVM,
  137. NetworkParams? nodeEVM}) async {
  138. if (nodeEVM == null) {
  139. final res = await sdk.api.connectNode(
  140. keyring,
  141. nodes ?? nodeList,
  142. types,
  143. );
  144. if (res == null) return null;
  145. keyring.setSS58(res.ss58);
  146. await updateNetworkState();
  147. if (keyring.current.address != null) {
  148. sdk.api.account.subscribeBalance(keyring.current.address,
  149. (BalanceData data) {
  150. _updateBalances(keyring.current, data);
  151. });
  152. }
  153. onStarted(keyring);
  154. return res;
  155. }
  156. final evmRes = await sdk.api.connectEVM(nodeEVM);
  157. if (evmRes == null) return null;
  158. if (keyringEVM?.current.address != null) {
  159. final data = await sdk.api.eth.account
  160. .getNativeTokenBalance(keyringEVM?.current.address ?? '');
  161. _updateBalances(
  162. keyringEVM!.current.toKeyPairData(),
  163. BalanceData()
  164. ..accountId = keyringEVM.current.address
  165. ..freeBalance = data
  166. ..availableBalance = data
  167. ..lockedBalance = '0'
  168. ..reservedBalance = '0');
  169. }
  170. onStartedEVM(keyringEVM!);
  171. return evmRes;
  172. }
  173. /// This method will be called while App user changes account.
  174. Future<void> changeAccount(KeyPairData account) async {
  175. onAccountChanged(account);
  176. if (account.pubKey == account.address) {
  177. //eth
  178. final data = await sdk.api.eth.account
  179. .getNativeTokenBalance(account.address ?? '');
  180. _updateBalances(
  181. account,
  182. BalanceData()
  183. ..accountId = account.address
  184. ..freeBalance = data
  185. ..availableBalance = data
  186. ..lockedBalance = '0'
  187. ..reservedBalance = '0');
  188. } else {
  189. sdk.api.account.unsubscribeBalance();
  190. loadBalances(account);
  191. sdk.api.account.subscribeBalance(account.address, (BalanceData data) {
  192. _updateBalances(account, data);
  193. });
  194. }
  195. }
  196. /// This method will be called before plugin start
  197. Future<void> onWillStart(Keyring keyring) async {
  198. if (keyring.current.address != null) {
  199. loadBalances(keyring.current);
  200. }
  201. }
  202. Future<void> onWillStartEVM(KeyringEVM keyring) async {
  203. if (keyring.current.address != null) {
  204. loadBalances(keyring.current.toKeyPairData());
  205. }
  206. }
  207. /// This method will be called after plugin started
  208. Future<void> onStarted(Keyring keyring) async => null;
  209. /// This method will be called after plugin started
  210. Future<void> onStartedEVM(KeyringEVM keyringEvm) async => null;
  211. /// This method will be called while App user changes account.
  212. /// In this method, the plugin should do:
  213. /// 1. update balance subscription to update balancesStore.
  214. /// 2. update other user state of plugin if needed.
  215. Future<void> onAccountChanged(KeyPairData account) async => null;
  216. /// we don't really need this method, calling webView.launch
  217. /// more than once will cause some exception.
  218. /// We just pass a [webViewParam] instance to the sdk.init function,
  219. /// so the sdk knows how to deal with the webView.
  220. Future<void> dispose() async {
  221. // do nothing
  222. }
  223. }
  224. abstract class PolkawalletPluginBase {
  225. /// A plugin's basic info, including: name, primaryColor and icons.
  226. final basic = PluginBasicData(
  227. name: 'kusama', primaryColor: Colors.black as MaterialColor?);
  228. /// Plugin should define a list of node to connect
  229. /// for users of Polkawallet App.
  230. List<NetworkParams> get nodeList => [];
  231. /// Plugin should provide [tokenIcons]
  232. /// for display in Assets page of Polkawallet App.
  233. final Map<String, Widget> tokenIcons = {};
  234. /// The [getNavItems] method returns a list of [HomeNavItem] which defines
  235. /// the [Widget] to be used in home page of polkawallet App.
  236. List<HomeNavItem> getNavItems(BuildContext context, Keyring keyring) => [];
  237. /// App will add plugin's pages with custom [routes].
  238. Map<String, WidgetBuilder> getRoutes(Keyring keyring) =>
  239. Map<String, WidgetBuilder>();
  240. /// App will inject plugin's [jsCode] into webview to connect.
  241. Future<String>? loadJSCode() => null;
  242. }
  243. class PluginBasicData {
  244. PluginBasicData({
  245. this.name,
  246. this.genesisHash,
  247. this.ss58,
  248. this.primaryColor,
  249. this.gradientColor,
  250. this.backgroundImage,
  251. this.icon,
  252. this.iconDisabled,
  253. this.jsCodeVersion,
  254. this.isTestNet = true,
  255. this.isXCMSupport = false,
  256. this.parachainId,
  257. });
  258. final String? name;
  259. final String? genesisHash;
  260. final int? ss58;
  261. final MaterialColor? primaryColor;
  262. final Color? gradientColor;
  263. /// The image will be displayed in network-select page
  264. final AssetImage? backgroundImage;
  265. /// The icons will be displayed in network-select page
  266. /// in Polkawallet App.
  267. final Widget? icon;
  268. final Widget? iconDisabled;
  269. /// JavaScript code version of your plugin.
  270. ///
  271. /// Polkawallet App will perform hot-update for the js code
  272. /// of your plugin with it.
  273. final int? jsCodeVersion;
  274. /// Your plugin is connected to a para-chain testNet by default.
  275. final bool isTestNet;
  276. /// Whether this para-chain receives assets from relay-chain.
  277. /// should set [parachainId] if [isXCMSupport] enabled.
  278. final bool isXCMSupport;
  279. final String? parachainId;
  280. }