toQaFunc function
Implementation
BigInt toQaFunc(String input, Units unit) {
String inputStr = num.parse(input).toString();
String? baseStr = unitMap[unit];
if (baseStr == null) {
throw 'No unit of type ${unit} exists.';
}
int baseNumDecimals = baseStr.length - 1;
BigInt base = BigInt.parse(baseStr);
// Is it negative?
bool isNegative = inputStr.substring(0, 1) == '-';
if (isNegative) {
inputStr = inputStr.substring(1);
}
if (inputStr == '.') {
throw 'type error: Cannot convert ${inputStr} to Qa.';
}
// Split it into a whole and fractional part
List<String> comps = inputStr.split('.'); // eslint-disable-line
if (comps.length > 2) {
throw 'too long: Cannot convert ${inputStr} to Qa.';
}
String? whole;
try {
whole = comps.first;
} on StateError {
whole = '0';
}
String? fraction = comps.length == 2 ? comps.last : null;
if (fraction == null) {
fraction = '0';
}
if (fraction.length > baseNumDecimals) {
throw 'fraction is too long :Cannot convert ${inputStr} to Qa.';
}
while (fraction!.length < baseNumDecimals) {
fraction += '0';
}
BigInt wholeBN = BigInt.parse(whole);
BigInt fractionBN = BigInt.parse(fraction);
BigInt wei = wholeBN * base + fractionBN;
if (isNegative) {
wei = -(wei);
}
return BigInt.parse(wei.toString());
}