Constructor
new ScInt(value, optsopt)
Parameters:
Name | Type | Attributes | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
value |
number
|
bigint
|
string
|
a single, integer-like value which will
be interpreted in the smallest appropriate XDR type supported by Stellar
(64, 128, or 256 bit integer values). signed values are supported, though
they are sanity-checked against |
|||||||||
opts |
object
|
<optional> |
an optional object controlling optional parameters
|
Throws:
-
-
if the
value
is invalid (e.g. floating point), too large (i.e. exceeds a 256-bit value), or doesn't fit in theopts.type
- Type
-
RangeError
-
-
-
on missing parameters, or if the "signedness" of
opts
doesn't match inputvalue
, e.g. passing{type: 'u64'}
yet passing -1n - Type
-
TypeError
-
-
-
if a string
value
can't be parsed as a big integer - Type
-
SyntaxError
-
Example
import { xdr, ScInt, scValToBigInt } from "@stellar/stellar-base";
// You have an ScVal from a contract and want to parse it into JS native.
const value = xdr.ScVal.fromXDR(someXdr, "base64");
const bigi = scValToBigInt(value); // grab it as a BigInt
let sci = new ScInt(bigi);
sci.toNumber(); // gives native JS type (w/ size check)
sci.toBigInt(); // gives the native BigInt value
sci.toU64(); // gives ScValType-specific XDR constructs (with size checks)
// You have a number and want to shove it into a contract.
sci = ScInt(0xdeadcafebabe);
sci.toBigInt() // returns 244838016400062n
sci.toNumber() // throws: too large
// Pass any to e.g. a Contract.call(), conversion happens automatically
// regardless of the initial type.
const scValU128 = sci.toU128();
const scValI256 = sci.toI256();
const scValU64 = sci.toU64();
// Lots of ways to initialize:
ScInt("123456789123456789")
ScInt(123456789123456789n);
ScInt(1n << 140n);
ScInt(-42);
ScInt(scValToBigInt(scValU128)); // from above
// If you know the type ahead of time (accessing `.raw` is faster than
// conversions), you can specify the type directly (otherwise, it's
// interpreted from the numbers you pass in):
const i = ScInt(123456789n, { type: "u256" });
// For example, you can use the underlying `sdk.U256` and convert it to an
// `xdr.ScVal` directly like so:
const scv = new xdr.ScVal.scvU256(i.raw);
// Or reinterpret it as a different type (size permitting):
const scv = i.toI64();