UNPKG

@starkdefi/core-sdk

Version:

SDK for building StarkDefi applications

560 lines (544 loc) • 22.9 kB
import { mainnet, sepolia } from '@starknet-react/chains'; import invariant from 'tiny-invariant'; import { validateAndParseAddress } from 'starknet'; function isSupportedChainId(chain) { return [mainnet, sepolia].some(function (c) { return c.id === chain.id; }); } var MaxUint256 = /*#__PURE__*/BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _inheritsLoose(t, o) { t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o); } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } var Fraction = /*#__PURE__*/function () { function Fraction(numerator, denominator) { if (denominator === void 0) { denominator = BigInt(1); } this.numerator = BigInt(numerator); this.denominator = BigInt(denominator); } Fraction.tryParseFraction = function tryParseFraction(fractionish) { if (typeof fractionish === 'bigint' || typeof fractionish === 'number' || typeof fractionish === 'string') return new Fraction(fractionish); if ('numerator' in fractionish && 'denominator' in fractionish) return fractionish; throw new Error('Could not parse fraction'); } // performs floor division ; var _proto = Fraction.prototype; _proto.invert = function invert() { return new Fraction(this.denominator, this.numerator); }; _proto.add = function add(other) { var otherParsed = Fraction.tryParseFraction(other); if (this.denominator === otherParsed.denominator) { return new Fraction(this.numerator + otherParsed.numerator, this.denominator); } return new Fraction(this.numerator * otherParsed.denominator + otherParsed.numerator * this.denominator, this.denominator * otherParsed.denominator); }; _proto.subtract = function subtract(other) { var otherParsed = Fraction.tryParseFraction(other); if (this.denominator === otherParsed.denominator) { return new Fraction(this.numerator - otherParsed.numerator, this.denominator); } return new Fraction(this.numerator * otherParsed.denominator - otherParsed.numerator * this.denominator, this.denominator * otherParsed.denominator); }; _proto.lessThan = function lessThan(other) { var otherParsed = Fraction.tryParseFraction(other); return this.numerator * otherParsed.denominator < otherParsed.numerator * this.denominator; }; _proto.equalTo = function equalTo(other) { var otherParsed = Fraction.tryParseFraction(other); return this.numerator * otherParsed.denominator === otherParsed.numerator * this.denominator; }; _proto.greaterThan = function greaterThan(other) { var otherParsed = Fraction.tryParseFraction(other); return this.numerator * otherParsed.denominator > otherParsed.numerator * this.denominator; }; _proto.multiply = function multiply(other) { var otherParsed = Fraction.tryParseFraction(other); return new Fraction(this.numerator * otherParsed.numerator, this.denominator * otherParsed.denominator); }; _proto.divide = function divide(other) { var otherParsed = Fraction.tryParseFraction(other); return new Fraction(this.numerator * otherParsed.denominator, this.denominator * otherParsed.numerator); }; _proto.toSignificant = function toSignificant(significantDigits) { !Number.isInteger(significantDigits) ? process.env.NODE_ENV !== "production" ? invariant(false, significantDigits + " is not an integer.") : invariant(false) : void 0; !(significantDigits > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, significantDigits + " is not positive.") : invariant(false) : void 0; var quotient = Number(this.numerator) / Number(this.denominator); if (quotient === 0) return '0'; // Calculate the magnitude of the number var magnitude = Math.floor(Math.log10(Math.abs(quotient))); // For numbers >= 1, round to maintain significant digits if (quotient >= 1) { var factor = Math.pow(10, significantDigits - magnitude - 1); var rounded = Math.floor(quotient * factor) / factor; return rounded.toString(); } // For numbers < 1, handle decimal places more carefully var decimalPlaces = Math.max(0, significantDigits - magnitude - 1); var result = quotient.toFixed(decimalPlaces); // Remove trailing zeros after decimal point but keep significant figures if (result.includes('.')) { // Count significant digits in the result var digits = result.replace(/^0*\.?0*/, '').replace('.', ''); if (digits.length > significantDigits) { var _result$match; // Truncate to significant digits var truncated = digits.substring(0, significantDigits); var leadingZeros = ((_result$match = result.match(/^0*\.?(0*)/)) == null || (_result$match = _result$match[1]) == null ? void 0 : _result$match.length) || 0; result = '0.' + '0'.repeat(leadingZeros) + truncated; } // Remove trailing zeros result = result.replace(/0+$/, '').replace(/\.$/, ''); } return result; }; _proto.toFixed = function toFixed(decimalPlaces) { !Number.isInteger(decimalPlaces) ? process.env.NODE_ENV !== "production" ? invariant(false, decimalPlaces + " is not an integer.") : invariant(false) : void 0; !(decimalPlaces >= 0) ? process.env.NODE_ENV !== "production" ? invariant(false, decimalPlaces + " is negative.") : invariant(false) : void 0; var quotient = Number(this.numerator) / Number(this.denominator); return quotient.toFixed(decimalPlaces); } /** * Helper method for converting any super class back to a fraction */; return _createClass(Fraction, [{ key: "quotient", get: function get() { return this.numerator / this.denominator; } // remainder after floor division }, { key: "remainder", get: function get() { return new Fraction(this.numerator % this.denominator, this.denominator); } }, { key: "asFraction", get: function get() { return new Fraction(this.numerator, this.denominator); } }]); }(); var TokenAmount = /*#__PURE__*/function (_Fraction) { function TokenAmount(token, numerator, denominator) { var _this; _this = _Fraction.call(this, numerator, denominator) || this; !(_this.quotient <= MaxUint256) ? process.env.NODE_ENV !== "production" ? invariant(false, 'AMOUNT') : invariant(false) : void 0; _this.token = token; _this.decimalScale = BigInt(Math.pow(10, token.decimals)); return _this; } /** * Returns a new token amount instance from the unitless amount of token, i.e. the raw amount * @param token the token in the amount * @param rawAmount the raw token or ether amount */ _inheritsLoose(TokenAmount, _Fraction); TokenAmount.fromRawAmount = function fromRawAmount(token, rawAmount) { return new TokenAmount(token, rawAmount); } /** * Construct a token amount with a denominator that is not equal to 1 * @param token the token * @param numerator the numerator of the fractional token amount * @param denominator the denominator of the fractional token amount */; TokenAmount.fromFractionalAmount = function fromFractionalAmount(token, numerator, denominator) { return new TokenAmount(token, numerator, denominator); }; var _proto = TokenAmount.prototype; _proto.add = function add(other) { !this.token.equals(other.token) ? process.env.NODE_ENV !== "production" ? invariant(false, 'CURRENCY') : invariant(false) : void 0; var added = _Fraction.prototype.add.call(this, other); return TokenAmount.fromFractionalAmount(this.token, added.numerator, added.denominator); }; _proto.subtract = function subtract(other) { !this.token.equals(other.token) ? process.env.NODE_ENV !== "production" ? invariant(false, 'CURRENCY') : invariant(false) : void 0; var subtracted = _Fraction.prototype.subtract.call(this, other); return TokenAmount.fromFractionalAmount(this.token, subtracted.numerator, subtracted.denominator); }; _proto.multiply = function multiply(other) { var multiplied = _Fraction.prototype.multiply.call(this, other); return TokenAmount.fromFractionalAmount(this.token, multiplied.numerator, multiplied.denominator); }; _proto.divide = function divide(other) { var divided = _Fraction.prototype.divide.call(this, other); return TokenAmount.fromFractionalAmount(this.token, divided.numerator, divided.denominator); }; _proto.toSignificant = function toSignificant(significantDigits) { if (significantDigits === void 0) { significantDigits = 6; } return _Fraction.prototype.divide.call(this, this.decimalScale).toSignificant(significantDigits); }; _proto.toFixed = function toFixed(decimalPlaces) { if (decimalPlaces === void 0) { decimalPlaces = this.token.decimals; } !(decimalPlaces <= this.token.decimals) ? process.env.NODE_ENV !== "production" ? invariant(false, 'DECIMALS') : invariant(false) : void 0; return _Fraction.prototype.divide.call(this, this.decimalScale).toFixed(decimalPlaces); }; _proto.toExact = function toExact() { var value = Number(this.quotient) / Number(this.decimalScale); var result = value.toFixed(this.token.decimals); // Remove trailing zeros after decimal point if (result.includes('.')) { result = result.replace(/\.?0+$/, ''); } return result; }; return _createClass(TokenAmount, [{ key: "wrapped", get: function get() { if (this.token.isToken) return this; return TokenAmount.fromFractionalAmount(this.token.wrapped, this.numerator, this.denominator); } }]); }(Fraction); var Price = /*#__PURE__*/function (_Fraction) { /** * Construct a price, either with the base and quote currency amount, or the * @param args */ function Price() { var _this; var baseCurrency, quoteCurrency, denominator, numerator; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (args.length === 4) { baseCurrency = args[0]; quoteCurrency = args[1]; denominator = args[2]; numerator = args[3]; } else { var result = args[0].quoteAmount.divide(args[0].baseAmount); var _ref = [args[0].baseAmount.token, args[0].quoteAmount.token, result.denominator, result.numerator]; baseCurrency = _ref[0]; quoteCurrency = _ref[1]; denominator = _ref[2]; numerator = _ref[3]; } _this = _Fraction.call(this, numerator, denominator) || this; _this.baseCurrency = baseCurrency; _this.quoteCurrency = quoteCurrency; _this.scalar = new Fraction(BigInt(Math.pow(10, baseCurrency.decimals)), BigInt(Math.pow(10, quoteCurrency.decimals))); return _this; } /** * Flip the price, switching the base and quote currency */ _inheritsLoose(Price, _Fraction); var _proto = Price.prototype; _proto.invert = function invert() { return new Price(this.quoteCurrency, this.baseCurrency, this.numerator, this.denominator); } /** * Multiply the price by another price, returning a new price. The other price must have the same base currency as this price's quote currency * @param other the other price */; _proto.multiply = function multiply(other) { !this.quoteCurrency.equals(other.baseCurrency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0; var fraction = _Fraction.prototype.multiply.call(this, other); return new Price(this.baseCurrency, other.quoteCurrency, fraction.denominator, fraction.numerator); } /** * Return the amount of quote currency corresponding to a given amount of the base currency * @param currencyAmount the amount of base currency to quote against the price */; _proto.quote = function quote(currencyAmount) { !currencyAmount.token.equals(this.baseCurrency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0; var result = _Fraction.prototype.multiply.call(this, currencyAmount); return TokenAmount.fromFractionalAmount(this.quoteCurrency, result.numerator, result.denominator); } /** * Get the value scaled by decimals for formatting * @private */; _proto.toSignificant = function toSignificant(significantDigits) { if (significantDigits === void 0) { significantDigits = 6; } return this.adjustedForDecimals.toSignificant(significantDigits); }; _proto.toFixed = function toFixed(decimalPlaces) { if (decimalPlaces === void 0) { decimalPlaces = 4; } return this.adjustedForDecimals.toFixed(decimalPlaces); }; return _createClass(Price, [{ key: "adjustedForDecimals", get: function get() { return _Fraction.prototype.multiply.call(this, this.scalar); } }]); }(Fraction); var ONE_HUNDRED = /*#__PURE__*/new Fraction(/*#__PURE__*/BigInt(100)); /** * Converts a fraction to a percent * @param fraction the fraction to convert */ function toPercent(fraction) { return new Percent(fraction.numerator, fraction.denominator); } var Percent = /*#__PURE__*/function (_Fraction) { function Percent() { var _this; _this = _Fraction.apply(this, arguments) || this; /** * This boolean prevents a fraction from being interpreted as a Percent */ _this.isPercent = true; return _this; } _inheritsLoose(Percent, _Fraction); var _proto = Percent.prototype; _proto.add = function add(other) { return toPercent(_Fraction.prototype.add.call(this, other)); }; _proto.subtract = function subtract(other) { return toPercent(_Fraction.prototype.subtract.call(this, other)); }; _proto.multiply = function multiply(other) { return toPercent(_Fraction.prototype.multiply.call(this, other)); }; _proto.divide = function divide(other) { return toPercent(_Fraction.prototype.divide.call(this, other)); }; _proto.toSignificant = function toSignificant(significantDigits) { if (significantDigits === void 0) { significantDigits = 5; } return _Fraction.prototype.multiply.call(this, ONE_HUNDRED).toSignificant(significantDigits); }; _proto.toFixed = function toFixed(decimalPlaces) { if (decimalPlaces === void 0) { decimalPlaces = 2; } return _Fraction.prototype.multiply.call(this, ONE_HUNDRED).toFixed(decimalPlaces); }; return Percent; }(Fraction); /** * A currency is any fungible financial instrument, including Ether, all ERC20 tokens, and other chain-native currencies */ var BaseToken = /** * Constructs an instance of the base class `BaseCurrency`. * @param chain the chain on which this currency resides * @param decimals decimals of the currency * @param symbol symbol of the currency * @param name of the currency */ function BaseToken(chain, decimals, symbol, name) { !isSupportedChainId(chain) ? process.env.NODE_ENV !== "production" ? invariant(false, 'CHAIN_ID') : invariant(false) : void 0; !(decimals >= 0 && decimals < 255 && Number.isInteger(decimals)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'DECIMALS') : invariant(false) : void 0; this.chain = chain; this.decimals = decimals; this.symbol = symbol; this.name = name; }; /** * Represents the native token of the chain on which it resides, e.g. eth/stark */ var NativeToken = /*#__PURE__*/function (_BaseToken) { function NativeToken() { var _this; _this = _BaseToken.apply(this, arguments) || this; _this.isNative = true; _this.isToken = false; return _this; } _inheritsLoose(NativeToken, _BaseToken); return NativeToken; }(BaseToken); function checkValidAddress(address) { if (/^0x[0-9a-fA-F]{63,64}$/.test(address)) { return address; } throw new Error('Invalid Address Format'); } /** * Represents an ERC20 token with a unique address and some metadata. */ var Token = /*#__PURE__*/function (_BaseToken) { /** * * @param chain {@link BaseCurrency#chain} * @param address The contract address on the chain on which this token lives * @param decimals {@link BaseCurrency#decimals} * @param symbol {@link BaseCurrency#symbol} * @param name {@link BaseCurrency#name} * @param bypassChecksum If true it only checks for length === 66, startsWith 0x and contains only hex characters */ function Token(chain, address, decimals, symbol, name, bypassChecksum) { var _this; _this = _BaseToken.call(this, chain, decimals, symbol, name) || this; _this.isNative = false; _this.isToken = true; if (bypassChecksum) { _this.address = checkValidAddress(address); } else { _this.address = validateAndParseAddress(address); } return _this; } /** * Returns true if the two tokens are equivalent, i.e. have the same chainId and address. * @param other other token to compare */ _inheritsLoose(Token, _BaseToken); var _proto = Token.prototype; _proto.equals = function equals(other) { return other.isToken && this.chain === other.chain && this.address === other.address; } /** * Returns true if the address of this token sorts before the address of the other token * @param other other token to compare * @throws if the tokens have the same address * @throws if the tokens are on different chains */; _proto.sortsBefore = function sortsBefore(other) { !(this.chain === other.chain) ? process.env.NODE_ENV !== "production" ? invariant(false, 'CHAIN_IDS') : invariant(false) : void 0; !(this.address !== other.address) ? process.env.NODE_ENV !== "production" ? invariant(false, 'ADDRESSES') : invariant(false) : void 0; return this.address.toLowerCase() < other.address.toLowerCase(); } /** * Return this token, which does not need to be wrapped */; return _createClass(Token, [{ key: "wrapped", get: function get() { return this; } }]); }(BaseToken); /** * Ether is the main usage of a 'native' token, i.e. for Ethereum mainnet and all testnets */ var Ether = /*#__PURE__*/function (_NativeToken) { function Ether(chain) { var nativeCurrency = chain.nativeCurrency; return _NativeToken.call(this, chain, nativeCurrency.decimals, nativeCurrency.symbol, nativeCurrency.name) || this; } _inheritsLoose(Ether, _NativeToken); Ether.onChain = function onChain(chain) { var _this$_etherCache$cha; return (_this$_etherCache$cha = this._etherCache[chain.name]) != null ? _this$_etherCache$cha : this._etherCache[chain.name] = new Ether(chain); }; var _proto = Ether.prototype; _proto.equals = function equals(other) { return other.isNative && other.chain === this.chain; }; return _createClass(Ether, [{ key: "wrapped", get: function get() { var eth = new Token(this.chain, this.chain.nativeCurrency.address, this.chain.nativeCurrency.decimals, this.chain.nativeCurrency.symbol, this.chain.nativeCurrency.name); !!!eth ? process.env.NODE_ENV !== "production" ? invariant(false, 'WRAPPED') : invariant(false) : void 0; return eth; } }]); }(NativeToken); Ether._etherCache = {}; // given an array of items sorted by `comparator`, insert an item into its sort index and constrain the size to // `maxSize` by removing the last item function sortedInsert(items, add, maxSize, comparator) { !(maxSize > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MAX_SIZE_ZERO') : invariant(false) : void 0; // this is an invariant because the interface cannot return multiple removed items if items.length exceeds maxSize !(items.length <= maxSize) ? process.env.NODE_ENV !== "production" ? invariant(false, 'ITEMS_SIZE') : invariant(false) : void 0; // short circuit first item add if (items.length === 0) { items.push(add); return null; } else { var isFull = items.length === maxSize; // short circuit if full and the additional item does not come before the last item if (isFull && comparator(items[items.length - 1], add) <= 0) { return add; } var lo = 0, hi = items.length; while (lo < hi) { var mid = lo + hi >>> 1; if (comparator(items[mid], add) <= 0) { lo = mid + 1; } else { hi = mid; } } items.splice(lo, 0, add); return isFull ? items.pop() : null; } } var MAX_SAFE_INTEGER = /*#__PURE__*/BigInt(Number.MAX_SAFE_INTEGER); var ZERO = /*#__PURE__*/BigInt(0); var ONE = /*#__PURE__*/BigInt(1); var TWO = /*#__PURE__*/BigInt(2); /** * Computes floor(sqrt(value)) * @param value the value for which to compute the square root, rounded down */ function sqrt(value) { !(value >= ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'NEGATIVE') : invariant(false) : void 0; // rely on built in sqrt if possible if (value < MAX_SAFE_INTEGER) { return BigInt(Math.floor(Math.sqrt(Number(value)))); } var z; var x; z = value; x = value / TWO + ONE; while (x < z) { z = x; x = (value / x + x) / TWO; } return z; } /** * Returns the percent difference between the mid price and the execution price, i.e. price impact. * @param midPrice mid price before the trade * @param inputAmount the input amount of the trade * @param outputAmount the output amount of the trade */ function computePriceImpact(midPrice, inputAmount, outputAmount) { var quotedOutputAmount = midPrice.quote(inputAmount); // calculate price impact := (exactQuote - outputAmount) / exactQuote var priceImpact = quotedOutputAmount.subtract(outputAmount).divide(quotedOutputAmount); return new Percent(priceImpact.numerator, priceImpact.denominator); } export { Ether, Fraction, MaxUint256, NativeToken, Percent, Price, Token, TokenAmount, checkValidAddress, computePriceImpact, isSupportedChainId, sortedInsert, sqrt }; //# sourceMappingURL=core-sdk.esm.js.map