gecko/lib/providers/substrate_sdk.dart

1023 lines
30 KiB
Dart
Raw Normal View History

// ignore_for_file: use_build_context_synchronously
2022-06-17 01:13:14 +02:00
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:gecko/globals.dart';
2022-05-28 21:15:47 +02:00
import 'package:gecko/models/chest_data.dart';
import 'package:gecko/models/wallet_data.dart';
import 'package:gecko/providers/home.dart';
import 'package:gecko/providers/my_wallets.dart';
2022-09-09 01:12:17 +02:00
import 'package:gecko/providers/wallet_options.dart';
import 'package:gecko/providers/wallets_profiles.dart';
2022-02-18 02:19:08 +01:00
import 'package:polkawallet_sdk/api/apiKeyring.dart';
import 'package:polkawallet_sdk/api/types/networkParams.dart';
2022-02-19 23:51:12 +01:00
import 'package:polkawallet_sdk/api/types/txInfoData.dart';
import 'package:polkawallet_sdk/polkawallet_sdk.dart';
import 'package:polkawallet_sdk/storage/keyring.dart';
2022-05-04 19:00:09 +02:00
import 'package:polkawallet_sdk/storage/types/keyPairData.dart';
import 'package:polkawallet_sdk/webviewWithExtension/types/signExtrinsicParam.dart';
import 'package:provider/provider.dart';
2022-02-19 23:51:12 +01:00
import 'package:truncate/truncate.dart';
2022-08-16 01:44:45 +02:00
import 'package:pointycastle/pointycastle.dart' as pc;
import "package:hex/hex.dart";
class SubstrateSdk with ChangeNotifier {
final WalletSDK sdk = WalletSDK();
final Keyring keyring = Keyring();
2022-02-18 19:49:37 +01:00
String generatedMnemonic = '';
bool sdkReady = false;
2022-02-18 18:57:03 +01:00
bool sdkLoading = false;
bool nodeConnected = false;
2022-02-18 19:49:37 +01:00
bool importIsLoading = false;
int blocNumber = 0;
bool isLoadingEndpoint = false;
2022-05-25 20:40:55 +02:00
String debugConnection = '';
2022-05-26 02:19:29 +02:00
String transactionStatus = '';
final int initSs58 = 42;
Map<String, int> currencyParameters = {};
TextEditingController csSalt = TextEditingController();
TextEditingController csPassword = TextEditingController();
String g1V1NewAddress = '';
bool isCesiumIDVisible = false;
bool isCesiumAddresLoading = false;
2022-09-11 13:14:52 +02:00
late int udValue;
/////////////////////////////////////
////////// 1: API METHODS ///////////
/////////////////////////////////////
Future<String> _executeCall(TxInfoData txInfo, txOptions, String password,
2022-08-12 10:04:55 +02:00
[String? rawParams]) async {
2022-09-09 01:12:17 +02:00
final walletOptions =
Provider.of<WalletOptionsProvider>(homeContext, listen: false);
final walletProfiles =
Provider.of<WalletsProfilesProvider>(homeContext, listen: false);
try {
2022-09-08 20:14:45 +02:00
final hash = await sdk.api.tx.signAndSend(txInfo, txOptions, password,
rawParam: rawParams, onStatusChange: (p0) {
transactionStatus = p0;
notifyListeners();
}).timeout(
2022-09-09 10:41:53 +02:00
const Duration(seconds: 18),
2022-09-08 20:14:45 +02:00
onTimeout: () => {},
);
log.d(hash);
if (hash.isEmpty) {
transactionStatus = 'timeout';
notifyListeners();
return 'timeout';
} else {
2022-09-09 01:12:17 +02:00
// Success !
transactionStatus = hash.toString();
notifyListeners();
2022-09-09 01:12:17 +02:00
walletOptions.reload();
walletProfiles.reload();
return hash.toString();
}
} catch (e) {
transactionStatus = e.toString();
notifyListeners();
return e.toString();
}
}
Future _getStorage(String call) async {
return await sdk.webView!.evalJavascript('api.query.$call');
}
Future _getStorageConst(String call) async {
return (await sdk.webView!
.evalJavascript('api.consts.$call', wrapPromise: false) ??
[null])[0];
}
2022-08-27 23:26:37 +02:00
Future<TxSenderData> _setSender(String address) async {
final fromPubkey = await sdk.api.account.decodeAddress([address]);
return TxSenderData(
2022-08-27 23:26:37 +02:00
address,
fromPubkey!.keys.first,
);
}
Future<String> _signMessage(
Uint8List message, String address, String password) async {
final params = SignAsExtensionParam();
params.msgType = "pub(bytes.sign)";
params.request = {
"address": address,
"data": message,
};
final res = await sdk.api.keyring.signAsExtension(password, params);
return res?.signature ?? '';
}
////////////////////////////////////////////
////////// 2: GET ONCHAIN STORAGE //////////
////////////////////////////////////////////
Future<int> _getIdentityIndexOf(String address) async {
return await _getStorage('identity.identityIndexOf("$address")') ?? 0;
}
Future<List<int>> getCerts(String address) async {
final idtyIndex = await _getIdentityIndexOf(address);
final certsReceiver =
await _getStorage('cert.storageIdtyCertMeta($idtyIndex)') ?? [];
return [certsReceiver['receivedCount'], certsReceiver['issuedCount']];
}
Future<int> getCertValidityPeriod(String from, String to) async {
final idtyIndexFrom = await _getIdentityIndexOf(from);
final idtyIndexTo = await _getIdentityIndexOf(to);
if (idtyIndexFrom == 0 || idtyIndexTo == 0) return 0;
final List certData =
await _getStorage('cert.certsByReceiver($idtyIndexTo)') ?? [];
if (certData.isEmpty) return 0;
for (List certInfo in certData) {
if (certInfo[0] == idtyIndexFrom) {
return certInfo[1];
}
}
return 0;
}
Future<bool> hasAccountConsumers(String address) async {
final accountInfo = await _getStorage('system.account("$address")');
final consumers = accountInfo['consumers'];
return consumers == 0 ? false : true;
}
2022-09-11 13:14:52 +02:00
Future<int> getUdValue() async {
udValue = int.parse(await _getStorage('universalDividend.currentUd()'));
return udValue;
}
2022-09-12 12:04:08 +02:00
Future<double> getBalanceRatio() async {
udValue = await getUdValue();
balanceRatio =
(configBox.get('isUdUnit') ?? false) ? round(udValue / 100, 6) : 1;
return balanceRatio;
}
Future<Map<String, double>> getBalance(String address) async {
// log.d('currencyParameters: $currencyParameters');
if (!nodeConnected) {
return {
'transferableBalance': 0,
'free': 0,
'unclaimedUds': 0,
'reserved': 0,
};
}
// Get onchain storage values
final Map balanceGlobal = await _getStorage('system.account("$address")');
final int? idtyIndex =
await _getStorage('identity.identityIndexOf("$address")');
final Map? idtyData = idtyIndex == null
? null
: await _getStorage('identity.identities($idtyIndex)');
final int currentUdIndex =
int.parse(await _getStorage('universalDividend.currentUdIndex()'));
final List pastReevals =
await _getStorage('universalDividend.pastReevals()');
// Compute amount of claimable UDs
final int unclaimedUds = _computeUnclaimUds(currentUdIndex,
idtyData?['data']?['firstEligibleUd'] ?? 0, pastReevals);
// Calculate transferable and potential balance
final int transferableBalance =
(balanceGlobal['data']['free'] + unclaimedUds);
2022-09-11 13:14:52 +02:00
// log.d('udValue: $udValue');
Map<String, double> finalBalances = {
2022-09-11 13:14:52 +02:00
'transferableBalance': round((transferableBalance / balanceRatio) / 100),
'free': round((balanceGlobal['data']['free'] / balanceRatio) / 100),
'unclaimedUds': round((unclaimedUds / balanceRatio) / 100),
'reserved':
round((balanceGlobal['data']['reserved'] / balanceRatio) / 100),
};
// log.i(finalBalances);
return finalBalances;
}
int _computeUnclaimUds(
int currentUdIndex, int firstEligibleUd, List pastReevals) {
int totalAmount = 0;
if (firstEligibleUd == 0) return 0;
for (final List reval in pastReevals.reversed) {
final int revalNbr = reval[0];
final int revalValue = reval[1];
// Loop each UDs revaluations and sum unclaimed balance
if (revalNbr <= firstEligibleUd) {
final count = currentUdIndex - firstEligibleUd;
totalAmount += count * revalValue;
break;
} else {
final count = currentUdIndex - revalNbr;
totalAmount += count * revalValue;
currentUdIndex = revalNbr;
}
}
return totalAmount;
}
Future<bool> isMemberGet(String address) async {
return await idtyStatus(address) == 'Validated';
}
Future<bool> isSmithGet(String address) async {
var idtyIndex = await _getIdentityIndexOf(address);
final Map smithExpireOn =
(await _getStorage('smithsMembership.membership($idtyIndex)')) ?? {};
if (smithExpireOn.isEmpty) {
return false;
} else {
return true;
}
}
Future<Map<String, int>> certState(String from, String to) async {
Map<String, int> result = {};
final toStatus = await idtyStatus(to);
if (from != to && await isMemberGet(from)) {
final removableOn = await getCertValidityPeriod(from, to);
final certMeta = await getCertMeta(from);
final int nextIssuableOn = certMeta['nextIssuableOn'] ?? 0;
final certRemovableDuration = (removableOn - blocNumber) * 6;
const int renewDelay = 2 * 30 * 24 * 3600; // 2 months
if (certRemovableDuration >= renewDelay) {
final certRenewDuration = certRemovableDuration - renewDelay;
result.putIfAbsent('certRenewable', () => certRenewDuration);
} else if (nextIssuableOn > blocNumber) {
final certDelayDuration = (nextIssuableOn - blocNumber) * 6;
result.putIfAbsent('certDelay', () => certDelayDuration);
} else if (toStatus == 'Created') {
result.putIfAbsent('toStatus', () => 1);
} else {
result.putIfAbsent('canCert', () => 0);
}
}
// if (toStatus == 'Created') result.putIfAbsent('toStatus', () => 1);
return result;
}
Future<Map> getCertMeta(String address) async {
var idtyIndex = await _getIdentityIndexOf(address);
final certMeta =
await _getStorage('cert.storageIdtyCertMeta($idtyIndex)') ?? '';
return certMeta;
}
2022-08-18 14:26:12 +02:00
Future<String> idtyStatus(String address) async {
2022-09-09 01:12:17 +02:00
// WalletOptionsProvider walletOptions =
// Provider.of<WalletOptionsProvider>(homeContext, listen: false);
var idtyIndex = await _getIdentityIndexOf(address);
if (idtyIndex == 0) {
return 'noid';
}
final idtyStatus = await _getStorage('identity.identities($idtyIndex)');
if (idtyStatus != null) {
final String status = idtyStatus['status'];
2022-09-09 01:12:17 +02:00
// if (address == walletOptions.address.text && status == 'Validated') {
// walletOptions.reloadBuild();
// }
return (status);
} else {
return 'expired';
}
}
Future<String> getGenesisHash() async {
final String genesisHash = await sdk.webView!.evalJavascript(
'api.genesisHash.toHex()',
wrapPromise: false,
) ??
[];
// log.d('genesisHash: $genesisHash');
// log.d('genesisHash: ${HEX.decode(genesisHash.substring(2))}');
return genesisHash;
}
Future<Uint8List> addressToPubkey(String address) async {
final pubkey = await sdk.api.account.decodeAddress([address]);
final String pubkeyHex = pubkey!.keys.first;
final pubkeyByte = HEX.decode(pubkeyHex.substring(2)) as Uint8List;
// final pubkey58 = Base58Encode(pubkeyByte);
return pubkeyByte;
}
// Future pubkeyToAddress(String pubkey) async {
// await sdk.api.account.encodeAddress([pubkey]);
// }
Future initCurrencyParameters() async {
currencyParameters['ss58'] =
await _getStorageConst('system.ss58Prefix.words');
currencyParameters['minCertForMembership'] =
await _getStorageConst('wot.minCertForMembership.words');
currencyParameters['newAccountPrice'] =
await _getStorageConst('account.newAccountPrice.words');
currencyParameters['existentialDeposit'] =
await _getStorageConst('balances.existentialDeposit.words');
currencyParameters['certPeriod'] =
await _getStorageConst('cert.certPeriod.words');
currencyParameters['certMaxByIssuer'] =
await _getStorageConst('cert.maxByIssuer.words');
currencyParameters['certValidityPeriod'] =
await _getStorageConst('cert.validityPeriod.words');
log.i('currencyParameters: $currencyParameters');
}
2022-08-18 14:26:12 +02:00
void cesiumIDisVisible() {
isCesiumIDVisible = !isCesiumIDVisible;
notifyListeners();
}
/////////////////////////////////////
////// 3: SUBSTRATE CONNECTION //////
/////////////////////////////////////
Future<void> initApi() async {
2022-02-18 18:57:03 +01:00
sdkLoading = true;
await keyring.init([initSs58]);
keyring.setSS58(initSs58);
await sdk.init(keyring);
sdkReady = true;
2022-02-18 18:57:03 +01:00
sdkLoading = false;
notifyListeners();
}
String? getConnectedEndpoint() {
return sdk.api.connectedNode?.endpoint;
}
Future<void> connectNode(BuildContext ctx) async {
HomeProvider homeProvider = Provider.of<HomeProvider>(ctx, listen: false);
MyWalletsProvider myWalletProvider =
Provider.of<MyWalletsProvider>(ctx, listen: false);
homeProvider.changeMessage("connectionPending".tr(), 0);
2022-06-01 21:00:17 +02:00
2022-07-14 18:18:19 +02:00
// configBox.delete('customEndpoint');
final List<NetworkParams> listEndpoints =
configBox.containsKey('customEndpoint')
? [getDuniterCustomEndpoint()]
: getDuniterBootstrap();
2022-05-25 20:40:55 +02:00
int timeout = 10000;
if (sdk.api.connectedNode?.endpoint != null) {
await sdk.api.setting.unsubscribeBestNumber();
2022-02-19 23:51:12 +01:00
}
isLoadingEndpoint = true;
notifyListeners();
2022-07-14 18:18:19 +02:00
final res = await sdk.api.connectNode(keyring, listEndpoints).timeout(
Duration(milliseconds: timeout),
2022-02-19 23:51:12 +01:00
onTimeout: () => null,
);
isLoadingEndpoint = false;
notifyListeners();
if (res != null) {
nodeConnected = true;
// await getSs58Prefix();
2022-05-25 20:40:55 +02:00
// Subscribe bloc number
sdk.api.setting.subscribeBestNumber((res) {
blocNumber = int.parse(res.toString());
// log.d(sdk.api.connectedNode?.endpoint);
2022-06-01 21:00:17 +02:00
if (sdk.api.connectedNode?.endpoint == null) {
nodeConnected = false;
homeProvider.changeMessage("networkLost".tr(), 0);
} else {
nodeConnected = true;
2022-06-01 21:00:17 +02:00
}
2022-05-25 20:40:55 +02:00
notifyListeners();
});
await initCurrencyParameters();
2022-09-12 12:04:08 +02:00
await getBalanceRatio();
notifyListeners();
homeProvider.changeMessage(
2022-06-17 20:18:54 +02:00
"wellConnectedToNode"
.tr(args: [getConnectedEndpoint()!.split('/')[2]]),
2022-06-01 21:00:17 +02:00
5);
// snackNode(ctx, true);
} else {
nodeConnected = false;
2022-05-25 20:40:55 +02:00
debugConnection = res.toString();
notifyListeners();
homeProvider.changeMessage("noDuniterEndointAvailable".tr(), 0);
if (!myWalletProvider.checkIfWalletExist()) snackNode(homeContext, false);
}
log.d(sdk.api.connectedNode?.endpoint);
}
2022-02-18 02:19:08 +01:00
2022-07-14 18:18:19 +02:00
List<NetworkParams> getDuniterBootstrap() {
List<NetworkParams> node = [];
for (String endpoint in configBox.get('endpoint')) {
2022-07-14 18:18:19 +02:00
final n = NetworkParams();
n.name = currencyName;
n.endpoint = endpoint;
n.ss58 = currencyParameters['ss58'] ?? initSs58;
2022-07-14 18:18:19 +02:00
node.add(n);
}
return node;
}
NetworkParams getDuniterCustomEndpoint() {
final nodeParams = NetworkParams();
nodeParams.name = currencyName;
nodeParams.endpoint = configBox.get('customEndpoint');
nodeParams.ss58 = currencyParameters['ss58'] ?? initSs58;
2022-07-14 18:18:19 +02:00
return nodeParams;
}
2022-05-04 19:00:09 +02:00
Future<String> importAccount(
{String mnemonic = '',
String derivePath = '',
2022-08-15 17:41:12 +02:00
required String password}) async {
const keytype = KeyType.mnemonic;
if (mnemonic != '') generatedMnemonic = mnemonic;
2022-02-19 23:51:12 +01:00
2022-02-18 19:49:37 +01:00
importIsLoading = true;
notifyListeners();
2022-08-15 17:41:12 +02:00
final json = await sdk.api.keyring
.importAccount(keyring,
keyType: keytype,
2022-08-15 17:41:12 +02:00
key: generatedMnemonic,
name: derivePath,
password: password,
2022-03-02 21:33:50 +01:00
derivePath: derivePath,
cryptoType: CryptoType.sr25519)
2022-02-18 19:49:37 +01:00
.catchError((e) {
importIsLoading = false;
notifyListeners();
});
2022-05-04 19:00:09 +02:00
if (json == null) return '';
// log.d(json);
2022-02-19 23:51:12 +01:00
try {
await sdk.api.keyring.addAccount(
2022-02-19 23:51:12 +01:00
keyring,
2022-02-22 10:39:45 +01:00
keyType: keytype,
2022-02-19 23:51:12 +01:00
acc: json,
password: password,
2022-02-19 23:51:12 +01:00
);
} catch (e) {
log.e(e);
2022-02-18 19:49:37 +01:00
importIsLoading = false;
notifyListeners();
2022-02-19 23:51:12 +01:00
}
2022-02-18 02:19:08 +01:00
2022-02-18 19:49:37 +01:00
importIsLoading = false;
2022-05-30 05:31:33 +02:00
2022-02-18 02:19:08 +01:00
notifyListeners();
return keyring.allAccounts.last.address!;
2022-02-18 02:19:08 +01:00
}
//////////////////////////////////
/////// 4: CRYPTOGRAPHY //////////
//////////////////////////////////
2022-05-28 21:15:47 +02:00
KeyPairData getKeypair(String address) {
return keyring.keyPairs.firstWhere((kp) => kp.address == address,
orElse: (() => KeyPairData()));
}
Future<bool> checkPassword(String address, String pass) async {
final account = getKeypair(address);
return await sdk.api.keyring.checkPassword(account, pass);
}
Future<String> getSeed(String address, String pin) async {
2022-05-29 00:00:57 +02:00
final account = getKeypair(address);
keyring.setCurrent(account);
final seed = await sdk.api.keyring.getDecryptedSeed(keyring, pin);
2022-05-29 00:00:57 +02:00
String seedText;
if (seed == null) {
seedText = '';
2022-05-29 00:00:57 +02:00
} else {
seedText = seed.seed!.split('//')[0];
2022-05-29 00:00:57 +02:00
}
log.d(seedText);
return seedText;
2022-05-29 00:00:57 +02:00
}
int getDerivationNumber(String address) {
final account = getKeypair(address);
final deriveNbr = account.name!.split('//')[1];
return int.parse(deriveNbr);
}
Future<KeyPairData?> changePassword(BuildContext context, String address,
String passOld, String passNew) async {
final account = getKeypair(address);
MyWalletsProvider myWalletProvider =
Provider.of<MyWalletsProvider>(context, listen: false);
keyring.setCurrent(account);
myWalletProvider.resetPinCode();
return await sdk.api.keyring.changePassword(keyring, passOld, passNew);
}
2022-02-19 23:51:12 +01:00
Future<void> deleteAllAccounts() async {
for (var account in keyring.allAccounts) {
await sdk.api.keyring.deleteAccount(keyring, account);
}
}
2022-05-24 16:51:40 +02:00
Future<void> deleteAccounts(List<String> address) async {
for (var a in address) {
final account = getKeypair(a);
await sdk.api.keyring.deleteAccount(keyring, account);
}
}
Future<String> generateMnemonic({String lang = appLang}) async {
final gen = await sdk.api.keyring
.generateMnemonic(currencyParameters['ss58'] ?? initSs58);
2022-02-18 19:49:37 +01:00
generatedMnemonic = gen.mnemonic!;
2022-02-19 23:51:12 +01:00
2022-02-22 10:39:45 +01:00
return gen.mnemonic!;
2022-02-18 18:57:03 +01:00
}
2022-02-19 23:51:12 +01:00
Future<String> setCurrentWallet(WalletData wallet) async {
2022-05-28 21:15:47 +02:00
final currentChestNumber = configBox.get('currentChest');
ChestData newChestData = chestBox.get(currentChestNumber)!;
newChestData.defaultWallet = wallet.number;
await chestBox.put(currentChestNumber, newChestData);
2022-05-28 21:15:47 +02:00
2022-05-19 13:44:22 +02:00
try {
final acc = getKeypair(wallet.address!);
2022-05-19 13:44:22 +02:00
keyring.setCurrent(acc);
return acc.address!;
} catch (e) {
return (e.toString());
}
}
KeyPairData getCurrentWallet() {
try {
final acc = keyring.current;
return acc;
} catch (e) {
return KeyPairData();
}
}
Future<String> derive(
BuildContext context, String address, int number, String password) async {
final keypair = getKeypair(address);
final seedMap =
await keyring.store.getDecryptedSeed(keypair.pubKey, password);
if (seedMap?['type'] != 'mnemonic') return '';
final List seedList = seedMap!['seed'].split('//');
generatedMnemonic = seedList[0];
return await importAccount(
mnemonic: generatedMnemonic,
derivePath: '//$number',
password: password);
}
Future<String> generateRootKeypair(String address, String password) async {
final keypair = getKeypair(address);
final seedMap =
await keyring.store.getDecryptedSeed(keypair.pubKey, password);
if (seedMap?['type'] != 'mnemonic') return '';
final List seedList = seedMap!['seed'].split('//');
generatedMnemonic = seedList[0];
2022-08-15 17:41:12 +02:00
return await importAccount(password: password);
}
Future<bool> isMnemonicValid(String mnemonic) async {
// Needed for bad encoding of UTF-8
mnemonic = mnemonic.replaceAll('é', '');
mnemonic = mnemonic.replaceAll('è', '');
return await sdk.api.keyring.checkMnemonicValid(mnemonic);
}
2022-08-20 16:55:55 +02:00
Future<String> csToV2Address(String salt, String password) async {
2022-08-16 16:13:11 +02:00
final scrypt = pc.KeyDerivator('scrypt');
scrypt.init(
pc.ScryptParameters(
4096,
16,
1,
32,
Uint8List.fromList(salt.codeUnits),
),
);
final rawSeed = scrypt.process(Uint8List.fromList(password.codeUnits));
final rawSeedHex = '0x${HEX.encode(rawSeed)}';
// Just get the address without keystore
final newAddress = await sdk.api.keyring.addressFromRawSeed(
currencyParameters['ss58']!,
cryptoType: CryptoType.ed25519,
rawSeed: rawSeedHex);
g1V1NewAddress = newAddress.address!;
notifyListeners();
2022-08-20 16:55:55 +02:00
return g1V1NewAddress;
2022-08-16 16:13:11 +02:00
}
Future<List> getBalanceAndIdtyStatus(
String fromAddress, String toAddress) async {
final fromBalance = fromAddress == ''
? {'transferableBalance': 0}
: await getBalance(fromAddress);
final fromIdtyStatus =
fromAddress == '' ? 'noid' : await idtyStatus(fromAddress);
final fromHasConsumer =
fromAddress == '' ? false : await hasAccountConsumers(fromAddress);
final toIdtyStatus = await idtyStatus(toAddress);
2022-08-18 14:26:12 +02:00
return [fromBalance, fromIdtyStatus, toIdtyStatus, fromHasConsumer];
2022-08-18 14:26:12 +02:00
}
//////////////////////////////////////
///////// 5: CALLS EXECUTION /////////
//////////////////////////////////////
Future<String> pay(
2022-05-19 13:44:22 +02:00
{required String fromAddress,
required String destAddress,
required double amount,
required String password}) async {
2022-05-26 02:19:29 +02:00
transactionStatus = '';
2022-09-06 09:29:29 +02:00
final sender = await _setSender(fromAddress);
final globalBalance = await getBalance(fromAddress);
TxInfoData txInfo;
2022-08-12 10:04:55 +02:00
List txOptions = [];
String? rawParams;
2022-09-11 13:14:52 +02:00
final bool isUdUnit = configBox.get('isUdUnit') ?? false;
late String palette;
late String call;
late String tx2;
if (amount == -1) {
palette = 'balances';
call = 'transferAll';
txOptions = [destAddress, false];
tx2 = 'api.tx.balances.transferAll("$destAddress", false)';
} else {
2022-09-12 12:04:08 +02:00
int amountUnit;
2022-09-11 13:14:52 +02:00
if (isUdUnit) {
palette = 'universalDividend';
call = 'transferUd';
2022-09-12 12:38:32 +02:00
// amount is milliUds
2022-09-12 12:04:08 +02:00
amountUnit = (amount * 1000).toInt();
2022-09-11 13:14:52 +02:00
} else {
palette = 'balances';
call = 'transferKeepAlive';
2022-09-12 12:38:32 +02:00
// amount is double at 2 decimals
2022-09-12 12:04:08 +02:00
amountUnit = (amount * 100).toInt();
2022-09-11 13:14:52 +02:00
}
txOptions = [destAddress, amountUnit];
tx2 = 'api.tx.$palette.$call("$destAddress", $amountUnit)';
}
if (globalBalance['unclaimedUds'] == 0) {
2022-09-11 13:14:52 +02:00
txInfo = TxInfoData(palette, call, sender);
} else {
txInfo = TxInfoData(
'utility',
'batchAll',
sender,
);
2022-08-12 10:04:55 +02:00
const tx1 = 'api.tx.universalDividend.claimUds()';
rawParams = '[[$tx1, $tx2]]';
}
return await _executeCall(txInfo, txOptions, password, rawParams);
}
Future<String> certify(
2022-08-27 05:43:43 +02:00
String fromAddress, String destAddress, String password) async {
transactionStatus = '';
final myIdtyStatus = await idtyStatus(fromAddress);
2022-08-27 05:43:43 +02:00
final toIdtyStatus = await idtyStatus(destAddress);
final fromIndex = await _getIdentityIndexOf(fromAddress);
2022-08-27 05:43:43 +02:00
final toIndex = await _getIdentityIndexOf(destAddress);
if (myIdtyStatus != 'Validated') {
transactionStatus = 'notMember';
notifyListeners();
return 'notMember';
}
2022-08-27 23:26:37 +02:00
final sender = await _setSender(fromAddress);
TxInfoData txInfo;
2022-08-10 07:18:04 +02:00
List txOptions = [];
2022-08-12 10:04:55 +02:00
String? rawParams;
2022-08-27 05:43:43 +02:00
final toCerts = await getCerts(destAddress);
// log.d('debug: ${currencyParameters['minCertForMembership']}');
if (toIdtyStatus == 'noid') {
txInfo = TxInfoData(
'identity',
'createIdentity',
sender,
);
2022-08-27 05:43:43 +02:00
txOptions = [destAddress];
} else if (toIdtyStatus == 'Validated' ||
toIdtyStatus == 'ConfirmedByOwner') {
if (toCerts[0] >= currencyParameters['minCertForMembership']! - 1 &&
toIdtyStatus != 'Validated') {
log.i('Batch cert and membership validation');
2022-08-12 10:04:55 +02:00
txInfo = TxInfoData(
'utility',
'batchAll',
sender,
);
final tx1 = 'api.tx.cert.addCert($fromIndex, $toIndex)';
final tx2 = 'api.tx.identity.validateIdentity($toIndex)';
2022-08-12 10:04:55 +02:00
rawParams = '[[$tx1, $tx2]]';
} else {
txInfo = TxInfoData(
'cert',
'addCert',
sender,
);
2022-08-10 07:18:04 +02:00
txOptions = [fromIndex, toIndex];
}
} else {
transactionStatus = 'cantBeCert';
notifyListeners();
return 'cantBeCert';
}
log.d('Cert action: ${txInfo.call!}');
return await _executeCall(txInfo, txOptions, password, rawParams);
2022-02-19 23:51:12 +01:00
}
2022-05-24 16:51:40 +02:00
Future<String> confirmIdentity(
String fromAddress, String name, String password) async {
2022-09-06 09:29:29 +02:00
final sender = await _setSender(fromAddress);
2022-05-24 16:51:40 +02:00
final txInfo = TxInfoData(
'identity',
'confirmIdentity',
sender,
);
final txOptions = [name];
2022-05-24 16:51:40 +02:00
return await _executeCall(txInfo, txOptions, password);
}
Future<String> migrateIdentity(
{required String fromAddress,
required String destAddress,
required String fromPassword,
2022-08-20 16:55:55 +02:00
required String destPassword,
required Map fromBalance,
2022-08-20 16:55:55 +02:00
bool withBalance = false}) async {
transactionStatus = '';
2022-09-06 09:29:29 +02:00
final sender = await _setSender(fromAddress);
TxInfoData txInfo;
List txOptions = [];
String? rawParams;
final prefix = 'icok'.codeUnits;
final genesisHashString = await getGenesisHash();
final genesisHash = HEX.decode(genesisHashString.substring(2)) as Uint8List;
final idtyIndex = _int32bytes(await _getIdentityIndexOf(fromAddress));
final oldPubkey = await addressToPubkey(fromAddress);
final messageToSign =
Uint8List.fromList(prefix + genesisHash + idtyIndex + oldPubkey);
final messageToSignHex = HEX.encode(messageToSign);
final newKeySig =
await _signMessage(messageToSign, destAddress, destPassword);
// messageToSign: [105, 99, 111, 107, 7, 193, 18, 255, 106, 185, 215, 208, 213, 49, 235, 229, 159, 152, 179, 83, 24, 178, 129, 59, 22, 85, 87, 115, 128, 129, 157, 56, 214, 24, 45, 153, 21, 0, 0, 0, 181, 82, 178, 99, 198, 4, 156, 190, 78, 35, 102, 137, 255, 7, 162, 31, 16, 79, 255, 132, 130, 237, 230, 222, 176, 88, 245, 217, 237, 78, 196, 239]
log.d("""
fromAddress: $fromAddress
destAddress: $destAddress
genesisHashString: $genesisHashString
prefix: $prefix
genesisHash: $genesisHash
idtyIndex: $idtyIndex
oldPubkey: $oldPubkey
messageToSign: $messageToSign
messageToSignHex: $messageToSignHex
newKeySig: $newKeySig""");
2022-08-20 16:55:55 +02:00
if (withBalance) {
txInfo = TxInfoData(
'utility',
'batchAll',
sender,
);
2022-08-20 16:55:55 +02:00
const tx1 = 'api.tx.universalDividend.claimUds()';
final tx2 =
'api.tx.identity.changeOwnerKey("$destAddress", "$newKeySig")';
final tx3 = 'api.tx.balances.transferAll("$destAddress", false)';
rawParams = fromBalance['unclaimedUds'] == 0
? '[[$tx2, $tx3]]'
: '[[$tx1, $tx2, $tx3]]';
2022-08-20 16:55:55 +02:00
} else {
txInfo = TxInfoData(
'identity',
'changeOwnerKey',
sender,
);
2022-08-20 16:55:55 +02:00
txOptions = [destAddress, newKeySig];
}
return await _executeCall(txInfo, txOptions, fromPassword, rawParams);
}
2022-06-05 02:22:22 +02:00
Future revokeIdentity(String address, String password) async {
final idtyIndex = await _getIdentityIndexOf(address);
2022-09-06 09:29:29 +02:00
final sender = await _setSender(address);
2022-06-05 02:22:22 +02:00
2022-09-08 14:37:00 +02:00
final prefix = 'revo'.codeUnits;
2022-09-06 12:14:50 +02:00
final genesisHashString = await getGenesisHash();
final genesisHash = HEX.decode(genesisHashString.substring(2)) as Uint8List;
final idtyIndexBytes = _int32bytes(idtyIndex);
final messageToSign =
2022-09-08 20:15:19 +02:00
Uint8List.fromList(prefix + genesisHash + idtyIndexBytes);
2022-09-08 20:52:43 +02:00
final revocationSig =
(await _signMessage(messageToSign, address, password)).substring(2);
final revocationSigTyped = '0x01$revocationSig';
2022-06-05 02:22:22 +02:00
2022-09-06 12:14:50 +02:00
final txInfo = TxInfoData(
2022-09-06 09:29:29 +02:00
'identity',
'revokeIdentity',
2022-06-05 02:22:22 +02:00
sender,
);
2022-09-08 20:52:43 +02:00
final txOptions = [idtyIndex, address, revocationSigTyped];
return await _executeCall(txInfo, txOptions, password);
2022-06-05 02:22:22 +02:00
}
2022-08-18 14:26:12 +02:00
Future migrateCsToV2(String salt, String password, String destAddress,
{required destPassword,
required Map balance,
String idtyStatus = 'noid'}) async {
2022-08-18 14:26:12 +02:00
final scrypt = pc.KeyDerivator('scrypt');
scrypt.init(
pc.ScryptParameters(
4096,
16,
1,
32,
Uint8List.fromList(salt.codeUnits),
),
);
final rawSeed = scrypt.process(Uint8List.fromList(password.codeUnits));
final rawSeedHex = '0x${HEX.encode(rawSeed)}';
final json = await sdk.api.keyring.importAccount(keyring,
keyType: KeyType.rawSeed,
key: rawSeedHex,
name: 'test',
password: 'password',
derivePath: '',
cryptoType: CryptoType.ed25519);
final keypair = await sdk.api.keyring.addAccount(
keyring,
keyType: KeyType.rawSeed,
acc: json!,
password: password,
);
log.d('g1migration idtyStatus: $idtyStatus');
if (idtyStatus != 'noid') {
await migrateIdentity(
fromAddress: keypair.address!,
destAddress: destAddress,
fromPassword: 'password',
2022-08-20 16:55:55 +02:00
destPassword: destPassword,
withBalance: true,
fromBalance: balance);
} else if (balance['transferableBalance'] != 0) {
2022-08-18 14:26:12 +02:00
await pay(
fromAddress: keypair.address!,
destAddress: destAddress,
amount: -1,
password: 'password');
}
await sdk.api.keyring.deleteAccount(keyring, keypair);
}
Future spawnBlock([int number = 1, int until = 0]) async {
if (!kDebugMode) return;
if (blocNumber < until) {
number = until - blocNumber;
}
for (var i = 1; i <= number; i++) {
2022-08-27 23:26:37 +02:00
await sdk.webView!
.evalJavascript('api.rpc.engine.createBlock(true, true)');
}
}
void reload() {
notifyListeners();
}
2022-02-19 23:51:12 +01:00
}
////////////////////////////////////////////
/////// 6: UI ELEMENTS (off class) /////////
////////////////////////////////////////////
void snackNode(BuildContext context, bool isConnected) {
String message;
if (!isConnected) {
message = "noDuniterNodeAvailableTryLater".tr();
} else {
SubstrateSdk sub = Provider.of<SubstrateSdk>(context, listen: false);
message =
"${"youAreConnectedToNode".tr()}\n${sub.getConnectedEndpoint()!.split('//')[1]}";
}
2022-05-21 06:47:26 +02:00
final snackBar = SnackBar(
padding: const EdgeInsets.all(20),
content: Text(message, style: const TextStyle(fontSize: 16)),
2022-05-27 12:54:25 +02:00
duration: const Duration(seconds: 4));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
2022-02-19 23:51:12 +01:00
String getShortPubkey(String pubkey) {
2022-05-28 00:17:50 +02:00
String pubkeyShort = truncate(pubkey, 7,
2022-02-19 23:51:12 +01:00
omission: String.fromCharCode(0x2026),
position: TruncatePosition.end) +
2022-05-28 00:17:50 +02:00
truncate(pubkey, 6, omission: "", position: TruncatePosition.start);
2022-02-19 23:51:12 +01:00
return pubkeyShort;
}
2022-05-24 16:51:40 +02:00
Uint8List _int32bytes(int value) =>
Uint8List(4)..buffer.asInt32List()[0] = value;
2022-09-11 13:14:52 +02:00
double round(double number, [int decimal = 2]) {
return double.parse((number.toStringAsFixed(decimal)));
}