nano derivation fix (#1428)

Matthew Fosse committed May 4, 2024 at 05:35 UTC d5543ceb08b055d5c0b3342ba7a3b5ca9983a8cb
1 file changed +33 -21
lib/nano/cw_nano.dart
+33 -21
@@ -228,35 +228,47 @@ class CWNanoUtil extends NanoUtil {
228 }) async {
229 NanoClient nanoClient = NanoClient();
230 nanoClient.connect(node);
231 - late String publicAddress;
231 + String? publicAddress;
232
233 - if (seedKey != null) {
234 - if (seedKey.length == 64) {
235 - try {
236 - mnemonic = NanoDerivations.standardSeedToMnemonic(seedKey);
237 - } catch (e) {
238 - print("not a valid 'nano' seed key");
233 + if (seedKey == null && mnemonic == null) {
234 + throw Exception("One of seed key OR mnemonic must be provided!");
235 + }
236 +
237 + try {
238 + if (seedKey != null) {
239 + if (seedKey.length == 64) {
240 + try {
241 + mnemonic = NanoDerivations.standardSeedToMnemonic(seedKey);
242 + } catch (e) {
243 + print("not a valid 'nano' seed key");
244 + }
245 + }
246 + if (derivationType == DerivationType.bip39) {
247 + publicAddress = await NanoDerivations.hdSeedToAddress(seedKey, index: 0);
248 + } else if (derivationType == DerivationType.nano) {
249 + publicAddress = await NanoDerivations.standardSeedToAddress(seedKey, index: 0);
250 }
251 }
252 +
253 if (derivationType == DerivationType.bip39) {
242 - publicAddress = await NanoDerivations.hdSeedToAddress(seedKey, index: 0);
243 - } else if (derivationType == DerivationType.nano) {
244 - publicAddress = await NanoDerivations.standardSeedToAddress(seedKey, index: 0);
254 + if (mnemonic != null) {
255 + seedKey = await NanoDerivations.hdMnemonicListToSeed(mnemonic.split(' '));
256 + publicAddress = await NanoDerivations.hdSeedToAddress(seedKey, index: 0);
257 + }
258 }
246 - }
259
248 - if (derivationType == DerivationType.bip39) {
249 - if (mnemonic != null) {
250 - seedKey = await NanoDerivations.hdMnemonicListToSeed(mnemonic.split(' '));
251 - publicAddress = await NanoDerivations.hdSeedToAddress(seedKey, index: 0);
260 + if (derivationType == DerivationType.nano) {
261 + if (mnemonic != null) {
262 + seedKey = await NanoDerivations.standardMnemonicToSeed(mnemonic);
263 + publicAddress = await NanoDerivations.standardSeedToAddress(seedKey, index: 0);
264 + }
265 }
253 - }
266 + } catch (_) {}
267
255 - if (derivationType == DerivationType.nano) {
256 - if (mnemonic != null) {
257 - seedKey = await NanoDerivations.standardMnemonicToSeed(mnemonic);
258 - publicAddress = await NanoDerivations.standardSeedToAddress(seedKey, index: 0);
259 - }
268 + if (publicAddress == null) {
269 + // we couldn't derive a public address for the derivation type provided
270 + // i.e. a bip39 seed was provided and we were instructed to derive a "nano" type address
271 + return null;
272 }
273
274 AccountInfoResponse? accountInfo = await nanoClient.getAccountInfo(publicAddress);