js-stellar-base/src/numbers/index.js

  1. import { XdrLargeInt } from './xdr_large_int';
  2. export { Uint128 } from './uint128';
  3. export { Uint256 } from './uint256';
  4. export { Int128 } from './int128';
  5. export { Int256 } from './int256';
  6. export { ScInt } from './sc_int';
  7. export { XdrLargeInt };
  8. /**
  9. * Transforms an opaque {@link xdr.ScVal} into a native bigint, if possible.
  10. *
  11. * If you then want to use this in the abstractions provided by this module,
  12. * you can pass it to the constructor of {@link XdrLargeInt}.
  13. *
  14. * @example
  15. * let scv = contract.call("add", x, y); // assume it returns an xdr.ScVal
  16. * let bigi = scValToBigInt(scv);
  17. *
  18. * new ScInt(bigi); // if you don't care about types, and
  19. * new XdrLargeInt('i128', bigi); // if you do
  20. *
  21. * @param {xdr.ScVal} scv - the raw XDR value to parse into an integer
  22. * @returns {bigint} the native value of this input value
  23. *
  24. * @throws {TypeError} if the `scv` input value doesn't represent an integer
  25. */
  26. export function scValToBigInt(scv) {
  27. const scIntType = XdrLargeInt.getType(scv.switch().name);
  28. switch (scv.switch().name) {
  29. case 'scvU32':
  30. case 'scvI32':
  31. return BigInt(scv.value());
  32. case 'scvU64':
  33. case 'scvI64':
  34. return new XdrLargeInt(scIntType, scv.value()).toBigInt();
  35. case 'scvU128':
  36. case 'scvI128':
  37. return new XdrLargeInt(scIntType, [
  38. scv.value().lo(),
  39. scv.value().hi()
  40. ]).toBigInt();
  41. case 'scvU256':
  42. case 'scvI256':
  43. return new XdrLargeInt(scIntType, [
  44. scv.value().loLo(),
  45. scv.value().loHi(),
  46. scv.value().hiLo(),
  47. scv.value().hiHi()
  48. ]).toBigInt();
  49. default:
  50. throw TypeError(`expected integer type, got ${scv.switch()}`);
  51. }
  52. }