@t2000/cli 9.6.0 → 9.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../node_modules/.pnpm/eventemitter3@5.0.4/node_modules/eventemitter3/index.js","../../../node_modules/.pnpm/eventemitter3@5.0.4/node_modules/eventemitter3/index.mjs","../../../node_modules/.pnpm/@mysten+payment-kit@0.1.6_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/payment-kit/src/error.ts","../../../node_modules/.pnpm/@mysten+payment-kit@0.1.6_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/payment-kit/src/constants.ts","../../../node_modules/.pnpm/@mysten+payment-kit@0.1.6_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/payment-kit/src/uri.ts","../../../node_modules/.pnpm/@mysten+sui@2.17.0_typescript@5.9.3/node_modules/@mysten/sui/src/graphql/generated/queries.ts","../../../node_modules/.pnpm/@mysten+sui@2.17.0_typescript@5.9.3/node_modules/@mysten/sui/src/graphql/core.ts","../../../node_modules/.pnpm/graphql@16.13.2/node_modules/graphql/jsutils/devAssert.mjs","../../../node_modules/.pnpm/graphql@16.13.2/node_modules/graphql/language/ast.mjs","../../../node_modules/.pnpm/graphql@16.13.2/node_modules/graphql/language/kinds.mjs","../../../node_modules/.pnpm/graphql@16.13.2/node_modules/graphql/language/characterClasses.mjs","../../../node_modules/.pnpm/graphql@16.13.2/node_modules/graphql/language/blockString.mjs","../../../node_modules/.pnpm/graphql@16.13.2/node_modules/graphql/jsutils/inspect.mjs","../../../node_modules/.pnpm/graphql@16.13.2/node_modules/graphql/language/printString.mjs","../../../node_modules/.pnpm/graphql@16.13.2/node_modules/graphql/language/visitor.mjs","../../../node_modules/.pnpm/graphql@16.13.2/node_modules/graphql/language/printer.mjs","../../../node_modules/.pnpm/@mysten+sui@2.17.0_typescript@5.9.3/node_modules/@mysten/sui/src/graphql/client.ts","../../../node_modules/.pnpm/@mysten+sui@2.17.0_typescript@5.9.3/node_modules/@mysten/sui/src/cryptography/intent.ts","../../../node_modules/.pnpm/@mysten+sui@2.17.0_typescript@5.9.3/node_modules/@mysten/sui/src/cryptography/publickey.ts","../../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/src/sha2.ts","../../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/src/utils.ts","../../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/src/abstract/modular.ts","../../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/src/abstract/curve.ts","../../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/src/abstract/edwards.ts","../../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/src/ed25519.ts","../../../node_modules/.pnpm/@mysten+sui@2.17.0_typescript@5.9.3/node_modules/@mysten/sui/src/keypairs/ed25519/publickey.ts","../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/utils.ts","../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/hmac.ts","../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/pbkdf2.ts","../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/_md.ts","../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/_u64.ts","../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/sha2.ts","../../../node_modules/.pnpm/@scure+bip39@2.2.0/node_modules/@scure/bip39/index.js","../../../node_modules/.pnpm/@mysten+sui@2.17.0_typescript@5.9.3/node_modules/@mysten/sui/src/cryptography/mnemonics.ts","../../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/src/hmac.ts","../../../node_modules/.pnpm/@mysten+sui@2.17.0_typescript@5.9.3/node_modules/@mysten/sui/src/cryptography/signature.ts","../../../node_modules/.pnpm/@mysten+sui@2.17.0_typescript@5.9.3/node_modules/@mysten/sui/src/cryptography/keypair.ts","../../../node_modules/.pnpm/@mysten+sui@2.17.0_typescript@5.9.3/node_modules/@mysten/sui/src/keypairs/ed25519/ed25519-hd-key.ts","../../../node_modules/.pnpm/@mysten+sui@2.17.0_typescript@5.9.3/node_modules/@mysten/sui/src/keypairs/ed25519/keypair.ts","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/src/utils.ts","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/src/abstract/modular.ts","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/src/abstract/curve.ts","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/src/abstract/edwards.ts","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/src/ed25519.ts","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/src/abstract/weierstrass.ts","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/src/_shortw_utils.ts","../../../node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/src/secp256k1.ts","../../../node_modules/.pnpm/@mysten+suins@1.1.1_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/suins/src/constants.ts","../../../node_modules/.pnpm/@mysten+suins@1.1.1_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/suins/src/helpers.ts","../../../node_modules/.pnpm/@mysten+suins@1.1.1_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/suins/src/contracts/utils/index.ts","../../../node_modules/.pnpm/@mysten+suins@1.1.1_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/suins/src/contracts/suins/domain.ts","../../../node_modules/.pnpm/@mysten+suins@1.1.1_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/suins/src/contracts/suins/deps/sui/vec_map.ts","../../../node_modules/.pnpm/@mysten+suins@1.1.1_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/suins/src/contracts/suins_payments/deps/std/type_name.ts","../../../node_modules/.pnpm/@mysten+suins@1.1.1_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/suins/src/contracts/suins_payments/deps/sui/vec_map.ts","../../../node_modules/.pnpm/@mysten+suins@1.1.1_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/suins/src/contracts/suins_payments/payments.ts","../../../node_modules/.pnpm/@mysten+suins@1.1.1_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/suins/src/contracts/suins/deps/std/type_name.ts","../../../node_modules/.pnpm/@mysten+suins@1.1.1_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/suins/src/contracts/suins/payment.ts","../../../node_modules/.pnpm/@mysten+suins@1.1.1_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/suins/src/contracts/suins/controller.ts","../../../node_modules/.pnpm/@mysten+suins@1.1.1_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/suins/src/contracts/suins_coupons/deps/sui/bag.ts","../../../node_modules/.pnpm/@mysten+suins@1.1.1_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/suins/src/contracts/suins_coupons/data.ts","../../../node_modules/.pnpm/@mysten+suins@1.1.1_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/suins/src/contracts/suins_coupons/coupon_house.ts","../../../node_modules/.pnpm/@mysten+suins@1.1.1_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/suins/src/contracts/suins_discounts/discounts.ts","../../../node_modules/.pnpm/@mysten+suins@1.1.1_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/suins/src/contracts/suins_discounts/deps/suins/pricing_config.ts","../../../node_modules/.pnpm/@mysten+suins@1.1.1_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/suins/src/contracts/suins_discounts/deps/sui/linked_table.ts","../../../node_modules/.pnpm/@mysten+suins@1.1.1_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/suins/src/contracts/suins_discounts/free_claims.ts","../../../node_modules/.pnpm/@mysten+suins@1.1.1_@mysten+sui@2.17.0_typescript@5.9.3_/node_modules/@mysten/suins/src/suins-transaction.ts","../../sdk/src/errors.ts","../../sdk/src/preflight.ts","../../sdk/src/token-registry.ts","../../sdk/src/wallet/coinSelection.ts","../../sdk/src/protocols/cetus-swap.ts","../../sdk/src/swap-quote.ts","../../sdk/src/constants.ts","../../sdk/src/utils/sui.ts","../../sdk/src/wallet/keyManager.ts","../../sdk/src/wallet/keypairSigner.ts","../../sdk/src/wallet/executeTx.ts","../../sdk/src/wallet/pay.ts","../../sdk/src/mpp-cost.ts","../../sdk/src/wallet/zkLoginSigner.ts","../../sdk/src/wallet/send.ts","../../sdk/src/utils/format.ts","../../sdk/src/wallet/balance.ts","../../sdk/src/wallet/classify.ts","../../sdk/src/wallet/history.ts","../../sdk/src/t2000.ts","../../sdk/src/utils/suins.ts","../../sdk/src/inference.ts","../../sdk/src/verify.ts","../../sdk/src/limits/config.ts","../../sdk/src/limits/errors.ts","../../sdk/src/limits/enforce.ts","../../sdk/src/index.ts","../../sdk/src/wallet/job.ts","../../sdk/src/composeTx.ts","../../sdk/src/utils/simulate.ts","../../sdk/src/protocols/suins-leaf.ts"],"sourcesContent":["'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","import EventEmitter from './index.js'\n\nexport { EventEmitter }\nexport default EventEmitter\n","// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nexport class PaymentKitClientError extends Error {}\n\nexport class PaymentKitUriError extends PaymentKitClientError {}\n","// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { PaymentKitPackageConfig } from './types.js';\nimport { SUI_TYPE_ARG, normalizeStructTag } from '@mysten/sui/utils';\n\nexport const TESTNET_PAYMENT_KIT_PACKAGE_CONFIG = {\n\tpackageId: '0x7e069abe383e80d32f2aec17b3793da82aabc8c2edf84abbf68dd7b719e71497',\n\tnamespaceId: '0xa5016862fdccba7cc576b56cc5a391eda6775200aaa03a6b3c97d512312878db',\n} satisfies PaymentKitPackageConfig;\n\nexport const MAINNET_PAYMENT_KIT_PACKAGE_CONFIG = {\n\tpackageId: '0xbc126f1535fba7d641cb9150ad9eae93b104972586ba20f3c60bfe0e53b69bc6',\n\tnamespaceId: '0xccd3e4c7802921991cd9ce488c4ca0b51334ba75483702744242284ccf3ae7c2',\n} satisfies PaymentKitPackageConfig;\n\nexport const SUI_COIN_TYPE = normalizeStructTag(SUI_TYPE_ARG);\nexport const DEFAULT_REGISTRY_NAME = 'default-payment-registry';\n\nexport const SUI_PAYMENT_KIT_PROTOCOL = 'sui:pay';\n","// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { isValidNamedType, isValidSuiAddress, isValidSuiObjectId } from '@mysten/sui/utils';\nimport type { PaymentUriParams } from './types.js';\nimport { PaymentKitUriError } from './error.js';\nimport { SUI_PAYMENT_KIT_PROTOCOL } from './constants.js';\n\nconst isValidNonce = (nonce: string) => {\n\treturn nonce.length <= 36;\n};\n\nconst isValidAmount = (amount: bigint) => {\n\treturn amount > 0n;\n};\n\nconst isValidCoinType = (coinType: string) => {\n\treturn isValidNamedType(coinType);\n};\n\n/**\n * Create a payment transaction URI from the given parameters.\n * Returns the constructed URI string.\n *\n * @example\n * ```ts\n * const uri = createPaymentTransactionUri({\n * receiverAddress: \"0x...\",\n * amount: \"10000000\", (0.01 SUI)\n * coinType: \"0x2::sui::SUI\",\n * nonce: <nonce>,\n * registryName: \"my-registry\"\n * });\n * ```\n */\nexport const createPaymentTransactionUri = (params: PaymentUriParams): string => {\n\tconst { receiverAddress, amount, coinType, nonce, registryId, registryName } = params;\n\n\tconst uri = new URL(SUI_PAYMENT_KIT_PROTOCOL);\n\n\tif (isValidSuiAddress(receiverAddress)) {\n\t\turi.searchParams.append('receiver', receiverAddress);\n\t} else {\n\t\tthrow new PaymentKitUriError('Invalid Sui address');\n\t}\n\n\tif (isValidAmount(amount)) {\n\t\turi.searchParams.append('amount', amount.toString());\n\t} else {\n\t\tthrow new PaymentKitUriError('Amount must be a positive numeric string');\n\t}\n\n\tif (isValidCoinType(coinType)) {\n\t\turi.searchParams.append('coinType', coinType);\n\t} else {\n\t\tthrow new PaymentKitUriError('Invalid Coin Type');\n\t}\n\n\tif (isValidNonce(nonce)) {\n\t\turi.searchParams.append('nonce', nonce);\n\t} else {\n\t\tthrow new PaymentKitUriError('Nonce length exceeds maximum of 36 characters');\n\t}\n\n\tif (registryId) {\n\t\tif (isValidSuiObjectId(registryId)) {\n\t\t\turi.searchParams.append('registry', registryId);\n\t\t} else {\n\t\t\tthrow new PaymentKitUriError('Invalid Sui Object Id for Registry Id');\n\t\t}\n\t}\n\n\tif (registryName) {\n\t\turi.searchParams.append('registry', registryName);\n\t}\n\n\tif (params.label) {\n\t\turi.searchParams.append('label', params.label);\n\t}\n\n\tif (params.message) {\n\t\turi.searchParams.append('message', params.message);\n\t}\n\n\tif (params.iconUrl) {\n\t\turi.searchParams.append('iconUrl', params.iconUrl);\n\t}\n\n\treturn uri.toString();\n};\n\n/**\n * Parse a payment transaction URI into its components.\n * Returns the parsed payment URI parameters.\n *\n * @example\n * ```ts\n * const params = parsePaymentTransactionUri(\"sui:0x...?amount=1000000&coinType=0x...&nonce=...\");\n * ```\n */\nexport const parsePaymentTransactionUri = (uri: string): PaymentUriParams => {\n\tif (!uri.startsWith(SUI_PAYMENT_KIT_PROTOCOL + '?')) {\n\t\tthrow new PaymentKitUriError('Invalid URI: Must start with sui:pay?');\n\t}\n\n\tconst url = new URL(uri);\n\n\t// Extract query parameters\n\tconst params = url.searchParams;\n\tconst receiver = params.get('receiver');\n\tconst amount = params.get('amount');\n\tconst coinType = params.get('coinType');\n\tconst nonce = params.get('nonce');\n\n\t// Amount and CoinType are required\n\tif (!receiver || !amount || !coinType || !nonce) {\n\t\tthrow new PaymentKitUriError('Invalid URI: Missing required parameters');\n\t}\n\n\t// Validate the receiver address\n\tif (!isValidSuiAddress(receiver)) {\n\t\tthrow new PaymentKitUriError('Invalid URI: Receiver address is not valid');\n\t}\n\n\tif (!isValidCoinType(coinType)) {\n\t\tthrow new PaymentKitUriError('Invalid URI: Coin Type is not valid');\n\t}\n\n\tif (!isValidNonce(nonce)) {\n\t\tthrow new PaymentKitUriError('Invalid URI: Nonce length exceeds maximum of 36 characters');\n\t}\n\n\t// Validate amount is a valid numeric string (int or float) and positive\n\tconst bigIntAmount = BigInt(amount);\n\tif (!isValidAmount(bigIntAmount)) {\n\t\tthrow new PaymentKitUriError('Invalid URI: Amount must be a positive number');\n\t}\n\n\t// Extract optional registry parameter\n\tconst registry = params.get('registry') ?? undefined;\n\n\t// Determine if registry is an ID or name\n\tlet registryId: string | undefined;\n\tlet registryName: string | undefined;\n\n\tif (registry) {\n\t\tif (isValidSuiObjectId(registry)) {\n\t\t\tregistryId = registry;\n\t\t} else {\n\t\t\tregistryName = registry;\n\t\t}\n\t}\n\n\tconst baseParams = {\n\t\treceiverAddress: receiver,\n\t\tamount: bigIntAmount,\n\t\tcoinType,\n\t\tnonce: nonce,\n\t\tlabel: params.get('label') ?? undefined,\n\t\tmessage: params.get('message') ?? undefined,\n\t\ticonUrl: params.get('iconUrl') ?? undefined,\n\t};\n\n\tif (registryId) {\n\t\treturn { ...baseParams, registryId };\n\t}\n\n\treturn { ...baseParams, registryName };\n};\n","// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n/* eslint-disable */\n\nimport { MoveTypeLayout } from '../types.js';\nimport { MoveTypeSignature } from '../types.js';\nimport { OpenMoveTypeSignature } from '../types.js';\nimport { DocumentTypeDecoration } from '@graphql-typed-document-node/core';\nexport type Maybe<T> = T | null;\nexport type InputMaybe<T> = Maybe<T>;\nexport type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };\nexport type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };\nexport type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };\nexport type MakeEmpty<T extends { [key: string]: unknown }, K extends keyof T> = { [_ in K]?: never };\nexport type Incremental<T> = T | { [P in keyof T]?: P extends ' $fragmentName' | '__typename' ? T[P] : never };\n/** All built-in and custom scalars, mapped to their actual values */\nexport type Scalars = {\n ID: { input: string; output: string; }\n String: { input: string; output: string; }\n Boolean: { input: boolean; output: boolean; }\n Int: { input: number; output: number; }\n Float: { input: number; output: number; }\n /** String containing Base64-encoded binary data. */\n Base64: { input: string; output: string; }\n /** String representation of an arbitrary width, possibly signed integer */\n BigInt: { input: string; output: string; }\n /** ISO-8601 Date and Time: RFC3339 in UTC with format: YYYY-MM-DDTHH:MM:SS.mmmZ. Note that the milliseconds part is optional, and it may be omitted if its value is 0. */\n DateTime: { input: string; output: string; }\n /** Arbitrary JSON data. */\n JSON: { input: unknown; output: unknown; }\n /**\n * The shape of a concrete Move Type (a type with all its type parameters instantiated with concrete types), corresponding to the following recursive type:\n *\n * type MoveTypeLayout =\n * \"address\"\n * | \"bool\"\n * | \"u8\" | \"u16\" | ... | \"u256\"\n * | { vector: MoveTypeLayout }\n * | {\n * struct: {\n * type: string,\n * fields: [{ name: string, layout: MoveTypeLayout }],\n * }\n * }\n * | { enum: [{\n * type: string,\n * variants: [{\n * name: string,\n * fields: [{ name: string, layout: MoveTypeLayout }],\n * }]\n * }]\n * }\n */\n MoveTypeLayout: { input: MoveTypeLayout; output: MoveTypeLayout; }\n /**\n * The signature of a concrete Move Type (a type with all its type parameters instantiated with concrete types, that contains no references), corresponding to the following recursive type:\n *\n * type MoveTypeSignature =\n * \"address\"\n * | \"bool\"\n * | \"u8\" | \"u16\" | ... | \"u256\"\n * | { vector: MoveTypeSignature }\n * | {\n * datatype: {\n * package: string,\n * module: string,\n * type: string,\n * typeParameters: [MoveTypeSignature],\n * }\n * }\n */\n MoveTypeSignature: { input: MoveTypeSignature; output: MoveTypeSignature; }\n /**\n * The shape of an abstract Move Type (a type that can contain free type parameters, and can optionally be taken by reference), corresponding to the following recursive type:\n *\n * type OpenMoveTypeSignature = {\n * ref: (\"&\" | \"&mut\")?,\n * body: OpenMoveTypeSignatureBody,\n * }\n *\n * type OpenMoveTypeSignatureBody =\n * \"address\"\n * | \"bool\"\n * | \"u8\" | \"u16\" | ... | \"u256\"\n * | { vector: OpenMoveTypeSignatureBody }\n * | {\n * datatype {\n * package: string,\n * module: string,\n * type: string,\n * typeParameters: [OpenMoveTypeSignatureBody]\n * }\n * }\n * | { typeParameter: number }\n */\n OpenMoveTypeSignature: { input: OpenMoveTypeSignature; output: OpenMoveTypeSignature; }\n /** String containing 32 byte hex-encoded address, with a leading '0x'. Leading zeroes can be omitted on input but will always appear in outputs (SuiAddress in output is guaranteed to be 66 characters long). */\n SuiAddress: { input: string; output: string; }\n /** An unsigned integer that can hold values up to 2^53 - 1. This can be treated similarly to `Int`, but it is guaranteed to be non-negative, and it may be larger than 2^32 - 1. */\n UInt53: { input: number; output: number; }\n};\n\n/** System transaction for creating the accumulator root. */\nexport type AccumulatorRootCreateTransaction = {\n __typename?: 'AccumulatorRootCreateTransaction';\n /** A workaround to define an empty variant of a GraphQL union. */\n _?: Maybe<Scalars['Boolean']['output']>;\n};\n\nexport type ActiveJwk = {\n __typename?: 'ActiveJwk';\n /** The JWK algorithm parameter, (RFC 7517, Section 4.4). */\n alg?: Maybe<Scalars['String']['output']>;\n /** The JWK RSA public exponent, (RFC 7517, Section 9.3). */\n e?: Maybe<Scalars['String']['output']>;\n /** The most recent epoch in which the JWK was validated. */\n epoch?: Maybe<Epoch>;\n /** The string (Issuing Authority) that identifies the OIDC provider. */\n iss?: Maybe<Scalars['String']['output']>;\n /** The string (Key ID) that identifies the JWK among a set of JWKs, (RFC 7517, Section 4.5). */\n kid?: Maybe<Scalars['String']['output']>;\n /** The JWK key type parameter, (RFC 7517, Section 4.1). */\n kty?: Maybe<Scalars['String']['output']>;\n /** The JWK RSA modulus, (RFC 7517, Section 9.3). */\n n?: Maybe<Scalars['String']['output']>;\n};\n\nexport type ActiveJwkConnection = {\n __typename?: 'ActiveJwkConnection';\n /** A list of edges. */\n edges: Array<ActiveJwkEdge>;\n /** A list of nodes. */\n nodes: Array<ActiveJwk>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type ActiveJwkEdge = {\n __typename?: 'ActiveJwkEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: ActiveJwk;\n};\n\nexport type Address = IAddressable & Node & {\n __typename?: 'Address';\n /** The Address' identifier, a 32-byte number represented as a 64-character hex string, with a lead \"0x\". */\n address: Scalars['SuiAddress']['output'];\n /**\n * Fetch the address as it was at a different root version, or checkpoint.\n *\n * If no additional bound is provided, the address is fetched at the latest checkpoint known to the RPC.\n */\n addressAt?: Maybe<Address>;\n /** Attempts to fetch the object at this address. */\n asObject?: Maybe<Object>;\n /**\n * Fetch the total balance for coins with marker type `coinType` (e.g. `0x2::sui::SUI`), owned by this address.\n *\n * Returns `None` when no checkpoint is set in scope (e.g. execution scope).\n * If the address does not own any coins of that type, a balance of zero is returned.\n */\n balance?: Maybe<Balance>;\n /** Total balance across coins owned by this address, grouped by coin type. */\n balances?: Maybe<BalanceConnection>;\n /** The domain explicitly configured as the default Name Service name for this address. */\n defaultNameRecord?: Maybe<NameRecord>;\n /**\n * Access a dynamic field on an object using its type and BCS-encoded name.\n *\n * Returns `null` if a dynamic field with that name could not be found attached to the object with this address.\n */\n dynamicField?: Maybe<DynamicField>;\n /**\n * Dynamic fields owned by this address.\n *\n * The address must correspond to an object (account addresses cannot own dynamic fields), but that object may be wrapped.\n */\n dynamicFields?: Maybe<DynamicFieldConnection>;\n /**\n * Access a dynamic object field on an object using its type and BCS-encoded name.\n *\n * Returns `null` if a dynamic object field with that name could not be found attached to the object with this address.\n */\n dynamicObjectField?: Maybe<DynamicField>;\n /** The address's globally unique identifier, which can be passed to `Query.node` to refetch it. */\n id: Scalars['ID']['output'];\n /**\n * Fetch the total balances keyed by coin types (e.g. `0x2::sui::SUI`) owned by this address.\n *\n * Returns `None` when no checkpoint is set in scope (e.g. execution scope).\n * If the address does not own any coins of a given type, a balance of zero is returned for that type.\n */\n multiGetBalances?: Maybe<Array<Balance>>;\n /**\n * Access dynamic fields on an object using their types and BCS-encoded names.\n *\n * Returns a list of dynamic fields that is guaranteed to be the same length as `keys`. If a dynamic field in `keys` could not be found in the store, its corresponding entry in the result will be `null`.\n */\n multiGetDynamicFields: Array<Maybe<DynamicField>>;\n /**\n * Access dynamic object fields on an object using their types and BCS-encoded names.\n *\n * Returns a list of dynamic object fields that is guaranteed to be the same length as `keys`. If a dynamic object field in `keys` could not be found in the store, its corresponding entry in the result will be `null`.\n */\n multiGetDynamicObjectFields: Array<Maybe<DynamicField>>;\n /** Objects owned by this address, optionally filtered by type. */\n objects?: Maybe<MoveObjectConnection>;\n /**\n * Transactions associated with this address.\n *\n * Similar behavior to the `transactions` in Query but supporting the additional `AddressTransactionRelationship` filter, which defaults to `SENT`.\n */\n transactions?: Maybe<TransactionConnection>;\n};\n\n\nexport type AddressAddressAtArgs = {\n checkpoint?: InputMaybe<Scalars['UInt53']['input']>;\n rootVersion?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\nexport type AddressBalanceArgs = {\n coinType: Scalars['String']['input'];\n};\n\n\nexport type AddressBalancesArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\nexport type AddressDynamicFieldArgs = {\n name: DynamicFieldName;\n};\n\n\nexport type AddressDynamicFieldsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\nexport type AddressDynamicObjectFieldArgs = {\n name: DynamicFieldName;\n};\n\n\nexport type AddressMultiGetBalancesArgs = {\n keys: Array<Scalars['String']['input']>;\n};\n\n\nexport type AddressMultiGetDynamicFieldsArgs = {\n keys: Array<DynamicFieldName>;\n};\n\n\nexport type AddressMultiGetDynamicObjectFieldsArgs = {\n keys: Array<DynamicFieldName>;\n};\n\n\nexport type AddressObjectsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<ObjectFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\nexport type AddressTransactionsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<TransactionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n relation?: InputMaybe<AddressTransactionRelationship>;\n};\n\n/** System transaction for creating the alias state. */\nexport type AddressAliasStateCreateTransaction = {\n __typename?: 'AddressAliasStateCreateTransaction';\n /** A workaround to define an empty variant of a GraphQL union. */\n _?: Maybe<Scalars['Boolean']['output']>;\n};\n\n/**\n * Identifies a specific version of an address.\n *\n * Exactly one of `address` or `name` must be specified. Additionally, at most one of `rootVersion` or `atCheckpoint` can be specified. If neither bound is provided, the address is fetched at the checkpoint being viewed.\n *\n * See `Query.address` for more details.\n */\nexport type AddressKey = {\n /** The address. */\n address?: InputMaybe<Scalars['SuiAddress']['input']>;\n /** If specified, sets a checkpoint bound for this address. */\n atCheckpoint?: InputMaybe<Scalars['UInt53']['input']>;\n /** A SuiNS name to resolve to an address. */\n name?: InputMaybe<Scalars['String']['input']>;\n /** If specified, sets a root version bound for this address. */\n rootVersion?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n/** Object is exclusively owned by a single address, and is mutable. */\nexport type AddressOwner = {\n __typename?: 'AddressOwner';\n /** The owner's address. */\n address?: Maybe<Address>;\n};\n\n/** The possible relationship types for a transaction: sent or affected. */\nexport enum AddressTransactionRelationship {\n /** Transactions that this address was involved in, either as the sender, sponsor, or as the owner of some object that was created, modified or transferred. */\n Affected = 'AFFECTED',\n /** Transactions this address has sent. */\n Sent = 'SENT'\n}\n\n/** System transaction for creating the on-chain state used by zkLogin. */\nexport type AuthenticatorStateCreateTransaction = {\n __typename?: 'AuthenticatorStateCreateTransaction';\n /** A workaround to define an empty variant of a GraphQL union. */\n _?: Maybe<Scalars['Boolean']['output']>;\n};\n\n/** System transaction that is executed at the end of an epoch to expire JSON Web Keys (JWKs) that are no longer valid, based on their associated epoch. This is part of the on-chain state management for zkLogin and authentication. */\nexport type AuthenticatorStateExpireTransaction = {\n __typename?: 'AuthenticatorStateExpireTransaction';\n /** The initial version that the AuthenticatorStateUpdate was shared at. */\n authenticatorObjInitialSharedVersion?: Maybe<Scalars['UInt53']['output']>;\n /** Expire JWKs that have a lower epoch than this. */\n minEpoch?: Maybe<Epoch>;\n};\n\nexport type AuthenticatorStateUpdateTransaction = {\n __typename?: 'AuthenticatorStateUpdateTransaction';\n /** The initial version of the authenticator object that it was shared at. */\n authenticatorObjInitialSharedVersion?: Maybe<Scalars['UInt53']['output']>;\n /** Epoch of the authenticator state update transaction. */\n epoch?: Maybe<Epoch>;\n /** Newly active JWKs (JSON Web Keys). */\n newActiveJwks?: Maybe<ActiveJwkConnection>;\n /** Consensus round of the authenticator state update. */\n round?: Maybe<Scalars['UInt53']['output']>;\n};\n\n\nexport type AuthenticatorStateUpdateTransactionNewActiveJwksArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n/** Checkpoint range for which data is available. */\nexport type AvailableRange = {\n __typename?: 'AvailableRange';\n /** Inclusive lower checkpoint for which data is available. */\n first?: Maybe<Checkpoint>;\n /** Inclusive upper checkpoint for which data is available. */\n last?: Maybe<Checkpoint>;\n};\n\n/** The total balance for a particular coin type. */\nexport type Balance = {\n __typename?: 'Balance';\n /** The balance as tracked by the accumulator object for the address. */\n addressBalance?: Maybe<Scalars['BigInt']['output']>;\n /** Total balance across all owned coin objects of the coin type. */\n coinBalance?: Maybe<Scalars['BigInt']['output']>;\n /** Coin type for the balance, such as `0x2::sui::SUI`. */\n coinType?: Maybe<MoveType>;\n /** The sum total of the accumulator balance and individual coin balances owned by the address. */\n totalBalance?: Maybe<Scalars['BigInt']['output']>;\n};\n\n/** Effects to the balance (sum of coin values per coin type) of addresses and objects. */\nexport type BalanceChange = {\n __typename?: 'BalanceChange';\n /** The signed balance change. */\n amount?: Maybe<Scalars['BigInt']['output']>;\n /** The inner type of the coin whose balance has changed (e.g. `0x2::sui::SUI`). */\n coinType?: Maybe<MoveType>;\n /** The address or object whose balance has changed. */\n owner?: Maybe<Address>;\n};\n\nexport type BalanceChangeConnection = {\n __typename?: 'BalanceChangeConnection';\n /** A list of edges. */\n edges: Array<BalanceChangeEdge>;\n /** A list of nodes. */\n nodes: Array<BalanceChange>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type BalanceChangeEdge = {\n __typename?: 'BalanceChangeEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: BalanceChange;\n};\n\nexport type BalanceConnection = {\n __typename?: 'BalanceConnection';\n /** A list of edges. */\n edges: Array<BalanceEdge>;\n /** A list of nodes. */\n nodes: Array<Balance>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type BalanceEdge = {\n __typename?: 'BalanceEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: Balance;\n};\n\n/** Input for withdrawing funds from an accumulator. */\nexport type BalanceWithdraw = {\n __typename?: 'BalanceWithdraw';\n /** How much to withdraw from the accumulator. */\n reservation?: Maybe<WithdrawalReservation>;\n /** The type of the funds accumulator to withdraw from (e.g. `0x2::balance::Balance<0x2::sui::SUI>`). */\n type?: Maybe<MoveType>;\n /** The account to withdraw funds from. */\n withdrawFrom?: Maybe<WithdrawFrom>;\n};\n\n/** System transaction for initializing bridge committee. */\nexport type BridgeCommitteeInitTransaction = {\n __typename?: 'BridgeCommitteeInitTransaction';\n /** The initial shared version of the bridge object. */\n bridgeObjectVersion?: Maybe<Scalars['UInt53']['output']>;\n};\n\n/** System transaction for creating bridge state for cross-chain operations. */\nexport type BridgeStateCreateTransaction = {\n __typename?: 'BridgeStateCreateTransaction';\n /** The chain identifier for which this bridge state is being created. */\n chainIdentifier?: Maybe<Scalars['String']['output']>;\n};\n\n/**\n * A system transaction that updates epoch information on-chain (increments the current epoch). Executed by the system once per epoch, without using gas. Epoch change transactions cannot be submitted by users, because validators will refuse to sign them.\n *\n * This transaction kind is deprecated in favour of `EndOfEpochTransaction`.\n */\nexport type ChangeEpochTransaction = {\n __typename?: 'ChangeEpochTransaction';\n /** The total amount of gas charged for computation during the epoch. */\n computationCharge?: Maybe<Scalars['UInt53']['output']>;\n /** The next (to become) epoch. */\n epoch?: Maybe<Epoch>;\n /** Unix timestamp when epoch started. */\n epochStartTimestamp?: Maybe<Scalars['DateTime']['output']>;\n /** The non-refundable storage fee. */\n nonRefundableStorageFee?: Maybe<Scalars['UInt53']['output']>;\n /** The epoch's corresponding protocol configuration. */\n protocolConfigs?: Maybe<ProtocolConfigs>;\n /** The total amount of gas charged for storage during the epoch. */\n storageCharge?: Maybe<Scalars['UInt53']['output']>;\n /** The amount of storage rebate refunded to the transaction senders. */\n storageRebate?: Maybe<Scalars['UInt53']['output']>;\n /** System packages that will be written by validators before the new epoch starts, to upgrade them on-chain. These objects do not have a \"previous transaction\" because they are not written on-chain yet. Consult `effects.objectChanges` for this transaction to see the actual objects written. */\n systemPackages?: Maybe<MovePackageConnection>;\n};\n\n\n/**\n * A system transaction that updates epoch information on-chain (increments the current epoch). Executed by the system once per epoch, without using gas. Epoch change transactions cannot be submitted by users, because validators will refuse to sign them.\n *\n * This transaction kind is deprecated in favour of `EndOfEpochTransaction`.\n */\nexport type ChangeEpochTransactionSystemPackagesArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n/** Checkpoints contain finalized transactions and are used for node synchronization and global transaction ordering. */\nexport type Checkpoint = Node & {\n __typename?: 'Checkpoint';\n /**\n * A commitment by the committee at each checkpoint on the artifacts of the checkpoint.\n * e.g., object checkpoint states\n */\n artifactsDigest?: Maybe<Scalars['String']['output']>;\n /** The Base64 serialized BCS bytes of this checkpoint's contents. */\n contentBcs?: Maybe<Scalars['Base64']['output']>;\n /** A 32-byte hash that uniquely identifies the checkpoint's content, encoded in Base58. */\n contentDigest?: Maybe<Scalars['String']['output']>;\n /** A 32-byte hash that uniquely identifies the checkpoint, encoded in Base58. This is a hash of the checkpoint's summary. */\n digest?: Maybe<Scalars['String']['output']>;\n /** The epoch that this checkpoint is part of. */\n epoch?: Maybe<Epoch>;\n /** The checkpoint's globally unique identifier, which can be passed to `Query.node` to refetch it. */\n id: Scalars['ID']['output'];\n /** The total number of transactions in the network by the end of this checkpoint. */\n networkTotalTransactions?: Maybe<Scalars['UInt53']['output']>;\n /** The digest of the previous checkpoint's summary. */\n previousCheckpointDigest?: Maybe<Scalars['String']['output']>;\n /** Query the RPC as if this checkpoint were the latest checkpoint. */\n query?: Maybe<Query>;\n /** The computation cost, storage cost, storage rebate, and non-refundable storage fee accumulated during this epoch, up to and including this checkpoint. These values increase monotonically across checkpoints in the same epoch, and reset on epoch boundaries. */\n rollingGasSummary?: Maybe<GasCostSummary>;\n /** The checkpoint's position in the total order of finalized checkpoints, agreed upon by consensus. */\n sequenceNumber: Scalars['UInt53']['output'];\n /** The Base64 serialized BCS bytes of this checkpoint's summary. */\n summaryBcs?: Maybe<Scalars['Base64']['output']>;\n /** The timestamp at which the checkpoint is agreed to have happened according to consensus. Transactions that access time in this checkpoint will observe this timestamp. */\n timestamp?: Maybe<Scalars['DateTime']['output']>;\n transactions?: Maybe<TransactionConnection>;\n /** The aggregation of signatures from a quorum of validators for the checkpoint proposal. */\n validatorSignatures?: Maybe<ValidatorAggregatedSignature>;\n};\n\n\n/** Checkpoints contain finalized transactions and are used for node synchronization and global transaction ordering. */\nexport type CheckpointTransactionsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<TransactionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\nexport type CheckpointConnection = {\n __typename?: 'CheckpointConnection';\n /** A list of edges. */\n edges: Array<CheckpointEdge>;\n /** A list of nodes. */\n nodes: Array<Checkpoint>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type CheckpointEdge = {\n __typename?: 'CheckpointEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: Checkpoint;\n};\n\nexport type CheckpointFilter = {\n /** Limit query results to checkpoints that occured strictly after the given checkpoint. */\n afterCheckpoint?: InputMaybe<Scalars['UInt53']['input']>;\n /** Limit query results to checkpoints that occured at the given checkpoint. */\n atCheckpoint?: InputMaybe<Scalars['UInt53']['input']>;\n /** Limit query results to checkpoints at this epoch. */\n atEpoch?: InputMaybe<Scalars['UInt53']['input']>;\n /** Limit query results to checkpoints that occured strictly before the given checkpoint. */\n beforeCheckpoint?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n/** A G1 elliptic curve point with 3 base10-encoded Bn254 field elements. */\nexport type CircomG1 = {\n __typename?: 'CircomG1';\n e0?: Maybe<Scalars['String']['output']>;\n e1?: Maybe<Scalars['String']['output']>;\n e2?: Maybe<Scalars['String']['output']>;\n};\n\n/** A G2 elliptic curve point with 6 base10-encoded Bn254 field elements. */\nexport type CircomG2 = {\n __typename?: 'CircomG2';\n e00?: Maybe<Scalars['String']['output']>;\n e01?: Maybe<Scalars['String']['output']>;\n e10?: Maybe<Scalars['String']['output']>;\n e11?: Maybe<Scalars['String']['output']>;\n e20?: Maybe<Scalars['String']['output']>;\n e21?: Maybe<Scalars['String']['output']>;\n};\n\n/** System transaction for creating the coin deny list state. */\nexport type CoinDenyListStateCreateTransaction = {\n __typename?: 'CoinDenyListStateCreateTransaction';\n /** A workaround to define an empty variant of a GraphQL union. */\n _?: Maybe<Scalars['Boolean']['output']>;\n};\n\n/** An object representing metadata about a coin type. */\nexport type CoinMetadata = IAddressable & IMoveObject & IObject & {\n __typename?: 'CoinMetadata';\n /** The CoinMetadata's ID. */\n address: Scalars['SuiAddress']['output'];\n /**\n * Fetch the address as it was at a different root version, or checkpoint.\n *\n * If no additional bound is provided, the address is fetched at the latest checkpoint known to the RPC.\n */\n addressAt?: Maybe<Address>;\n /** Whether the `DenyCap` can be used to enable a global pause that behaves as if all addresses were added to the deny list. `null` indicates that it is not known whether the currency can be paused or not. This field is only populated on currencies held in the Coin Registry. To determine whether a legacy currency can be paused, check the contents of its `DenyCap`, if it can be found. */\n allowGlobalPause?: Maybe<Scalars['Boolean']['output']>;\n /**\n * Fetch the total balance for coins with marker type `coinType` (e.g. `0x2::sui::SUI`), owned by this address.\n *\n * If the address does not own any coins of that type, a balance of zero is returned.\n */\n balance?: Maybe<Balance>;\n /** Total balance across coins owned by this address, grouped by coin type. */\n balances?: Maybe<BalanceConnection>;\n /** The structured representation of the object's contents. */\n contents?: Maybe<MoveValue>;\n /** Number of decimal places the coin uses. */\n decimals?: Maybe<Scalars['Int']['output']>;\n /** The domain explicitly configured as the default Name Service name for this address. */\n defaultNameRecord?: Maybe<NameRecord>;\n /** If the currency is regulated, this object represents the capability to modify the deny list. If a capability is known but wrapped, its address can be fetched but other fields will not be accessible. */\n denyCap?: Maybe<MoveObject>;\n /** Description of the coin. */\n description?: Maybe<Scalars['String']['output']>;\n /** 32-byte hash that identifies the object's contents, encoded in Base58. */\n digest?: Maybe<Scalars['String']['output']>;\n /**\n * Access a dynamic field on an object using its type and BCS-encoded name.\n *\n * Returns `null` if a dynamic field with that name could not be found attached to this object.\n */\n dynamicField?: Maybe<DynamicField>;\n /**\n * Dynamic fields owned by this object.\n *\n * Dynamic fields on wrapped objects can be accessed using `Address.dynamicFields`.\n */\n dynamicFields?: Maybe<DynamicFieldConnection>;\n /**\n * Access a dynamic object field on an object using its type and BCS-encoded name.\n *\n * Returns `null` if a dynamic object field with that name could not be found attached to this object.\n */\n dynamicObjectField?: Maybe<DynamicField>;\n /**\n * Whether this object can be transfered using the `TransferObjects` Programmable Transaction Command or `sui::transfer::public_transfer`.\n *\n * Both these operations require the object to have both the `key` and `store` abilities.\n */\n hasPublicTransfer?: Maybe<Scalars['Boolean']['output']>;\n /** URL for the coin logo. */\n iconUrl?: Maybe<Scalars['String']['output']>;\n /** The Base64-encoded BCS serialize of this object, as a `MoveObject`. */\n moveObjectBcs?: Maybe<Scalars['Base64']['output']>;\n /**\n * Fetch the total balances keyed by coin types (e.g. `0x2::sui::SUI`) owned by this address.\n *\n * If the address does not own any coins of a given type, a balance of zero is returned for that type.\n */\n multiGetBalances?: Maybe<Array<Balance>>;\n /**\n * Access dynamic fields on an object using their types and BCS-encoded names.\n *\n * Returns a list of dynamic fields that is guaranteed to be the same length as `keys`. If a dynamic field in `keys` could not be found in the store, its corresponding entry in the result will be `null`.\n */\n multiGetDynamicFields: Array<Maybe<DynamicField>>;\n /**\n * Access dynamic object fields on an object using their types and BCS-encoded names.\n *\n * Returns a list of dynamic object fields that is guaranteed to be the same length as `keys`. If a dynamic object field in `keys` could not be found in the store, its corresponding entry in the result will be `null`.\n */\n multiGetDynamicObjectFields: Array<Maybe<DynamicField>>;\n /** Name for the coin. */\n name?: Maybe<Scalars['String']['output']>;\n /** Fetch the object with the same ID, at a different version, root version bound, or checkpoint. */\n objectAt?: Maybe<Object>;\n /** The Base64-encoded BCS serialization of this object, as an `Object`. */\n objectBcs?: Maybe<Scalars['Base64']['output']>;\n /** Paginate all versions of this object after this one. */\n objectVersionsAfter?: Maybe<ObjectConnection>;\n /** Paginate all versions of this object before this one. */\n objectVersionsBefore?: Maybe<ObjectConnection>;\n /** Objects owned by this object, optionally filtered by type. */\n objects?: Maybe<MoveObjectConnection>;\n /** The object's owner kind. */\n owner?: Maybe<Owner>;\n /** The transaction that created this version of the object. */\n previousTransaction?: Maybe<Transaction>;\n /** The transactions that sent objects to this object. */\n receivedTransactions?: Maybe<TransactionConnection>;\n /** Whether the currency is regulated or not. `null` indicates that the regulatory status is unknown. */\n regulatedState?: Maybe<RegulatedState>;\n /** The SUI returned to the sponsor or sender of the transaction that modifies or deletes this object. */\n storageRebate?: Maybe<Scalars['BigInt']['output']>;\n /** The overall balance of coins issued. */\n supply?: Maybe<Scalars['BigInt']['output']>;\n /** Future behavior of the supply. `null` indicates that the future behavior of the supply is not known because the currency's treasury still exists. */\n supplyState?: Maybe<SupplyState>;\n /** Symbol for the coin. */\n symbol?: Maybe<Scalars['String']['output']>;\n /** The version of this object that this content comes from. */\n version?: Maybe<Scalars['UInt53']['output']>;\n};\n\n\n/** An object representing metadata about a coin type. */\nexport type CoinMetadataAddressAtArgs = {\n checkpoint?: InputMaybe<Scalars['UInt53']['input']>;\n rootVersion?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\n/** An object representing metadata about a coin type. */\nexport type CoinMetadataBalanceArgs = {\n coinType: Scalars['String']['input'];\n};\n\n\n/** An object representing metadata about a coin type. */\nexport type CoinMetadataBalancesArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** An object representing metadata about a coin type. */\nexport type CoinMetadataDynamicFieldArgs = {\n name: DynamicFieldName;\n};\n\n\n/** An object representing metadata about a coin type. */\nexport type CoinMetadataDynamicFieldsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** An object representing metadata about a coin type. */\nexport type CoinMetadataDynamicObjectFieldArgs = {\n name: DynamicFieldName;\n};\n\n\n/** An object representing metadata about a coin type. */\nexport type CoinMetadataMultiGetBalancesArgs = {\n keys: Array<Scalars['String']['input']>;\n};\n\n\n/** An object representing metadata about a coin type. */\nexport type CoinMetadataMultiGetDynamicFieldsArgs = {\n keys: Array<DynamicFieldName>;\n};\n\n\n/** An object representing metadata about a coin type. */\nexport type CoinMetadataMultiGetDynamicObjectFieldsArgs = {\n keys: Array<DynamicFieldName>;\n};\n\n\n/** An object representing metadata about a coin type. */\nexport type CoinMetadataObjectAtArgs = {\n checkpoint?: InputMaybe<Scalars['UInt53']['input']>;\n rootVersion?: InputMaybe<Scalars['UInt53']['input']>;\n version?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\n/** An object representing metadata about a coin type. */\nexport type CoinMetadataObjectVersionsAfterArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<VersionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** An object representing metadata about a coin type. */\nexport type CoinMetadataObjectVersionsBeforeArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<VersionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** An object representing metadata about a coin type. */\nexport type CoinMetadataObjectsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<ObjectFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** An object representing metadata about a coin type. */\nexport type CoinMetadataReceivedTransactionsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<TransactionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n/** System transaction for creating the coin registry. */\nexport type CoinRegistryCreateTransaction = {\n __typename?: 'CoinRegistryCreateTransaction';\n /** A workaround to define an empty variant of a GraphQL union. */\n _?: Maybe<Scalars['Boolean']['output']>;\n};\n\n/** A single command in the programmable transaction. */\nexport type Command = MakeMoveVecCommand | MergeCoinsCommand | MoveCallCommand | OtherCommand | PublishCommand | SplitCoinsCommand | TransferObjectsCommand | UpgradeCommand;\n\nexport type CommandConnection = {\n __typename?: 'CommandConnection';\n /** A list of edges. */\n edges: Array<CommandEdge>;\n /** A list of nodes. */\n nodes: Array<Command>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type CommandEdge = {\n __typename?: 'CommandEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: Command;\n};\n\n/**\n * A value produced or modified during command execution.\n *\n * This can represent either a return value from a command or an argument that was mutated by reference.\n */\nexport type CommandOutput = {\n __typename?: 'CommandOutput';\n /** The transaction argument that this value corresponds to (if any). */\n argument?: Maybe<TransactionArgument>;\n /** The structured Move value, if available. */\n value?: Maybe<MoveValue>;\n};\n\n/** The intermediate results for each command of a transaction simulation. */\nexport type CommandResult = {\n __typename?: 'CommandResult';\n /** Changes made to arguments that were mutably borrowed by each command in this transaction. */\n mutatedReferences?: Maybe<Array<CommandOutput>>;\n /** Return results of each command in this transaction. */\n returnValues?: Maybe<Array<CommandOutput>>;\n};\n\n/** Object is exclusively owned by a single adderss and sequenced via consensus. */\nexport type ConsensusAddressOwner = {\n __typename?: 'ConsensusAddressOwner';\n /** The owner's address. */\n address?: Maybe<Address>;\n /** The version at which the object most recently bcame a consensus object. This serves the same function as `Shared.initialSharedVersion`, except it may change if the object's `owner` type changes. */\n startVersion?: Maybe<Scalars['UInt53']['output']>;\n};\n\n/** System transaction that runs at the beginning of a checkpoint, and is responsible for setting the current value of the clock, based on the timestamp from consensus. */\nexport type ConsensusCommitPrologueTransaction = {\n __typename?: 'ConsensusCommitPrologueTransaction';\n /**\n * Digest of any additional state computed by the consensus handler.\n * Used to detect forking bugs as early as possible.\n *\n * Present in V4.\n */\n additionalStateDigest?: Maybe<Scalars['String']['output']>;\n /**\n * Unix timestamp from consensus.\n *\n * Present in V1, V2, V3, V4.\n */\n commitTimestamp?: Maybe<Scalars['DateTime']['output']>;\n /**\n * Digest of consensus output, encoded as a Base58 string.\n *\n * Present in V2, V3, V4.\n */\n consensusCommitDigest?: Maybe<Scalars['String']['output']>;\n /**\n * Epoch of the commit prologue transaction.\n *\n * Present in V1, V2, V3, V4.\n */\n epoch?: Maybe<Epoch>;\n /**\n * Consensus round of the commit.\n *\n * Present in V1, V2, V3, V4.\n */\n round?: Maybe<Scalars['UInt53']['output']>;\n /**\n * The sub DAG index of the consensus commit. This field is populated if there\n * are multiple consensus commits per round.\n *\n * Present in V3, V4.\n */\n subDagIndex?: Maybe<Scalars['UInt53']['output']>;\n};\n\n/** Reason why a transaction that attempted to access a consensus-managed object was cancelled. */\nexport enum ConsensusObjectCancellationReason {\n /** Read operation was cancelled. */\n CancelledRead = 'CANCELLED_READ',\n /** Object congestion prevented execution. */\n Congested = 'CONGESTED',\n /** Randomness service was unavailable. */\n RandomnessUnavailable = 'RANDOMNESS_UNAVAILABLE',\n /** Internal use only. */\n Unknown = 'UNKNOWN'\n}\n\n/** A transaction that was cancelled before it could access the consensus-managed object, so the object was an input but remained unchanged. */\nexport type ConsensusObjectCancelled = {\n __typename?: 'ConsensusObjectCancelled';\n /** The ID of the consensus-managed object that the transaction intended to access. */\n address?: Maybe<Scalars['SuiAddress']['output']>;\n /** Reason why the transaction was cancelled. */\n cancellationReason?: Maybe<ConsensusObjectCancellationReason>;\n};\n\nexport type ConsensusObjectRead = {\n __typename?: 'ConsensusObjectRead';\n /** The version of the consensus-managed object that was read by this transaction. */\n object?: Maybe<Object>;\n};\n\n/** A rendered JSON blob based on an on-chain template. */\nexport type Display = {\n __typename?: 'Display';\n /** If any fields failed to render, this will contain a mapping from failed field names to error messages. If all fields succeed, this will be `null`. */\n errors?: Maybe<Scalars['JSON']['output']>;\n /** Output for all successfully substituted display fields. Unsuccessful fields will be `null`, and will be accompanied by a field in `errors`, explaining the error. */\n output?: Maybe<Scalars['JSON']['output']>;\n};\n\n/** System transaction for creating the display registry. */\nexport type DisplayRegistryCreateTransaction = {\n __typename?: 'DisplayRegistryCreateTransaction';\n /** A workaround to define an empty variant of a GraphQL union. */\n _?: Maybe<Scalars['Boolean']['output']>;\n};\n\n/**\n * Dynamic fields are heterogenous fields that can be added or removed from an object at runtime. Their names are arbitrary Move values that have `copy`, `drop`, and `store`.\n *\n * There are two sub-types of dynamic fields:\n *\n * - Dynamic fields can store any value that has `store`. Objects stored in this kind of field will be considered wrapped (not accessible via its ID by external tools like explorers, wallets, etc. accessing storage).\n * - Dynamic object fields can only store objects (values that have the `key` ability, and an `id: UID` as its first field) that have `store`, but they will still be directly accessible off-chain via their ID after being attached as a field.\n */\nexport type DynamicField = IAddressable & IMoveObject & IObject & Node & {\n __typename?: 'DynamicField';\n /** The DynamicField's ID. */\n address: Scalars['SuiAddress']['output'];\n /**\n * Fetch the address as it was at a different root version, or checkpoint.\n *\n * If no additional bound is provided, the address is fetched at the latest checkpoint known to the RPC.\n */\n addressAt?: Maybe<Address>;\n /**\n * Fetch the total balance for coins with marker type `coinType` (e.g. `0x2::sui::SUI`), owned by this address.\n *\n * If the address does not own any coins of that type, a balance of zero is returned.\n */\n balance?: Maybe<Balance>;\n /** Total balance across coins owned by this address, grouped by coin type. */\n balances?: Maybe<BalanceConnection>;\n /** The structured representation of the object's contents. */\n contents?: Maybe<MoveValue>;\n /** The domain explicitly configured as the default Name Service name for this address. */\n defaultNameRecord?: Maybe<NameRecord>;\n /** 32-byte hash that identifies the object's contents, encoded in Base58. */\n digest?: Maybe<Scalars['String']['output']>;\n /**\n * Access a dynamic field on an object using its type and BCS-encoded name.\n *\n * Returns `null` if a dynamic field with that name could not be found attached to this object.\n */\n dynamicField?: Maybe<DynamicField>;\n /**\n * Dynamic fields owned by this object.\n *\n * Dynamic fields on wrapped objects can be accessed using `Address.dynamicFields`.\n */\n dynamicFields?: Maybe<DynamicFieldConnection>;\n /**\n * Access a dynamic object field on an object using its type and BCS-encoded name.\n *\n * Returns `null` if a dynamic object field with that name could not be found attached to this object.\n */\n dynamicObjectField?: Maybe<DynamicField>;\n /**\n * Whether this object can be transfered using the `TransferObjects` Programmable Transaction Command or `sui::transfer::public_transfer`.\n *\n * Both these operations require the object to have both the `key` and `store` abilities.\n */\n hasPublicTransfer?: Maybe<Scalars['Boolean']['output']>;\n /** The dynamic field's globally unique identifier, which can be passed to `Query.node` to refetch it. */\n id: Scalars['ID']['output'];\n /** The Base64-encoded BCS serialize of this object, as a `MoveObject`. */\n moveObjectBcs?: Maybe<Scalars['Base64']['output']>;\n /**\n * Fetch the total balances keyed by coin types (e.g. `0x2::sui::SUI`) owned by this address.\n *\n * If the address does not own any coins of a given type, a balance of zero is returned for that type.\n */\n multiGetBalances?: Maybe<Array<Balance>>;\n /**\n * Access dynamic fields on an object using their types and BCS-encoded names.\n *\n * Returns a list of dynamic fields that is guaranteed to be the same length as `keys`. If a dynamic field in `keys` could not be found in the store, its corresponding entry in the result will be `null`.\n */\n multiGetDynamicFields: Array<Maybe<DynamicField>>;\n /**\n * Access dynamic object fields on an object using their types and BCS-encoded names.\n *\n * Returns a list of dynamic object fields that is guaranteed to be the same length as `keys`. If a dynamic object field in `keys` could not be found in the store, its corresponding entry in the result will be `null`.\n */\n multiGetDynamicObjectFields: Array<Maybe<DynamicField>>;\n /** The dynamic field's name, as a Move value. */\n name?: Maybe<MoveValue>;\n /** Fetch the object with the same ID, at a different version, root version bound, or checkpoint. */\n objectAt?: Maybe<Object>;\n /** The Base64-encoded BCS serialization of this object, as an `Object`. */\n objectBcs?: Maybe<Scalars['Base64']['output']>;\n /** Paginate all versions of this object after this one. */\n objectVersionsAfter?: Maybe<ObjectConnection>;\n /** Paginate all versions of this object before this one. */\n objectVersionsBefore?: Maybe<ObjectConnection>;\n /** Objects owned by this object, optionally filtered by type. */\n objects?: Maybe<MoveObjectConnection>;\n /** The object's owner kind. */\n owner?: Maybe<Owner>;\n /** The transaction that created this version of the object. */\n previousTransaction?: Maybe<Transaction>;\n /** The transactions that sent objects to this object. */\n receivedTransactions?: Maybe<TransactionConnection>;\n /** The SUI returned to the sponsor or sender of the transaction that modifies or deletes this object. */\n storageRebate?: Maybe<Scalars['BigInt']['output']>;\n /** The dynamic field's value, as a Move value for dynamic fields and as a MoveObject for dynamic object fields. */\n value?: Maybe<DynamicFieldValue>;\n /** The version of this object that this content comes from. */\n version?: Maybe<Scalars['UInt53']['output']>;\n};\n\n\n/**\n * Dynamic fields are heterogenous fields that can be added or removed from an object at runtime. Their names are arbitrary Move values that have `copy`, `drop`, and `store`.\n *\n * There are two sub-types of dynamic fields:\n *\n * - Dynamic fields can store any value that has `store`. Objects stored in this kind of field will be considered wrapped (not accessible via its ID by external tools like explorers, wallets, etc. accessing storage).\n * - Dynamic object fields can only store objects (values that have the `key` ability, and an `id: UID` as its first field) that have `store`, but they will still be directly accessible off-chain via their ID after being attached as a field.\n */\nexport type DynamicFieldAddressAtArgs = {\n checkpoint?: InputMaybe<Scalars['UInt53']['input']>;\n rootVersion?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\n/**\n * Dynamic fields are heterogenous fields that can be added or removed from an object at runtime. Their names are arbitrary Move values that have `copy`, `drop`, and `store`.\n *\n * There are two sub-types of dynamic fields:\n *\n * - Dynamic fields can store any value that has `store`. Objects stored in this kind of field will be considered wrapped (not accessible via its ID by external tools like explorers, wallets, etc. accessing storage).\n * - Dynamic object fields can only store objects (values that have the `key` ability, and an `id: UID` as its first field) that have `store`, but they will still be directly accessible off-chain via their ID after being attached as a field.\n */\nexport type DynamicFieldBalanceArgs = {\n coinType: Scalars['String']['input'];\n};\n\n\n/**\n * Dynamic fields are heterogenous fields that can be added or removed from an object at runtime. Their names are arbitrary Move values that have `copy`, `drop`, and `store`.\n *\n * There are two sub-types of dynamic fields:\n *\n * - Dynamic fields can store any value that has `store`. Objects stored in this kind of field will be considered wrapped (not accessible via its ID by external tools like explorers, wallets, etc. accessing storage).\n * - Dynamic object fields can only store objects (values that have the `key` ability, and an `id: UID` as its first field) that have `store`, but they will still be directly accessible off-chain via their ID after being attached as a field.\n */\nexport type DynamicFieldBalancesArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/**\n * Dynamic fields are heterogenous fields that can be added or removed from an object at runtime. Their names are arbitrary Move values that have `copy`, `drop`, and `store`.\n *\n * There are two sub-types of dynamic fields:\n *\n * - Dynamic fields can store any value that has `store`. Objects stored in this kind of field will be considered wrapped (not accessible via its ID by external tools like explorers, wallets, etc. accessing storage).\n * - Dynamic object fields can only store objects (values that have the `key` ability, and an `id: UID` as its first field) that have `store`, but they will still be directly accessible off-chain via their ID after being attached as a field.\n */\nexport type DynamicFieldDynamicFieldArgs = {\n name: DynamicFieldName;\n};\n\n\n/**\n * Dynamic fields are heterogenous fields that can be added or removed from an object at runtime. Their names are arbitrary Move values that have `copy`, `drop`, and `store`.\n *\n * There are two sub-types of dynamic fields:\n *\n * - Dynamic fields can store any value that has `store`. Objects stored in this kind of field will be considered wrapped (not accessible via its ID by external tools like explorers, wallets, etc. accessing storage).\n * - Dynamic object fields can only store objects (values that have the `key` ability, and an `id: UID` as its first field) that have `store`, but they will still be directly accessible off-chain via their ID after being attached as a field.\n */\nexport type DynamicFieldDynamicFieldsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/**\n * Dynamic fields are heterogenous fields that can be added or removed from an object at runtime. Their names are arbitrary Move values that have `copy`, `drop`, and `store`.\n *\n * There are two sub-types of dynamic fields:\n *\n * - Dynamic fields can store any value that has `store`. Objects stored in this kind of field will be considered wrapped (not accessible via its ID by external tools like explorers, wallets, etc. accessing storage).\n * - Dynamic object fields can only store objects (values that have the `key` ability, and an `id: UID` as its first field) that have `store`, but they will still be directly accessible off-chain via their ID after being attached as a field.\n */\nexport type DynamicFieldDynamicObjectFieldArgs = {\n name: DynamicFieldName;\n};\n\n\n/**\n * Dynamic fields are heterogenous fields that can be added or removed from an object at runtime. Their names are arbitrary Move values that have `copy`, `drop`, and `store`.\n *\n * There are two sub-types of dynamic fields:\n *\n * - Dynamic fields can store any value that has `store`. Objects stored in this kind of field will be considered wrapped (not accessible via its ID by external tools like explorers, wallets, etc. accessing storage).\n * - Dynamic object fields can only store objects (values that have the `key` ability, and an `id: UID` as its first field) that have `store`, but they will still be directly accessible off-chain via their ID after being attached as a field.\n */\nexport type DynamicFieldMultiGetBalancesArgs = {\n keys: Array<Scalars['String']['input']>;\n};\n\n\n/**\n * Dynamic fields are heterogenous fields that can be added or removed from an object at runtime. Their names are arbitrary Move values that have `copy`, `drop`, and `store`.\n *\n * There are two sub-types of dynamic fields:\n *\n * - Dynamic fields can store any value that has `store`. Objects stored in this kind of field will be considered wrapped (not accessible via its ID by external tools like explorers, wallets, etc. accessing storage).\n * - Dynamic object fields can only store objects (values that have the `key` ability, and an `id: UID` as its first field) that have `store`, but they will still be directly accessible off-chain via their ID after being attached as a field.\n */\nexport type DynamicFieldMultiGetDynamicFieldsArgs = {\n keys: Array<DynamicFieldName>;\n};\n\n\n/**\n * Dynamic fields are heterogenous fields that can be added or removed from an object at runtime. Their names are arbitrary Move values that have `copy`, `drop`, and `store`.\n *\n * There are two sub-types of dynamic fields:\n *\n * - Dynamic fields can store any value that has `store`. Objects stored in this kind of field will be considered wrapped (not accessible via its ID by external tools like explorers, wallets, etc. accessing storage).\n * - Dynamic object fields can only store objects (values that have the `key` ability, and an `id: UID` as its first field) that have `store`, but they will still be directly accessible off-chain via their ID after being attached as a field.\n */\nexport type DynamicFieldMultiGetDynamicObjectFieldsArgs = {\n keys: Array<DynamicFieldName>;\n};\n\n\n/**\n * Dynamic fields are heterogenous fields that can be added or removed from an object at runtime. Their names are arbitrary Move values that have `copy`, `drop`, and `store`.\n *\n * There are two sub-types of dynamic fields:\n *\n * - Dynamic fields can store any value that has `store`. Objects stored in this kind of field will be considered wrapped (not accessible via its ID by external tools like explorers, wallets, etc. accessing storage).\n * - Dynamic object fields can only store objects (values that have the `key` ability, and an `id: UID` as its first field) that have `store`, but they will still be directly accessible off-chain via their ID after being attached as a field.\n */\nexport type DynamicFieldObjectAtArgs = {\n checkpoint?: InputMaybe<Scalars['UInt53']['input']>;\n rootVersion?: InputMaybe<Scalars['UInt53']['input']>;\n version?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\n/**\n * Dynamic fields are heterogenous fields that can be added or removed from an object at runtime. Their names are arbitrary Move values that have `copy`, `drop`, and `store`.\n *\n * There are two sub-types of dynamic fields:\n *\n * - Dynamic fields can store any value that has `store`. Objects stored in this kind of field will be considered wrapped (not accessible via its ID by external tools like explorers, wallets, etc. accessing storage).\n * - Dynamic object fields can only store objects (values that have the `key` ability, and an `id: UID` as its first field) that have `store`, but they will still be directly accessible off-chain via their ID after being attached as a field.\n */\nexport type DynamicFieldObjectVersionsAfterArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<VersionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/**\n * Dynamic fields are heterogenous fields that can be added or removed from an object at runtime. Their names are arbitrary Move values that have `copy`, `drop`, and `store`.\n *\n * There are two sub-types of dynamic fields:\n *\n * - Dynamic fields can store any value that has `store`. Objects stored in this kind of field will be considered wrapped (not accessible via its ID by external tools like explorers, wallets, etc. accessing storage).\n * - Dynamic object fields can only store objects (values that have the `key` ability, and an `id: UID` as its first field) that have `store`, but they will still be directly accessible off-chain via their ID after being attached as a field.\n */\nexport type DynamicFieldObjectVersionsBeforeArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<VersionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/**\n * Dynamic fields are heterogenous fields that can be added or removed from an object at runtime. Their names are arbitrary Move values that have `copy`, `drop`, and `store`.\n *\n * There are two sub-types of dynamic fields:\n *\n * - Dynamic fields can store any value that has `store`. Objects stored in this kind of field will be considered wrapped (not accessible via its ID by external tools like explorers, wallets, etc. accessing storage).\n * - Dynamic object fields can only store objects (values that have the `key` ability, and an `id: UID` as its first field) that have `store`, but they will still be directly accessible off-chain via their ID after being attached as a field.\n */\nexport type DynamicFieldObjectsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<ObjectFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/**\n * Dynamic fields are heterogenous fields that can be added or removed from an object at runtime. Their names are arbitrary Move values that have `copy`, `drop`, and `store`.\n *\n * There are two sub-types of dynamic fields:\n *\n * - Dynamic fields can store any value that has `store`. Objects stored in this kind of field will be considered wrapped (not accessible via its ID by external tools like explorers, wallets, etc. accessing storage).\n * - Dynamic object fields can only store objects (values that have the `key` ability, and an `id: UID` as its first field) that have `store`, but they will still be directly accessible off-chain via their ID after being attached as a field.\n */\nexport type DynamicFieldReceivedTransactionsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<TransactionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\nexport type DynamicFieldConnection = {\n __typename?: 'DynamicFieldConnection';\n /** A list of edges. */\n edges: Array<DynamicFieldEdge>;\n /** A list of nodes. */\n nodes: Array<DynamicField>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type DynamicFieldEdge = {\n __typename?: 'DynamicFieldEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: DynamicField;\n};\n\n/**\n * A description of a dynamic field's name.\n *\n * Names can either be given as serialized `bcs` accompanied by its `type`, or as a Display v2 `literal` expression. Other combinations of inputs are not supported.\n */\nexport type DynamicFieldName = {\n /** The Base64-encoded BCS serialization of the dynamic field's 'name'. */\n bcs?: InputMaybe<Scalars['Base64']['input']>;\n /** The name represented as a Display v2 literal expression. */\n literal?: InputMaybe<Scalars['String']['input']>;\n /** The type of the dynamic field's name, like 'u64' or '0x2::kiosk::Listing'. */\n type?: InputMaybe<Scalars['String']['input']>;\n};\n\n/** The value of a dynamic field (`MoveValue`) or dynamic object field (`MoveObject`). */\nexport type DynamicFieldValue = MoveObject | MoveValue;\n\n/** An Ed25519 public key. */\nexport type Ed25519PublicKey = {\n __typename?: 'Ed25519PublicKey';\n /** The raw public key bytes. */\n bytes?: Maybe<Scalars['Base64']['output']>;\n};\n\n/** An Ed25519 signature. */\nexport type Ed25519Signature = {\n __typename?: 'Ed25519Signature';\n /** The public key bytes. */\n publicKey?: Maybe<Scalars['Base64']['output']>;\n /** The raw signature bytes. */\n signature?: Maybe<Scalars['Base64']['output']>;\n};\n\n/** System transaction that supersedes `ChangeEpochTransaction` as the new way to run transactions at the end of an epoch. Behaves similarly to `ChangeEpochTransaction` but can accommodate other optional transactions to run at the end of the epoch. */\nexport type EndOfEpochTransaction = {\n __typename?: 'EndOfEpochTransaction';\n /** The list of system transactions that are allowed to run at the end of the epoch. */\n transactions?: Maybe<EndOfEpochTransactionKindConnection>;\n};\n\n\n/** System transaction that supersedes `ChangeEpochTransaction` as the new way to run transactions at the end of an epoch. Behaves similarly to `ChangeEpochTransaction` but can accommodate other optional transactions to run at the end of the epoch. */\nexport type EndOfEpochTransactionTransactionsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\nexport type EndOfEpochTransactionKind = AccumulatorRootCreateTransaction | AddressAliasStateCreateTransaction | AuthenticatorStateCreateTransaction | AuthenticatorStateExpireTransaction | BridgeCommitteeInitTransaction | BridgeStateCreateTransaction | ChangeEpochTransaction | CoinDenyListStateCreateTransaction | CoinRegistryCreateTransaction | DisplayRegistryCreateTransaction | RandomnessStateCreateTransaction | StoreExecutionTimeObservationsTransaction | WriteAccumulatorStorageCostTransaction;\n\nexport type EndOfEpochTransactionKindConnection = {\n __typename?: 'EndOfEpochTransactionKindConnection';\n /** A list of edges. */\n edges: Array<EndOfEpochTransactionKindEdge>;\n /** A list of nodes. */\n nodes: Array<EndOfEpochTransactionKind>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type EndOfEpochTransactionKindEdge = {\n __typename?: 'EndOfEpochTransactionKindEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: EndOfEpochTransactionKind;\n};\n\n/**\n * Activity on Sui is partitioned in time, into epochs.\n *\n * Epoch changes are opportunities for the network to reconfigure itself (perform protocol or system package upgrades, or change the committee) and distribute staking rewards. The network aims to keep epochs roughly the same duration as each other.\n *\n * During a particular epoch the following data is fixed:\n *\n * - protocol version,\n * - reference gas price,\n * - system package versions,\n * - validators in the committee.\n */\nexport type Epoch = Node & {\n __typename?: 'Epoch';\n /** The epoch's corresponding checkpoints. */\n checkpoints?: Maybe<CheckpointConnection>;\n /**\n * State of the Coin DenyList object (0x403) at the start of this epoch.\n *\n * The DenyList controls access to Regulated Coins. Writes to the DenyList are accumulated and only take effect on the next epoch boundary. Consequently, it's possible to determine the state of the DenyList for a transaction by reading it at the start of the epoch the transaction is in.\n */\n coinDenyList?: Maybe<Object>;\n /** The timestamp associated with the last checkpoint in the epoch (or `null` if the epoch has not finished yet). */\n endTimestamp?: Maybe<Scalars['DateTime']['output']>;\n /** The epoch's id as a sequence number that starts at 0 and is incremented by one at every epoch change. */\n epochId: Scalars['UInt53']['output'];\n /** The storage fees paid for transactions executed during the epoch (or `null` if the epoch has not finished yet). */\n fundInflow?: Maybe<Scalars['BigInt']['output']>;\n /** The storage fee rebates paid to users who deleted the data associated with past transactions (or `null` if the epoch has not finished yet). */\n fundOutflow?: Maybe<Scalars['BigInt']['output']>;\n /**\n * The storage fund available in this epoch (or `null` if the epoch has not finished yet).\n * This fund is used to redistribute storage fees from past transactions to future validators.\n */\n fundSize?: Maybe<Scalars['BigInt']['output']>;\n /** The epoch's globally unique identifier, which can be passed to `Query.node` to refetch it. */\n id: Scalars['ID']['output'];\n /**\n * A commitment by the committee at the end of epoch on the contents of the live object set at that time.\n * This can be used to verify state snapshots.\n */\n liveObjectSetDigest?: Maybe<Scalars['String']['output']>;\n /** The difference between the fund inflow and outflow, representing the net amount of storage fees accumulated in this epoch (or `null` if the epoch has not finished yet). */\n netInflow?: Maybe<Scalars['BigInt']['output']>;\n /** The epoch's corresponding protocol configuration, including the feature flags and the configuration options. */\n protocolConfigs?: Maybe<ProtocolConfigs>;\n /** The minimum gas price that a quorum of validators are guaranteed to sign a transaction for in this epoch. */\n referenceGasPrice?: Maybe<Scalars['BigInt']['output']>;\n /** The timestamp associated with the first checkpoint in the epoch. */\n startTimestamp?: Maybe<Scalars['DateTime']['output']>;\n /** The system packages used by all transactions in this epoch. */\n systemPackages?: Maybe<MovePackageConnection>;\n /** The contents of the system state inner object at the start of this epoch. */\n systemState?: Maybe<MoveValue>;\n /**\n * The total number of checkpoints in this epoch.\n *\n * Returns `None` when no checkpoint is set in scope (e.g. execution scope).\n */\n totalCheckpoints?: Maybe<Scalars['UInt53']['output']>;\n /** The total amount of gas fees (in MIST) that were paid in this epoch (or `null` if the epoch has not finished yet). */\n totalGasFees?: Maybe<Scalars['BigInt']['output']>;\n /** The total MIST rewarded as stake (or `null` if the epoch has not finished yet). */\n totalStakeRewards?: Maybe<Scalars['BigInt']['output']>;\n /** The amount added to total gas fees to make up the total stake rewards (or `null` if the epoch has not finished yet). */\n totalStakeSubsidies?: Maybe<Scalars['BigInt']['output']>;\n /**\n * The total number of transaction blocks in this epoch.\n *\n * If the epoch has not finished yet, this number is computed based on the number of transactions at the latest known checkpoint.\n */\n totalTransactions?: Maybe<Scalars['UInt53']['output']>;\n /**\n * The transactions in this epoch, optionally filtered by transaction filters.\n *\n * Returns `None` when no checkpoint is set in scope (e.g. execution scope).\n */\n transactions?: Maybe<TransactionConnection>;\n /** Validator-related properties, including the active validators. */\n validatorSet?: Maybe<ValidatorSet>;\n};\n\n\n/**\n * Activity on Sui is partitioned in time, into epochs.\n *\n * Epoch changes are opportunities for the network to reconfigure itself (perform protocol or system package upgrades, or change the committee) and distribute staking rewards. The network aims to keep epochs roughly the same duration as each other.\n *\n * During a particular epoch the following data is fixed:\n *\n * - protocol version,\n * - reference gas price,\n * - system package versions,\n * - validators in the committee.\n */\nexport type EpochCheckpointsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<CheckpointFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/**\n * Activity on Sui is partitioned in time, into epochs.\n *\n * Epoch changes are opportunities for the network to reconfigure itself (perform protocol or system package upgrades, or change the committee) and distribute staking rewards. The network aims to keep epochs roughly the same duration as each other.\n *\n * During a particular epoch the following data is fixed:\n *\n * - protocol version,\n * - reference gas price,\n * - system package versions,\n * - validators in the committee.\n */\nexport type EpochSystemPackagesArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/**\n * Activity on Sui is partitioned in time, into epochs.\n *\n * Epoch changes are opportunities for the network to reconfigure itself (perform protocol or system package upgrades, or change the committee) and distribute staking rewards. The network aims to keep epochs roughly the same duration as each other.\n *\n * During a particular epoch the following data is fixed:\n *\n * - protocol version,\n * - reference gas price,\n * - system package versions,\n * - validators in the committee.\n */\nexport type EpochTransactionsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<TransactionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\nexport type EpochConnection = {\n __typename?: 'EpochConnection';\n /** A list of edges. */\n edges: Array<EpochEdge>;\n /** A list of nodes. */\n nodes: Array<Epoch>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type EpochEdge = {\n __typename?: 'EpochEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: Epoch;\n};\n\nexport type Event = {\n __typename?: 'Event';\n /** The Move value emitted for this event. */\n contents?: Maybe<MoveValue>;\n /**\n * The Base64 encoded BCS serialized bytes of the entire Event structure from sui-types.\n * This includes: package_id, transaction_module, sender, type, and contents (which itself contains the BCS-serialized Move struct data).\n */\n eventBcs?: Maybe<Scalars['Base64']['output']>;\n /** Address of the sender of the transaction that emitted this event. */\n sender?: Maybe<Address>;\n /** The position of the event among the events from the same transaction. */\n sequenceNumber: Scalars['UInt53']['output'];\n /**\n * Timestamp corresponding to the checkpoint this event's transaction was finalized in.\n * All events from the same transaction share the same timestamp.\n *\n * `null` for simulated/executed transactions as they are not included in a checkpoint.\n */\n timestamp?: Maybe<Scalars['DateTime']['output']>;\n /** The transaction that emitted this event. This information is only available for events from indexed transactions, and not from transactions that have just been executed or dry-run. */\n transaction?: Maybe<Transaction>;\n /** The module containing the function that was called in the programmable transaction, that resulted in this event being emitted. */\n transactionModule?: Maybe<MoveModule>;\n};\n\nexport type EventConnection = {\n __typename?: 'EventConnection';\n /** A list of edges. */\n edges: Array<EventEdge>;\n /** A list of nodes. */\n nodes: Array<Event>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type EventEdge = {\n __typename?: 'EventEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: Event;\n};\n\nexport type EventFilter = {\n /** Limit to events that occured strictly after the given checkpoint. */\n afterCheckpoint?: InputMaybe<Scalars['UInt53']['input']>;\n /** Limit to events in the given checkpoint. */\n atCheckpoint?: InputMaybe<Scalars['UInt53']['input']>;\n /** Limit to event that occured strictly before the given checkpoint. */\n beforeCheckpoint?: InputMaybe<Scalars['UInt53']['input']>;\n /**\n * Events emitted by a particular module. An event is emitted by a particular module if some function in the module is called by a PTB and emits an event.\n *\n * Modules can be filtered by their package, or package::module. We currently do not support filtering by emitting module and event type at the same time so if both are provided in one filter, the query will error.\n */\n module?: InputMaybe<Scalars['String']['input']>;\n /** Filter on events by transaction sender address. */\n sender?: InputMaybe<Scalars['SuiAddress']['input']>;\n /**\n * This field is used to specify the type of event emitted.\n *\n * Events can be filtered by their type's package, package::module, or their fully qualified type name.\n *\n * Generic types can be queried by either the generic type name, e.g. `0x2::coin::Coin`, or by the full type name, such as `0x2::coin::Coin<0x2::sui::SUI>`.\n */\n type?: InputMaybe<Scalars['String']['input']>;\n};\n\n/** Represents execution error information for failed transactions. */\nexport type ExecutionError = {\n __typename?: 'ExecutionError';\n /**\n * The error code of the Move abort, populated if this transaction failed with a Move abort.\n *\n * Returns the explicit code if the abort used `code` annotation (e.g., `abort(ERR, code = 5)` returns 5), otherwise returns the raw abort code containing encoded error information.\n */\n abortCode?: Maybe<Scalars['BigInt']['output']>;\n /**\n * An associated constant for the error. Only populated for clever errors.\n *\n * Constants are returned as human-readable strings when possible. Complex types are returned as Base64-encoded bytes.\n */\n constant?: Maybe<Scalars['String']['output']>;\n /** The function that the abort originated from. Only populated for Move aborts and primitive runtime errors that have function name information. */\n function?: Maybe<MoveFunction>;\n /** The error's name. Only populated for clever errors. */\n identifier?: Maybe<Scalars['String']['output']>;\n /** The instruction offset in the Move bytecode where the error occurred. Populated for Move aborts and primitive runtime errors. */\n instructionOffset?: Maybe<Scalars['Int']['output']>;\n /**\n * Human readable explanation of why the transaction failed.\n *\n * For Move aborts, the error message will be resolved to a human-readable form if possible, otherwise it will fall back to displaying the abort code and location.\n */\n message: Scalars['String']['output'];\n /** The module that the abort originated from. Only populated for Move aborts and primitive runtime errors. */\n module?: Maybe<MoveModule>;\n /** The source line number for the abort. Only populated for clever errors. */\n sourceLineNumber?: Maybe<Scalars['Int']['output']>;\n};\n\n/** The execution result of a transaction, including the transaction effects. */\nexport type ExecutionResult = {\n __typename?: 'ExecutionResult';\n /** The effects of the transaction execution. */\n effects?: Maybe<TransactionEffects>;\n};\n\n/** The execution status of this transaction: success or failure. */\nexport enum ExecutionStatus {\n /** The transaction could not be executed. */\n Failure = 'FAILURE',\n /** The transaction was successfully executed. */\n Success = 'SUCCESS'\n}\n\n/** A boolean protocol configuration. */\nexport type FeatureFlag = {\n __typename?: 'FeatureFlag';\n /** Feature flag name. */\n key: Scalars['String']['output'];\n /** Feature flag value. */\n value: Scalars['Boolean']['output'];\n};\n\n/** Access to the gas inputs, after they have been smashed into one coin. The gas coin can only be used by reference, except for with `TransferObjectsTransaction` that can accept it by value. */\nexport type GasCoin = {\n __typename?: 'GasCoin';\n /** Placeholder field (gas coin has no additional data) */\n _?: Maybe<Scalars['Boolean']['output']>;\n};\n\n/**\n * Summary of charges from transactions.\n *\n * Storage is charged in three parts -- `storage_cost`, `-storage_rebate`, and `non_refundable_storage_fee` -- independently of `computation_cost`.\n *\n * The overall cost of a transaction, deducted from its gas coins, is its `computation_cost + storage_cost - storage_rebate`. `non_refundable_storage_fee` is collected from objects being mutated or deleted and accumulated by the system in storage funds, the remaining storage costs of previous object versions are what become the `storage_rebate`. The ratio between `non_refundable_storage_fee` and `storage_rebate` is set by the protocol.\n */\nexport type GasCostSummary = {\n __typename?: 'GasCostSummary';\n /** The sum cost of computation/execution */\n computationCost?: Maybe<Scalars['UInt53']['output']>;\n /** Amount that is retained by the system in the storage fund from the cost of the previous versions of objects being mutated or deleted. */\n nonRefundableStorageFee?: Maybe<Scalars['UInt53']['output']>;\n /** Cost for storage at the time the transaction is executed, calculated as the size of the objects being mutated in bytes multiplied by a storage cost per byte (part of the protocol). */\n storageCost?: Maybe<Scalars['UInt53']['output']>;\n /** Amount the user gets back from the storage cost of the previous versions of objects being mutated or deleted. */\n storageRebate?: Maybe<Scalars['UInt53']['output']>;\n};\n\n/** Effects related to gas (costs incurred and the identity of the smashed gas object returned). */\nexport type GasEffects = {\n __typename?: 'GasEffects';\n /** The gas object used to pay for this transaction. If multiple gas coins were provided, this represents the combined coin after smashing. */\n gasObject?: Maybe<Object>;\n /** Breakdown of the gas costs for this transaction. */\n gasSummary?: Maybe<GasCostSummary>;\n};\n\nexport type GasInput = {\n __typename?: 'GasInput';\n /** The maximum SUI that can be expended by executing this transaction */\n gasBudget?: Maybe<Scalars['BigInt']['output']>;\n /** Objects used to pay for a transaction's execution and storage */\n gasPayment?: Maybe<ObjectConnection>;\n /** An unsigned integer specifying the number of native tokens per gas unit this transaction will pay (in MIST). */\n gasPrice?: Maybe<Scalars['BigInt']['output']>;\n /** Address of the owner of the gas object(s) used. */\n gasSponsor?: Maybe<Address>;\n};\n\n\nexport type GasInputGasPaymentArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n/** System transaction that initializes the network and writes the initial set of objects on-chain. */\nexport type GenesisTransaction = {\n __typename?: 'GenesisTransaction';\n /** Objects to be created during genesis. */\n objects?: Maybe<ObjectConnection>;\n};\n\n\n/** System transaction that initializes the network and writes the initial set of objects on-chain. */\nexport type GenesisTransactionObjectsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n/**\n * Interface implemented by GraphQL types representing entities that are identified by an address.\n *\n * An address uniquely represents either the public key of an account, or an object's ID, but never both. It is not possible to determine which type an address represents up-front. If an object is wrapped, its contents will not be accessible via its address, but it will still be possible to access other objects it owns.\n */\nexport type IAddressable = {\n address: Scalars['SuiAddress']['output'];\n /**\n * Fetch the address as it was at a different root version, or checkpoint.\n *\n * If no additional bound is provided, the address is fetched at the latest checkpoint known to the RPC.\n */\n addressAt?: Maybe<Address>;\n /**\n * Fetch the total balance for coins with marker type `coinType` (e.g. `0x2::sui::SUI`), owned by this address.\n *\n * If the address does not own any coins of that type, a balance of zero is returned.\n */\n balance?: Maybe<Balance>;\n /** Total balance across coins owned by this address, grouped by coin type. */\n balances?: Maybe<BalanceConnection>;\n /** The domain explicitly configured as the default Name Service name for this address. */\n defaultNameRecord?: Maybe<NameRecord>;\n /**\n * Fetch the total balances keyed by coin types (e.g. `0x2::sui::SUI`) owned by this address.\n *\n * Returns `null` when no checkpoint is set in scope (e.g. execution scope). If the address does not own any coins of a given type, a balance of zero is returned for that type.\n */\n multiGetBalances?: Maybe<Array<Balance>>;\n /** Objects owned by this address, optionally filtered by type. */\n objects?: Maybe<MoveObjectConnection>;\n};\n\n\n/**\n * Interface implemented by GraphQL types representing entities that are identified by an address.\n *\n * An address uniquely represents either the public key of an account, or an object's ID, but never both. It is not possible to determine which type an address represents up-front. If an object is wrapped, its contents will not be accessible via its address, but it will still be possible to access other objects it owns.\n */\nexport type IAddressableAddressAtArgs = {\n checkpoint?: InputMaybe<Scalars['UInt53']['input']>;\n rootVersion?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\n/**\n * Interface implemented by GraphQL types representing entities that are identified by an address.\n *\n * An address uniquely represents either the public key of an account, or an object's ID, but never both. It is not possible to determine which type an address represents up-front. If an object is wrapped, its contents will not be accessible via its address, but it will still be possible to access other objects it owns.\n */\nexport type IAddressableBalanceArgs = {\n coinType: Scalars['String']['input'];\n};\n\n\n/**\n * Interface implemented by GraphQL types representing entities that are identified by an address.\n *\n * An address uniquely represents either the public key of an account, or an object's ID, but never both. It is not possible to determine which type an address represents up-front. If an object is wrapped, its contents will not be accessible via its address, but it will still be possible to access other objects it owns.\n */\nexport type IAddressableBalancesArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/**\n * Interface implemented by GraphQL types representing entities that are identified by an address.\n *\n * An address uniquely represents either the public key of an account, or an object's ID, but never both. It is not possible to determine which type an address represents up-front. If an object is wrapped, its contents will not be accessible via its address, but it will still be possible to access other objects it owns.\n */\nexport type IAddressableMultiGetBalancesArgs = {\n keys: Array<Scalars['String']['input']>;\n};\n\n\n/**\n * Interface implemented by GraphQL types representing entities that are identified by an address.\n *\n * An address uniquely represents either the public key of an account, or an object's ID, but never both. It is not possible to determine which type an address represents up-front. If an object is wrapped, its contents will not be accessible via its address, but it will still be possible to access other objects it owns.\n */\nexport type IAddressableObjectsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<ObjectFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n/**\n * Interface implemented by all GraphQL types that represent a Move datatype definition (either a struct or an enum definition).\n *\n * This interface is used to provide a way to access fields that are shared by both structs and enums, e.g., the module that the datatype belongs to, the name of the datatype, type parameters etc.\n */\nexport type IMoveDatatype = {\n /** Abilities on this datatype definition. */\n abilities?: Maybe<Array<MoveAbility>>;\n /** The datatype's fully-qualified name, including package address, module name, and datatype name. */\n fullyQualifiedName: Scalars['String']['output'];\n /** The module that this datatype is defined in */\n module: MoveModule;\n /** The datatype's unqualified name */\n name: Scalars['String']['output'];\n /**\n * Constraints on the datatype's formal type parameters\n *\n * Move bytecode does not name type parameters, so when they are referenced (e.g. in field types), they are identified by their index in this list.\n */\n typeParameters?: Maybe<Array<MoveDatatypeTypeParameter>>;\n};\n\n/** Interface implemented by types that represent a Move object on-chain (A Move value whose type has `key`). */\nexport type IMoveObject = {\n /** The structured representation of the object's contents. */\n contents?: Maybe<MoveValue>;\n /**\n * Access a dynamic field on an object using its type and BCS-encoded name.\n *\n * Returns `null` if a dynamic field with that name could not be found attached to this object.\n */\n dynamicField?: Maybe<DynamicField>;\n /**\n * Dynamic fields and dynamic object fields owned by this object.\n *\n * Dynamic fields on wrapped objects can be accessed using `Address.dynamicFields`.\n */\n dynamicFields?: Maybe<DynamicFieldConnection>;\n /**\n * Access a dynamic object field on an object using its type and BCS-encoded name.\n *\n * Returns `null` if a dynamic object field with that name could not be found attached to this object.\n */\n dynamicObjectField?: Maybe<DynamicField>;\n /**\n * Whether this object can be transfered using the `TransferObjects` Programmable Transaction Command or `sui::transfer::public_transfer`.\n *\n * Both these operations require the object to have both the `key` and `store` abilities.\n */\n hasPublicTransfer?: Maybe<Scalars['Boolean']['output']>;\n /** The Base64-encoded BCS serialize of this object, as a `MoveObject`. */\n moveObjectBcs?: Maybe<Scalars['Base64']['output']>;\n /**\n * Access dynamic fields on an object using their types and BCS-encoded names.\n *\n * Returns a list of dynamic fields that is guaranteed to be the same length as `keys`. If a dynamic field in `keys` could not be found in the store, its corresponding entry in the result will be `null`.\n */\n multiGetDynamicFields: Array<Maybe<DynamicField>>;\n /**\n * Access dynamic object fields on an object using their types and BCS-encoded names.\n *\n * Returns a list of dynamic object fields that is guaranteed to be the same length as `keys`. If a dynamic object field in `keys` could not be found in the store, its corresponding entry in the result will be `null`.\n */\n multiGetDynamicObjectFields: Array<Maybe<DynamicField>>;\n};\n\n\n/** Interface implemented by types that represent a Move object on-chain (A Move value whose type has `key`). */\nexport type IMoveObjectDynamicFieldArgs = {\n name: DynamicFieldName;\n};\n\n\n/** Interface implemented by types that represent a Move object on-chain (A Move value whose type has `key`). */\nexport type IMoveObjectDynamicFieldsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** Interface implemented by types that represent a Move object on-chain (A Move value whose type has `key`). */\nexport type IMoveObjectDynamicObjectFieldArgs = {\n name: DynamicFieldName;\n};\n\n\n/** Interface implemented by types that represent a Move object on-chain (A Move value whose type has `key`). */\nexport type IMoveObjectMultiGetDynamicFieldsArgs = {\n keys: Array<DynamicFieldName>;\n};\n\n\n/** Interface implemented by types that represent a Move object on-chain (A Move value whose type has `key`). */\nexport type IMoveObjectMultiGetDynamicObjectFieldsArgs = {\n keys: Array<DynamicFieldName>;\n};\n\n/** Interface implemented by versioned on-chain values that are addressable by an ID (also referred to as its address). This includes Move objects and packages. */\nexport type IObject = {\n /** 32-byte hash that identifies the object's contents, encoded in Base58. */\n digest?: Maybe<Scalars['String']['output']>;\n /** Fetch the object with the same ID, at a different version, root version bound, or checkpoint. */\n objectAt?: Maybe<Object>;\n /** The Base64-encoded BCS serialization of this object, as an `Object`. */\n objectBcs?: Maybe<Scalars['Base64']['output']>;\n /** Paginate all versions of this object after this one. */\n objectVersionsAfter?: Maybe<ObjectConnection>;\n /** Paginate all versions of this object before this one. */\n objectVersionsBefore?: Maybe<ObjectConnection>;\n /** The object's owner kind. */\n owner?: Maybe<Owner>;\n /** The transaction that created this version of the object */\n previousTransaction?: Maybe<Transaction>;\n /** The transactions that sent objects to this object. */\n receivedTransactions?: Maybe<TransactionConnection>;\n /** The SUI returned to the sponsor or sender of the transaction that modifies or deletes this object. */\n storageRebate?: Maybe<Scalars['BigInt']['output']>;\n /** The version of this object that this content comes from. */\n version?: Maybe<Scalars['UInt53']['output']>;\n};\n\n\n/** Interface implemented by versioned on-chain values that are addressable by an ID (also referred to as its address). This includes Move objects and packages. */\nexport type IObjectObjectAtArgs = {\n checkpoint?: InputMaybe<Scalars['UInt53']['input']>;\n rootVersion?: InputMaybe<Scalars['UInt53']['input']>;\n version?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\n/** Interface implemented by versioned on-chain values that are addressable by an ID (also referred to as its address). This includes Move objects and packages. */\nexport type IObjectObjectVersionsAfterArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<VersionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** Interface implemented by versioned on-chain values that are addressable by an ID (also referred to as its address). This includes Move objects and packages. */\nexport type IObjectObjectVersionsBeforeArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<VersionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** Interface implemented by versioned on-chain values that are addressable by an ID (also referred to as its address). This includes Move objects and packages. */\nexport type IObjectReceivedTransactionsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<TransactionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n/** Object is accessible to all addresses, and is immutable. */\nexport type Immutable = {\n __typename?: 'Immutable';\n _?: Maybe<Scalars['Boolean']['output']>;\n};\n\nexport type Input = {\n __typename?: 'Input';\n /** The index of the input. */\n ix?: Maybe<Scalars['Int']['output']>;\n};\n\n/** An enum that specifies the intent scope for signature verification. */\nexport enum IntentScope {\n /** Indicates that the bytes are to be parsed as a personal message. */\n PersonalMessage = 'PERSONAL_MESSAGE',\n /** Indicates that the bytes are to be parsed as transaction data bytes. */\n TransactionData = 'TRANSACTION_DATA'\n}\n\n/** Information used by a package to link to a specific version of its dependency. */\nexport type Linkage = {\n __typename?: 'Linkage';\n /** The ID on-chain of the first version of the dependency. */\n originalId?: Maybe<Scalars['SuiAddress']['output']>;\n /** The ID on-chain of the version of the dependency that this package depends on. */\n upgradedId?: Maybe<Scalars['SuiAddress']['output']>;\n /** The version of the dependency that this package depends on. */\n version?: Maybe<Scalars['UInt53']['output']>;\n};\n\n/** Create a vector (can be empty). */\nexport type MakeMoveVecCommand = {\n __typename?: 'MakeMoveVecCommand';\n /** The values to pack into the vector, all of the same type. */\n elements?: Maybe<Array<TransactionArgument>>;\n /** If the elements are not objects, or the vector is empty, a type must be supplied. */\n type?: Maybe<MoveType>;\n};\n\n/** Merges `coins` into the first `coin` (produces no results). */\nexport type MergeCoinsCommand = {\n __typename?: 'MergeCoinsCommand';\n /** The coin to merge into. */\n coin?: Maybe<TransactionArgument>;\n /** The coins to be merged. */\n coins: Array<TransactionArgument>;\n};\n\n/** Abilities are keywords in Sui Move that define how types behave at the compiler level. */\nexport enum MoveAbility {\n /** Enables values to be copied. */\n Copy = 'COPY',\n /** Enables values to be popped/dropped. */\n Drop = 'DROP',\n /** Enables values to be held directly in global storage. */\n Key = 'KEY',\n /** Enables values to be held inside a struct in global storage. */\n Store = 'STORE'\n}\n\nexport type MoveCallCommand = {\n __typename?: 'MoveCallCommand';\n /** The actual function parameters passed in for this move call. */\n arguments: Array<TransactionArgument>;\n /** The function being called. */\n function: MoveFunction;\n};\n\n/** Description of a datatype, defined in a Move module. */\nexport type MoveDatatype = IMoveDatatype & {\n __typename?: 'MoveDatatype';\n /** Abilities on this datatype definition. */\n abilities?: Maybe<Array<MoveAbility>>;\n /** Attempts to convert the `MoveDatatype` to a `MoveEnum`. */\n asMoveEnum?: Maybe<MoveEnum>;\n /** Attempts to convert the `MoveDatatype` to a `MoveStruct`. */\n asMoveStruct?: Maybe<MoveStruct>;\n /** The datatype's fully-qualified name, including package address, module name, and datatype name. */\n fullyQualifiedName: Scalars['String']['output'];\n /** The module that this datatype is defined in. */\n module: MoveModule;\n /** The datatype's unqualified name. */\n name: Scalars['String']['output'];\n /**\n * Constraints on the datatype's formal type parameters.\n *\n * Move bytecode does not name type parameters, so when they are referenced (e.g. in field types), they are identified by their index in this list.\n */\n typeParameters?: Maybe<Array<MoveDatatypeTypeParameter>>;\n};\n\nexport type MoveDatatypeConnection = {\n __typename?: 'MoveDatatypeConnection';\n /** A list of edges. */\n edges: Array<MoveDatatypeEdge>;\n /** A list of nodes. */\n nodes: Array<MoveDatatype>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type MoveDatatypeEdge = {\n __typename?: 'MoveDatatypeEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: MoveDatatype;\n};\n\n/** Declaration of a type parameter on a Move struct. */\nexport type MoveDatatypeTypeParameter = {\n __typename?: 'MoveDatatypeTypeParameter';\n /** Ability constraints on this type parameter. */\n constraints: Array<MoveAbility>;\n /**\n * Whether this type parameter is marked `phantom` or not.\n *\n * Phantom type parameters are not referenced in the struct's fields.\n */\n isPhantom: Scalars['Boolean']['output'];\n};\n\n/** Description of an enum type, defined in a Move module. */\nexport type MoveEnum = IMoveDatatype & {\n __typename?: 'MoveEnum';\n /** Abilities on this enum definition. */\n abilities?: Maybe<Array<MoveAbility>>;\n /** The enum's fully-qualified name, including package address, module name, and datatype name. */\n fullyQualifiedName: Scalars['String']['output'];\n /** The module that this enum is defined in. */\n module: MoveModule;\n /** The enum's unqualified name. */\n name: Scalars['String']['output'];\n /**\n * Constraints on the enum's formal type parameters.\n *\n * Move bytecode does not name type parameters, so when they are referenced (e.g. in field types), they are identified by their index in this list.\n */\n typeParameters?: Maybe<Array<MoveDatatypeTypeParameter>>;\n /**\n * The names and fields of the enum's variants\n *\n * Field types reference type parameters by their index in the defining enum's `typeParameters` list.\n */\n variants?: Maybe<Array<MoveEnumVariant>>;\n};\n\nexport type MoveEnumConnection = {\n __typename?: 'MoveEnumConnection';\n /** A list of edges. */\n edges: Array<MoveEnumEdge>;\n /** A list of nodes. */\n nodes: Array<MoveEnum>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type MoveEnumEdge = {\n __typename?: 'MoveEnumEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: MoveEnum;\n};\n\nexport type MoveEnumVariant = {\n __typename?: 'MoveEnumVariant';\n /**\n * The names and types of the variant's fields.\n *\n * Field types reference type parameters by their index in the defining struct's `typeParameters` list.\n */\n fields?: Maybe<Array<MoveField>>;\n /** The variant's name. */\n name?: Maybe<Scalars['String']['output']>;\n};\n\nexport type MoveField = {\n __typename?: 'MoveField';\n /** The field's name. */\n name?: Maybe<Scalars['String']['output']>;\n /**\n * The field's type.\n *\n * This type can reference type parameters introduced by the defining struct (see `typeParameters`).\n */\n type?: Maybe<OpenMoveType>;\n};\n\n/** A function defined in a Move module. */\nexport type MoveFunction = {\n __typename?: 'MoveFunction';\n /** The function's fully-qualified name, including package address, module name, and function name. */\n fullyQualifiedName: Scalars['String']['output'];\n /** Whether the function is marked `entry` or not. */\n isEntry?: Maybe<Scalars['Boolean']['output']>;\n /** The module that this function is defined in. */\n module: MoveModule;\n /** The function's unqualified name. */\n name: Scalars['String']['output'];\n /** The function's parameter types. These types can reference type parameters introduced by this function (see `typeParameters`). */\n parameters?: Maybe<Array<OpenMoveType>>;\n /** The function's return types. There can be multiple because functions in Move can return multiple values. These types can reference type parameters introduced by this function (see `typeParameters`). */\n return?: Maybe<Array<OpenMoveType>>;\n /**\n * Constraints on the function's formal type parameters.\n *\n * Move bytecode does not name type parameters, so when they are referenced (e.g. in parameter and return types), they are identified by their index in this list.\n */\n typeParameters?: Maybe<Array<MoveFunctionTypeParameter>>;\n /** The function's visibility: `public`, `public(friend)`, or `private`. */\n visibility?: Maybe<MoveVisibility>;\n};\n\nexport type MoveFunctionConnection = {\n __typename?: 'MoveFunctionConnection';\n /** A list of edges. */\n edges: Array<MoveFunctionEdge>;\n /** A list of nodes. */\n nodes: Array<MoveFunction>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type MoveFunctionEdge = {\n __typename?: 'MoveFunctionEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: MoveFunction;\n};\n\n/** Declaration of a type parameter on a Move function. */\nexport type MoveFunctionTypeParameter = {\n __typename?: 'MoveFunctionTypeParameter';\n /** Ability constraints on this type parameter. */\n constraints: Array<MoveAbility>;\n};\n\n/**\n * Modules are a unit of code organization in Move.\n *\n * Modules belong to packages, and contain type and function definitions.\n */\nexport type MoveModule = {\n __typename?: 'MoveModule';\n /** Base64 encoded bytes of the serialized CompiledModule. */\n bytes?: Maybe<Scalars['Base64']['output']>;\n /** The datatype (struct or enum) named `name` in this module. */\n datatype?: Maybe<MoveDatatype>;\n /** Paginate through this module's datatype definitions. */\n datatypes?: Maybe<MoveDatatypeConnection>;\n /** Textual representation of the module's bytecode. */\n disassembly?: Maybe<Scalars['String']['output']>;\n /** The enum named `name` in this module. */\n enum?: Maybe<MoveEnum>;\n /** Paginate through this module's enum definitions. */\n enums?: Maybe<MoveEnumConnection>;\n /** Bytecode format version. */\n fileFormatVersion?: Maybe<Scalars['Int']['output']>;\n /** Modules that this module considers friends. These modules can call `public(package)` functions in this module. */\n friends?: Maybe<MoveModuleConnection>;\n /** The module's fully-qualified name, including its package address. */\n fullyQualifiedName: Scalars['String']['output'];\n /** The function named `name` in this module. */\n function?: Maybe<MoveFunction>;\n /** Paginate through this module's function definitions. */\n functions?: Maybe<MoveFunctionConnection>;\n /** The module's unqualified name. */\n name: Scalars['String']['output'];\n /** The package that this module was defined in. */\n package?: Maybe<MovePackage>;\n /** The struct named `name` in this module. */\n struct?: Maybe<MoveStruct>;\n /** Paginate through this module's struct definitions. */\n structs?: Maybe<MoveStructConnection>;\n};\n\n\n/**\n * Modules are a unit of code organization in Move.\n *\n * Modules belong to packages, and contain type and function definitions.\n */\nexport type MoveModuleDatatypeArgs = {\n name: Scalars['String']['input'];\n};\n\n\n/**\n * Modules are a unit of code organization in Move.\n *\n * Modules belong to packages, and contain type and function definitions.\n */\nexport type MoveModuleDatatypesArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/**\n * Modules are a unit of code organization in Move.\n *\n * Modules belong to packages, and contain type and function definitions.\n */\nexport type MoveModuleEnumArgs = {\n name: Scalars['String']['input'];\n};\n\n\n/**\n * Modules are a unit of code organization in Move.\n *\n * Modules belong to packages, and contain type and function definitions.\n */\nexport type MoveModuleEnumsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/**\n * Modules are a unit of code organization in Move.\n *\n * Modules belong to packages, and contain type and function definitions.\n */\nexport type MoveModuleFriendsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/**\n * Modules are a unit of code organization in Move.\n *\n * Modules belong to packages, and contain type and function definitions.\n */\nexport type MoveModuleFunctionArgs = {\n name: Scalars['String']['input'];\n};\n\n\n/**\n * Modules are a unit of code organization in Move.\n *\n * Modules belong to packages, and contain type and function definitions.\n */\nexport type MoveModuleFunctionsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/**\n * Modules are a unit of code organization in Move.\n *\n * Modules belong to packages, and contain type and function definitions.\n */\nexport type MoveModuleStructArgs = {\n name: Scalars['String']['input'];\n};\n\n\n/**\n * Modules are a unit of code organization in Move.\n *\n * Modules belong to packages, and contain type and function definitions.\n */\nexport type MoveModuleStructsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\nexport type MoveModuleConnection = {\n __typename?: 'MoveModuleConnection';\n /** A list of edges. */\n edges: Array<MoveModuleEdge>;\n /** A list of nodes. */\n nodes: Array<MoveModule>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type MoveModuleEdge = {\n __typename?: 'MoveModuleEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: MoveModule;\n};\n\n/** A MoveObject is a kind of Object that reprsents data stored on-chain. */\nexport type MoveObject = IAddressable & IMoveObject & IObject & Node & {\n __typename?: 'MoveObject';\n /** The MoveObject's ID. */\n address: Scalars['SuiAddress']['output'];\n /**\n * Fetch the address as it was at a different root version, or checkpoint.\n *\n * If no additional bound is provided, the address is fetched at the latest checkpoint known to the RPC.\n */\n addressAt?: Maybe<Address>;\n /** Attempts to convert the object into a CoinMetadata. */\n asCoinMetadata?: Maybe<CoinMetadata>;\n /** Attempts to convert the object into a DynamicField. */\n asDynamicField?: Maybe<DynamicField>;\n /**\n * Fetch the total balance for coins with marker type `coinType` (e.g. `0x2::sui::SUI`), owned by this address.\n *\n * If the address does not own any coins of that type, a balance of zero is returned.\n */\n balance?: Maybe<Balance>;\n /** Total balance across coins owned by this address, grouped by coin type. */\n balances?: Maybe<BalanceConnection>;\n /** The structured representation of the object's contents. */\n contents?: Maybe<MoveValue>;\n /** The domain explicitly configured as the default Name Service name for this address. */\n defaultNameRecord?: Maybe<NameRecord>;\n /** 32-byte hash that identifies the object's contents, encoded in Base58. */\n digest?: Maybe<Scalars['String']['output']>;\n /**\n * Access a dynamic field on an object using its type and BCS-encoded name.\n *\n * Returns `null` if a dynamic field with that name could not be found attached to this object.\n */\n dynamicField?: Maybe<DynamicField>;\n /**\n * Dynamic fields owned by this object.\n *\n * Dynamic fields on wrapped objects can be accessed using `Address.dynamicFields`.\n */\n dynamicFields?: Maybe<DynamicFieldConnection>;\n /**\n * Access a dynamic object field on an object using its type and BCS-encoded name.\n *\n * Returns `null` if a dynamic object field with that name could not be found attached to this object.\n */\n dynamicObjectField?: Maybe<DynamicField>;\n /**\n * Whether this object can be transfered using the `TransferObjects` Programmable Transaction Command or `sui::transfer::public_transfer`.\n *\n * Both these operations require the object to have both the `key` and `store` abilities.\n */\n hasPublicTransfer?: Maybe<Scalars['Boolean']['output']>;\n /** The Move object's globally unique identifier, which can be passed to `Query.node` to refetch it. */\n id: Scalars['ID']['output'];\n /** The Base64-encoded BCS serialize of this object, as a `MoveObject`. */\n moveObjectBcs?: Maybe<Scalars['Base64']['output']>;\n /**\n * Fetch the total balances keyed by coin types (e.g. `0x2::sui::SUI`) owned by this address.\n *\n * If the address does not own any coins of a given type, a balance of zero is returned for that type.\n */\n multiGetBalances?: Maybe<Array<Balance>>;\n /**\n * Access dynamic fields on an object using their types and BCS-encoded names.\n *\n * Returns a list of dynamic fields that is guaranteed to be the same length as `keys`. If a dynamic field in `keys` could not be found in the store, its corresponding entry in the result will be `null`.\n */\n multiGetDynamicFields: Array<Maybe<DynamicField>>;\n /**\n * Access dynamic object fields on an object using their types and BCS-encoded names.\n *\n * Returns a list of dynamic object fields that is guaranteed to be the same length as `keys`. If a dynamic object field in `keys` could not be found in the store, its corresponding entry in the result will be `null`.\n */\n multiGetDynamicObjectFields: Array<Maybe<DynamicField>>;\n /**\n * Fetch the object with the same ID, at a different version, root version bound, or checkpoint.\n *\n * If no additional bound is provided, the latest version of this object is fetched at the latest checkpoint.\n */\n objectAt?: Maybe<Object>;\n /** The Base64-encoded BCS serialization of this object, as an `Object`. */\n objectBcs?: Maybe<Scalars['Base64']['output']>;\n /** Paginate all versions of this object after this one. */\n objectVersionsAfter?: Maybe<ObjectConnection>;\n /** Paginate all versions of this object before this one. */\n objectVersionsBefore?: Maybe<ObjectConnection>;\n /** Objects owned by this object, optionally filtered by type. */\n objects?: Maybe<MoveObjectConnection>;\n /** The object's owner kind. */\n owner?: Maybe<Owner>;\n /** The transaction that created this version of the object. */\n previousTransaction?: Maybe<Transaction>;\n /** The transactions that sent objects to this object. */\n receivedTransactions?: Maybe<TransactionConnection>;\n /** The SUI returned to the sponsor or sender of the transaction that modifies or deletes this object. */\n storageRebate?: Maybe<Scalars['BigInt']['output']>;\n /** The version of this object that this content comes from. */\n version?: Maybe<Scalars['UInt53']['output']>;\n};\n\n\n/** A MoveObject is a kind of Object that reprsents data stored on-chain. */\nexport type MoveObjectAddressAtArgs = {\n checkpoint?: InputMaybe<Scalars['UInt53']['input']>;\n rootVersion?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\n/** A MoveObject is a kind of Object that reprsents data stored on-chain. */\nexport type MoveObjectBalanceArgs = {\n coinType: Scalars['String']['input'];\n};\n\n\n/** A MoveObject is a kind of Object that reprsents data stored on-chain. */\nexport type MoveObjectBalancesArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** A MoveObject is a kind of Object that reprsents data stored on-chain. */\nexport type MoveObjectDynamicFieldArgs = {\n name: DynamicFieldName;\n};\n\n\n/** A MoveObject is a kind of Object that reprsents data stored on-chain. */\nexport type MoveObjectDynamicFieldsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** A MoveObject is a kind of Object that reprsents data stored on-chain. */\nexport type MoveObjectDynamicObjectFieldArgs = {\n name: DynamicFieldName;\n};\n\n\n/** A MoveObject is a kind of Object that reprsents data stored on-chain. */\nexport type MoveObjectMultiGetBalancesArgs = {\n keys: Array<Scalars['String']['input']>;\n};\n\n\n/** A MoveObject is a kind of Object that reprsents data stored on-chain. */\nexport type MoveObjectMultiGetDynamicFieldsArgs = {\n keys: Array<DynamicFieldName>;\n};\n\n\n/** A MoveObject is a kind of Object that reprsents data stored on-chain. */\nexport type MoveObjectMultiGetDynamicObjectFieldsArgs = {\n keys: Array<DynamicFieldName>;\n};\n\n\n/** A MoveObject is a kind of Object that reprsents data stored on-chain. */\nexport type MoveObjectObjectAtArgs = {\n checkpoint?: InputMaybe<Scalars['UInt53']['input']>;\n rootVersion?: InputMaybe<Scalars['UInt53']['input']>;\n version?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\n/** A MoveObject is a kind of Object that reprsents data stored on-chain. */\nexport type MoveObjectObjectVersionsAfterArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<VersionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** A MoveObject is a kind of Object that reprsents data stored on-chain. */\nexport type MoveObjectObjectVersionsBeforeArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<VersionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** A MoveObject is a kind of Object that reprsents data stored on-chain. */\nexport type MoveObjectObjectsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<ObjectFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** A MoveObject is a kind of Object that reprsents data stored on-chain. */\nexport type MoveObjectReceivedTransactionsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<TransactionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\nexport type MoveObjectConnection = {\n __typename?: 'MoveObjectConnection';\n /** A list of edges. */\n edges: Array<MoveObjectEdge>;\n /** A list of nodes. */\n nodes: Array<MoveObject>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type MoveObjectEdge = {\n __typename?: 'MoveObjectEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: MoveObject;\n};\n\n/** A MovePackage is a kind of Object that represents code that has been published on-chain. It exposes information about its modules, type definitions, functions, and dependencies. */\nexport type MovePackage = IAddressable & IObject & Node & {\n __typename?: 'MovePackage';\n /** The MovePackage's ID. */\n address: Scalars['SuiAddress']['output'];\n /**\n * Fetch the address as it was at a different root version, or checkpoint.\n *\n * If no additional bound is provided, the address is fetched at the latest checkpoint known to the RPC.\n */\n addressAt?: Maybe<Address>;\n /**\n * Fetch the total balance for coins with marker type `coinType` (e.g. `0x2::sui::SUI`), owned by this address.\n *\n * If the address does not own any coins of that type, a balance of zero is returned.\n */\n balance?: Maybe<Balance>;\n /** Total balance across coins owned by this address, grouped by coin type. */\n balances?: Maybe<BalanceConnection>;\n /** The domain explicitly configured as the default Name Service name for this address. */\n defaultNameRecord?: Maybe<NameRecord>;\n /** 32-byte hash that identifies the package's contents, encoded in Base58. */\n digest?: Maybe<Scalars['String']['output']>;\n /** The package's globally unique identifier, which can be passed to `Query.node` to refetch it. */\n id: Scalars['ID']['output'];\n /** The transitive dependencies of this package. */\n linkage?: Maybe<Array<Linkage>>;\n /** The module named `name` in this package. */\n module?: Maybe<MoveModule>;\n /** BCS representation of the package's modules. Modules appear as a sequence of pairs (module name, followed by module bytes), in alphabetic order by module name. */\n moduleBcs?: Maybe<Scalars['Base64']['output']>;\n /** Paginate through this package's modules. */\n modules?: Maybe<MoveModuleConnection>;\n /**\n * Fetch the total balances keyed by coin types (e.g. `0x2::sui::SUI`) owned by this address.\n *\n * If the address does not own any coins of a given type, a balance of zero is returned for that type.\n */\n multiGetBalances?: Maybe<Array<Balance>>;\n /**\n * Fetch the package as an object with the same ID, at a different version, root version bound, or checkpoint.\n *\n * If no additional bound is provided, the latest version of this object is fetched at the latest checkpoint.\n */\n objectAt?: Maybe<Object>;\n /** The Base64-encoded BCS serialization of this package, as an `Object`. */\n objectBcs?: Maybe<Scalars['Base64']['output']>;\n /** Paginate all versions of this package treated as an object, after this one. */\n objectVersionsAfter?: Maybe<ObjectConnection>;\n /** Paginate all versions of this package treated as an object, before this one. */\n objectVersionsBefore?: Maybe<ObjectConnection>;\n /** Objects owned by this package, optionally filtered by type. */\n objects?: Maybe<MoveObjectConnection>;\n /** The object's owner kind. */\n owner?: Maybe<Owner>;\n /**\n * Fetch the package with the same original ID, at a different version, or checkpoint.\n *\n * If no additional bound is provided, the package is fetched at the latest checkpoint known to the RPC.\n */\n packageAt?: Maybe<MovePackage>;\n /** The Base64-encoded BCS serialization of this package, as a `MovePackage`. */\n packageBcs?: Maybe<Scalars['Base64']['output']>;\n /** Paginate all versions of this package after this one. */\n packageVersionsAfter?: Maybe<MovePackageConnection>;\n /** Paginate all versions of this package before this one. */\n packageVersionsBefore?: Maybe<MovePackageConnection>;\n /** The transaction that created this version of the object. */\n previousTransaction?: Maybe<Transaction>;\n /** The transactions that sent objects to this object. */\n receivedTransactions?: Maybe<TransactionConnection>;\n /** The SUI returned to the sponsor or sender of the transaction that modifies or deletes this object. */\n storageRebate?: Maybe<Scalars['BigInt']['output']>;\n /** A table identifying which versions of a package introduced each of its types. */\n typeOrigins?: Maybe<Array<TypeOrigin>>;\n /** The version of this package that this content comes from. */\n version?: Maybe<Scalars['UInt53']['output']>;\n};\n\n\n/** A MovePackage is a kind of Object that represents code that has been published on-chain. It exposes information about its modules, type definitions, functions, and dependencies. */\nexport type MovePackageAddressAtArgs = {\n checkpoint?: InputMaybe<Scalars['UInt53']['input']>;\n rootVersion?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\n/** A MovePackage is a kind of Object that represents code that has been published on-chain. It exposes information about its modules, type definitions, functions, and dependencies. */\nexport type MovePackageBalanceArgs = {\n coinType: Scalars['String']['input'];\n};\n\n\n/** A MovePackage is a kind of Object that represents code that has been published on-chain. It exposes information about its modules, type definitions, functions, and dependencies. */\nexport type MovePackageBalancesArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** A MovePackage is a kind of Object that represents code that has been published on-chain. It exposes information about its modules, type definitions, functions, and dependencies. */\nexport type MovePackageModuleArgs = {\n name: Scalars['String']['input'];\n};\n\n\n/** A MovePackage is a kind of Object that represents code that has been published on-chain. It exposes information about its modules, type definitions, functions, and dependencies. */\nexport type MovePackageModulesArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** A MovePackage is a kind of Object that represents code that has been published on-chain. It exposes information about its modules, type definitions, functions, and dependencies. */\nexport type MovePackageMultiGetBalancesArgs = {\n keys: Array<Scalars['String']['input']>;\n};\n\n\n/** A MovePackage is a kind of Object that represents code that has been published on-chain. It exposes information about its modules, type definitions, functions, and dependencies. */\nexport type MovePackageObjectAtArgs = {\n checkpoint?: InputMaybe<Scalars['UInt53']['input']>;\n rootVersion?: InputMaybe<Scalars['UInt53']['input']>;\n version?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\n/** A MovePackage is a kind of Object that represents code that has been published on-chain. It exposes information about its modules, type definitions, functions, and dependencies. */\nexport type MovePackageObjectVersionsAfterArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<VersionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** A MovePackage is a kind of Object that represents code that has been published on-chain. It exposes information about its modules, type definitions, functions, and dependencies. */\nexport type MovePackageObjectVersionsBeforeArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<VersionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** A MovePackage is a kind of Object that represents code that has been published on-chain. It exposes information about its modules, type definitions, functions, and dependencies. */\nexport type MovePackageObjectsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<ObjectFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** A MovePackage is a kind of Object that represents code that has been published on-chain. It exposes information about its modules, type definitions, functions, and dependencies. */\nexport type MovePackagePackageAtArgs = {\n checkpoint?: InputMaybe<Scalars['UInt53']['input']>;\n version?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\n/** A MovePackage is a kind of Object that represents code that has been published on-chain. It exposes information about its modules, type definitions, functions, and dependencies. */\nexport type MovePackagePackageVersionsAfterArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<VersionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** A MovePackage is a kind of Object that represents code that has been published on-chain. It exposes information about its modules, type definitions, functions, and dependencies. */\nexport type MovePackagePackageVersionsBeforeArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<VersionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** A MovePackage is a kind of Object that represents code that has been published on-chain. It exposes information about its modules, type definitions, functions, and dependencies. */\nexport type MovePackageReceivedTransactionsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<TransactionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\nexport type MovePackageConnection = {\n __typename?: 'MovePackageConnection';\n /** A list of edges. */\n edges: Array<MovePackageEdge>;\n /** A list of nodes. */\n nodes: Array<MovePackage>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type MovePackageEdge = {\n __typename?: 'MovePackageEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: MovePackage;\n};\n\n/** Description of a struct type, defined in a Move module. */\nexport type MoveStruct = IMoveDatatype & {\n __typename?: 'MoveStruct';\n /** Abilities on this struct definition. */\n abilities?: Maybe<Array<MoveAbility>>;\n /**\n * The names and types of the struct's fields.\n *\n * Field types reference type parameters by their index in the defining struct's `typeParameters` list.\n */\n fields?: Maybe<Array<MoveField>>;\n /** The struct's fully-qualified name, including package address, module name, and datatype name. */\n fullyQualifiedName: Scalars['String']['output'];\n /** The module that this struct is defined in. */\n module: MoveModule;\n /** The struct's unqualified name. */\n name: Scalars['String']['output'];\n /**\n * Constraints on the struct's formal type parameters.\n *\n * Move bytecode does not name type parameters, so when they are referenced (e.g. in field types), they are identified by their index in this list.\n */\n typeParameters?: Maybe<Array<MoveDatatypeTypeParameter>>;\n};\n\nexport type MoveStructConnection = {\n __typename?: 'MoveStructConnection';\n /** A list of edges. */\n edges: Array<MoveStructEdge>;\n /** A list of nodes. */\n nodes: Array<MoveStruct>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type MoveStructEdge = {\n __typename?: 'MoveStructEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: MoveStruct;\n};\n\n/** Represents instances of concrete types (no type parameters, no references). */\nexport type MoveType = {\n __typename?: 'MoveType';\n /** The abilities this concrete type has. Returns no abilities if the type is invalid. */\n abilities?: Maybe<Array<MoveAbility>>;\n /**\n * Structured representation of the \"shape\" of values that match this type. May return no\n * layout if the type is invalid.\n */\n layout?: Maybe<Scalars['MoveTypeLayout']['output']>;\n /** Flat representation of the type signature, as a displayable string. */\n repr: Scalars['String']['output'];\n /** Structured representation of the type signature. */\n signature: Scalars['MoveTypeSignature']['output'];\n};\n\nexport type MoveValue = {\n __typename?: 'MoveValue';\n /**\n * Attempts to treat this value as an `Address`.\n *\n * If the value is of type `address` or `0x2::object::ID`, it is interpreted as an address pointer, and it is scoped to the current checkpoint.\n *\n * If the value is of type `0x2::object::UID`, it is interpreted as a wrapped object whose version is bounded by the root version of the current value. Such values do not support nested owned object queries, but `Address.addressAt` can be used to re-scope it to a checkpoint (defaults to the current checkpoint), instead of a root version, allowing owned object queries.\n *\n * Values of other types cannot be interpreted as addresses, and `null` is returned.\n */\n asAddress?: Maybe<Address>;\n /**\n * Attempts to treat this value as a `vector<T>` and paginate over its elements.\n *\n * Values of other types cannot be interpreted as vectors, and `null` is returned.\n */\n asVector?: Maybe<MoveValueConnection>;\n /** The BCS representation of this value, Base64-encoded. */\n bcs?: Maybe<Scalars['Base64']['output']>;\n /**\n * A rendered JSON blob based on an on-chain template, substituted with data from this value.\n *\n * Returns `null` if the value's type does not have an associated `Display` template.\n */\n display?: Maybe<Display>;\n /**\n * Extract a nested value at the given path.\n *\n * `path` is a Display v2 'chain' expression, allowing access to nested, named and positional fields, vector indices, VecMap keys, and dynamic (object) field accesses.\n */\n extract?: Maybe<MoveValue>;\n /**\n * Render a single Display v2 format string against this value.\n *\n * Returns `null` if the value does not have a valid type, or if any of the expressions in the format string fail to evaluate (e.g. field does not exist).\n */\n format?: Maybe<Scalars['JSON']['output']>;\n /**\n * Representation of a Move value in JSON, where:\n *\n * - Addresses, IDs, and UIDs are represented in canonical form, as JSON strings.\n * - Bools are represented by JSON boolean literals.\n * - u8, u16, and u32 are represented as JSON numbers.\n * - u64, u128, and u256 are represented as JSON strings.\n * - Balances, Strings, and Urls are represented as JSON strings.\n * - Vectors of bytes are represented as Base64 blobs, and other vectors are represented by JSON arrays.\n * - Structs are represented by JSON objects.\n * - Enums are represented by JSON objects, with a field named `@variant` containing the variant name.\n * - Empty optional values are represented by `null`.\n */\n json?: Maybe<Scalars['JSON']['output']>;\n /** The value's type. */\n type?: Maybe<MoveType>;\n};\n\n\nexport type MoveValueAsVectorArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\nexport type MoveValueExtractArgs = {\n path: Scalars['String']['input'];\n};\n\n\nexport type MoveValueFormatArgs = {\n format: Scalars['String']['input'];\n};\n\nexport type MoveValueConnection = {\n __typename?: 'MoveValueConnection';\n /** A list of edges. */\n edges: Array<MoveValueEdge>;\n /** A list of nodes. */\n nodes: Array<MoveValue>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type MoveValueEdge = {\n __typename?: 'MoveValueEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: MoveValue;\n};\n\n/**\n * The visibility modifier describes which modules can access this module member.\n *\n * By default, a module member can be called only within the same module.\n */\nexport enum MoveVisibility {\n /** A friend member can be accessed in the module it is defined in and any other module in its package that is explicitly specified in its friend list. */\n Friend = 'FRIEND',\n /** A private member can be accessed in the module it is defined in. */\n Private = 'PRIVATE',\n /** A public member can be accessed by any module. */\n Public = 'PUBLIC'\n}\n\n/** The multisig committee definition. */\nexport type MultisigCommittee = {\n __typename?: 'MultisigCommittee';\n /** The committee members (public key + weight). */\n members?: Maybe<Array<MultisigMember>>;\n /** The threshold number of weight needed for a valid multisig. */\n threshold?: Maybe<Scalars['Int']['output']>;\n};\n\n/** A single member of a multisig committee. */\nexport type MultisigMember = {\n __typename?: 'MultisigMember';\n /** The member's public key. */\n publicKey?: Maybe<MultisigMemberPublicKey>;\n /** The member's weight in the committee. */\n weight?: Maybe<Scalars['Int']['output']>;\n};\n\n/** A multisig member's public key, varying by scheme. */\nexport type MultisigMemberPublicKey = Ed25519PublicKey | PasskeyPublicKey | Secp256K1PublicKey | Secp256R1PublicKey | ZkLoginPublicIdentifier;\n\n/** An aggregated multisig signature. */\nexport type MultisigSignature = {\n __typename?: 'MultisigSignature';\n /** A bitmap indicating which members of the committee signed. */\n bitmap?: Maybe<Scalars['Int']['output']>;\n /** The multisig committee (public keys + weights + threshold). */\n committee?: Maybe<MultisigCommittee>;\n /**\n * The individual member signatures, one per signer who participated.\n * Compressed signatures within a multisig do not include the signer's public key,\n * so `publicKey` will be `null` for simple signature schemes (Ed25519, Secp256k1, Secp256r1).\n */\n signatures?: Maybe<Array<SignatureScheme>>;\n};\n\n/** A transaction that wanted to mutate a consensus-managed object but couldn't because it became not-consensus-managed before the transaction executed (for example, it was deleted, turned into an owned object, or wrapped). */\nexport type MutateConsensusStreamEnded = {\n __typename?: 'MutateConsensusStreamEnded';\n /** The ID of the consensus-managed object. */\n address?: Maybe<Scalars['SuiAddress']['output']>;\n /** The sequence number associated with the consensus stream ending. */\n sequenceNumber?: Maybe<Scalars['UInt53']['output']>;\n};\n\n/** Mutations are used to write to the Sui network. */\nexport type Mutation = {\n __typename?: 'Mutation';\n /**\n * Execute a transaction, committing its effects on chain.\n *\n * - `transactionDataBcs` contains the BCS-encoded transaction data (Base64-encoded).\n * - `signatures` are a list of `flag || signature || pubkey` bytes, Base64-encoded.\n *\n * Waits until the transaction has reached finality on chain to return its transaction digest, or returns the error that prevented finality if that was not possible. A transaction is final when its effects are guaranteed on chain (it cannot be revoked).\n *\n * There may be a delay between transaction finality and when GraphQL requests (including the request that issued the transaction) reflect its effects. As a result, queries that depend on indexing the state of the chain (e.g. contents of output objects, address-level balance information at the time of the transaction), must wait for indexing to catch up by polling for the transaction digest using `Query.transaction`.\n */\n executeTransaction: ExecutionResult;\n};\n\n\n/** Mutations are used to write to the Sui network. */\nexport type MutationExecuteTransactionArgs = {\n signatures: Array<Scalars['Base64']['input']>;\n transactionDataBcs: Scalars['Base64']['input'];\n};\n\n/** A Name Service NameRecord representing a domain name registration. */\nexport type NameRecord = {\n __typename?: 'NameRecord';\n /** On-chain representation of the underlying Name Service `NameRecord` Move value. */\n contents: MoveValue;\n /** The domain name this record is for. */\n domain: Scalars['String']['output'];\n /**\n * The Name Service Name Record of the parent domain, if this is a subdomain.\n *\n * Returns `null` if this is not a subdomain.\n */\n parent?: Maybe<NameRecord>;\n /**\n * The address this domain points to.\n *\n * `rootVersion` and `atCheckpoint` control how the target `Address` is scoped. If neither is provided, the `Address` is scoped to the latest checkpoint known to the RPC.\n */\n target?: Maybe<Address>;\n};\n\n\n/** A Name Service NameRecord representing a domain name registration. */\nexport type NameRecordTargetArgs = {\n atCheckpoint?: InputMaybe<Scalars['UInt53']['input']>;\n rootVersion?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n/** An interface implemented by types that can be uniquely identified by a globally unique `ID`, following the GraphQL Global Object Identification specification. */\nexport type Node = {\n /** The node's globally unique identifier, which can be passed to `Query.node` to refetch it. */\n id: Scalars['ID']['output'];\n};\n\n/**\n * An Object on Sui is either a typed value (a Move Object) or a Package (modules containing functions and types).\n *\n * Every object on Sui is identified by a unique address, and has a version number that increases with every modification. Objects also hold metadata detailing their current owner (who can sign for access to the object and whether that access can modify and/or delete the object), and the digest of the last transaction that modified the object.\n */\nexport type Object = IAddressable & IObject & Node & {\n __typename?: 'Object';\n /** The Object's ID. */\n address: Scalars['SuiAddress']['output'];\n /**\n * Fetch the address as it was at a different root version, or checkpoint.\n *\n * If no additional bound is provided, the address is fetched at the latest checkpoint known to the RPC.\n */\n addressAt?: Maybe<Address>;\n /** Attempts to convert the object into a MoveObject. */\n asMoveObject?: Maybe<MoveObject>;\n /** Attempts to convert the object into a MovePackage. */\n asMovePackage?: Maybe<MovePackage>;\n /**\n * Fetch the total balance for coins with marker type `coinType` (e.g. `0x2::sui::SUI`), owned by this address.\n *\n * If the address does not own any coins of that type, a balance of zero is returned.\n */\n balance?: Maybe<Balance>;\n /** Total balance across coins owned by this address, grouped by coin type. */\n balances?: Maybe<BalanceConnection>;\n /** The domain explicitly configured as the default Name Service name for this address. */\n defaultNameRecord?: Maybe<NameRecord>;\n /** 32-byte hash that identifies the object's contents, encoded in Base58. */\n digest?: Maybe<Scalars['String']['output']>;\n /**\n * Access a dynamic field on an object using its type and BCS-encoded name.\n *\n * Returns `null` if a dynamic field with that name could not be found attached to this object.\n */\n dynamicField?: Maybe<DynamicField>;\n /** Dynamic fields owned by this object. */\n dynamicFields?: Maybe<DynamicFieldConnection>;\n /**\n * Access a dynamic object field on an object using its type and BCS-encoded name.\n *\n * Returns `null` if a dynamic object field with that name could not be found attached to this object.\n */\n dynamicObjectField?: Maybe<DynamicField>;\n /** The object's globally unique identifier, which can be passed to `Query.node` to refetch it. */\n id: Scalars['ID']['output'];\n /**\n * Fetch the total balances keyed by coin types (e.g. `0x2::sui::SUI`) owned by this address.\n *\n * Returns `None` when no checkpoint is set in scope (e.g. execution scope).\n * If the address does not own any coins of a given type, a balance of zero is returned for that type.\n */\n multiGetBalances?: Maybe<Array<Balance>>;\n /**\n * Access dynamic fields on an object using their types and BCS-encoded names.\n *\n * Returns a list of dynamic fields that is guaranteed to be the same length as `keys`. If a dynamic field in `keys` could not be found in the store, its corresponding entry in the result will be `null`.\n */\n multiGetDynamicFields: Array<Maybe<DynamicField>>;\n /**\n * Access dynamic object fields on an object using their types and BCS-encoded names.\n *\n * Returns a list of dynamic object fields that is guaranteed to be the same length as `keys`. If a dynamic object field in `keys` could not be found in the store, its corresponding entry in the result will be `null`.\n */\n multiGetDynamicObjectFields: Array<Maybe<DynamicField>>;\n /**\n * Fetch the object with the same ID, at a different version, root version bound, or checkpoint.\n *\n * If no additional bound is provided, the object is fetched at the latest checkpoint known to the RPC.\n */\n objectAt?: Maybe<Object>;\n /** The Base64-encoded BCS serialization of this object, as an `Object`. */\n objectBcs?: Maybe<Scalars['Base64']['output']>;\n /** Paginate all versions of this object after this one. */\n objectVersionsAfter?: Maybe<ObjectConnection>;\n /** Paginate all versions of this object before this one. */\n objectVersionsBefore?: Maybe<ObjectConnection>;\n /** Objects owned by this object, optionally filtered by type. */\n objects?: Maybe<MoveObjectConnection>;\n /** The object's owner kind. */\n owner?: Maybe<Owner>;\n /** The transaction that created this version of the object. */\n previousTransaction?: Maybe<Transaction>;\n /** The transactions that sent objects to this object */\n receivedTransactions?: Maybe<TransactionConnection>;\n /** The SUI returned to the sponsor or sender of the transaction that modifies or deletes this object. */\n storageRebate?: Maybe<Scalars['BigInt']['output']>;\n /** The version of this object that this content comes from. */\n version?: Maybe<Scalars['UInt53']['output']>;\n};\n\n\n/**\n * An Object on Sui is either a typed value (a Move Object) or a Package (modules containing functions and types).\n *\n * Every object on Sui is identified by a unique address, and has a version number that increases with every modification. Objects also hold metadata detailing their current owner (who can sign for access to the object and whether that access can modify and/or delete the object), and the digest of the last transaction that modified the object.\n */\nexport type ObjectAddressAtArgs = {\n checkpoint?: InputMaybe<Scalars['UInt53']['input']>;\n rootVersion?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\n/**\n * An Object on Sui is either a typed value (a Move Object) or a Package (modules containing functions and types).\n *\n * Every object on Sui is identified by a unique address, and has a version number that increases with every modification. Objects also hold metadata detailing their current owner (who can sign for access to the object and whether that access can modify and/or delete the object), and the digest of the last transaction that modified the object.\n */\nexport type ObjectBalanceArgs = {\n coinType: Scalars['String']['input'];\n};\n\n\n/**\n * An Object on Sui is either a typed value (a Move Object) or a Package (modules containing functions and types).\n *\n * Every object on Sui is identified by a unique address, and has a version number that increases with every modification. Objects also hold metadata detailing their current owner (who can sign for access to the object and whether that access can modify and/or delete the object), and the digest of the last transaction that modified the object.\n */\nexport type ObjectBalancesArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/**\n * An Object on Sui is either a typed value (a Move Object) or a Package (modules containing functions and types).\n *\n * Every object on Sui is identified by a unique address, and has a version number that increases with every modification. Objects also hold metadata detailing their current owner (who can sign for access to the object and whether that access can modify and/or delete the object), and the digest of the last transaction that modified the object.\n */\nexport type ObjectDynamicFieldArgs = {\n name: DynamicFieldName;\n};\n\n\n/**\n * An Object on Sui is either a typed value (a Move Object) or a Package (modules containing functions and types).\n *\n * Every object on Sui is identified by a unique address, and has a version number that increases with every modification. Objects also hold metadata detailing their current owner (who can sign for access to the object and whether that access can modify and/or delete the object), and the digest of the last transaction that modified the object.\n */\nexport type ObjectDynamicFieldsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/**\n * An Object on Sui is either a typed value (a Move Object) or a Package (modules containing functions and types).\n *\n * Every object on Sui is identified by a unique address, and has a version number that increases with every modification. Objects also hold metadata detailing their current owner (who can sign for access to the object and whether that access can modify and/or delete the object), and the digest of the last transaction that modified the object.\n */\nexport type ObjectDynamicObjectFieldArgs = {\n name: DynamicFieldName;\n};\n\n\n/**\n * An Object on Sui is either a typed value (a Move Object) or a Package (modules containing functions and types).\n *\n * Every object on Sui is identified by a unique address, and has a version number that increases with every modification. Objects also hold metadata detailing their current owner (who can sign for access to the object and whether that access can modify and/or delete the object), and the digest of the last transaction that modified the object.\n */\nexport type ObjectMultiGetBalancesArgs = {\n keys: Array<Scalars['String']['input']>;\n};\n\n\n/**\n * An Object on Sui is either a typed value (a Move Object) or a Package (modules containing functions and types).\n *\n * Every object on Sui is identified by a unique address, and has a version number that increases with every modification. Objects also hold metadata detailing their current owner (who can sign for access to the object and whether that access can modify and/or delete the object), and the digest of the last transaction that modified the object.\n */\nexport type ObjectMultiGetDynamicFieldsArgs = {\n keys: Array<DynamicFieldName>;\n};\n\n\n/**\n * An Object on Sui is either a typed value (a Move Object) or a Package (modules containing functions and types).\n *\n * Every object on Sui is identified by a unique address, and has a version number that increases with every modification. Objects also hold metadata detailing their current owner (who can sign for access to the object and whether that access can modify and/or delete the object), and the digest of the last transaction that modified the object.\n */\nexport type ObjectMultiGetDynamicObjectFieldsArgs = {\n keys: Array<DynamicFieldName>;\n};\n\n\n/**\n * An Object on Sui is either a typed value (a Move Object) or a Package (modules containing functions and types).\n *\n * Every object on Sui is identified by a unique address, and has a version number that increases with every modification. Objects also hold metadata detailing their current owner (who can sign for access to the object and whether that access can modify and/or delete the object), and the digest of the last transaction that modified the object.\n */\nexport type ObjectObjectAtArgs = {\n checkpoint?: InputMaybe<Scalars['UInt53']['input']>;\n rootVersion?: InputMaybe<Scalars['UInt53']['input']>;\n version?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\n/**\n * An Object on Sui is either a typed value (a Move Object) or a Package (modules containing functions and types).\n *\n * Every object on Sui is identified by a unique address, and has a version number that increases with every modification. Objects also hold metadata detailing their current owner (who can sign for access to the object and whether that access can modify and/or delete the object), and the digest of the last transaction that modified the object.\n */\nexport type ObjectObjectVersionsAfterArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<VersionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/**\n * An Object on Sui is either a typed value (a Move Object) or a Package (modules containing functions and types).\n *\n * Every object on Sui is identified by a unique address, and has a version number that increases with every modification. Objects also hold metadata detailing their current owner (who can sign for access to the object and whether that access can modify and/or delete the object), and the digest of the last transaction that modified the object.\n */\nexport type ObjectObjectVersionsBeforeArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<VersionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/**\n * An Object on Sui is either a typed value (a Move Object) or a Package (modules containing functions and types).\n *\n * Every object on Sui is identified by a unique address, and has a version number that increases with every modification. Objects also hold metadata detailing their current owner (who can sign for access to the object and whether that access can modify and/or delete the object), and the digest of the last transaction that modified the object.\n */\nexport type ObjectObjectsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<ObjectFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/**\n * An Object on Sui is either a typed value (a Move Object) or a Package (modules containing functions and types).\n *\n * Every object on Sui is identified by a unique address, and has a version number that increases with every modification. Objects also hold metadata detailing their current owner (who can sign for access to the object and whether that access can modify and/or delete the object), and the digest of the last transaction that modified the object.\n */\nexport type ObjectReceivedTransactionsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<TransactionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\nexport type ObjectChange = {\n __typename?: 'ObjectChange';\n /** The address of the object that has changed. */\n address: Scalars['SuiAddress']['output'];\n /** Whether the ID was created in this transaction. */\n idCreated?: Maybe<Scalars['Boolean']['output']>;\n /** Whether the ID was deleted in this transaction. */\n idDeleted?: Maybe<Scalars['Boolean']['output']>;\n /** The contents of the object immediately before the transaction. */\n inputState?: Maybe<Object>;\n /** The contents of the object immediately after the transaction. */\n outputState?: Maybe<Object>;\n};\n\nexport type ObjectChangeConnection = {\n __typename?: 'ObjectChangeConnection';\n /** A list of edges. */\n edges: Array<ObjectChangeEdge>;\n /** A list of nodes. */\n nodes: Array<ObjectChange>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type ObjectChangeEdge = {\n __typename?: 'ObjectChangeEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: ObjectChange;\n};\n\nexport type ObjectConnection = {\n __typename?: 'ObjectConnection';\n /** A list of edges. */\n edges: Array<ObjectEdge>;\n /** A list of nodes. */\n nodes: Array<Object>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type ObjectEdge = {\n __typename?: 'ObjectEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: Object;\n};\n\n/**\n * A filter over the live object set, the filter can be one of:\n *\n * - A filter on type (all live objects whose type matches that filter).\n * - Fetching all objects owned by an address or object, optionally filtered by type.\n * - Fetching all shared or immutable objects, filtered by type.\n */\nexport type ObjectFilter = {\n /**\n * Specifies the address of the owning address or object.\n *\n * This field is required if `ownerKind` is \"ADDRESS\" or \"OBJECT\". If provided without `ownerKind`, `ownerKind` defaults to \"ADDRESS\".\n */\n owner?: InputMaybe<Scalars['SuiAddress']['input']>;\n /**\n * Filter on whether the object is address-owned, object-owned, shared, or immutable.\n *\n * - If this field is set to \"ADDRESS\" or \"OBJECT\", then an owner filter must also be provided.\n * - If this field is set to \"SHARED\" or \"IMMUTABLE\", then a type filter must also be provided.\n */\n ownerKind?: InputMaybe<OwnerKind>;\n /**\n * Filter on the object's type.\n *\n * The filter can be one of:\n *\n * - A package address: `0x2`,\n * - A module: `0x2::coin`,\n * - A fully-qualified name: `0x2::coin::Coin`,\n * - A type instantiation: `0x2::coin::Coin<0x2::sui::SUI>`.\n */\n type?: InputMaybe<Scalars['String']['input']>;\n};\n\n/**\n * Identifies a specific version of an object.\n *\n * The `address` field must be specified, as well as at most one of `version`, `rootVersion`, or `atCheckpoint`. If none are provided, the object is fetched at the current checkpoint.\n *\n * Specifying a `version` or a `rootVersion` disables nested queries for paginating owned objects or dynamic fields (these queries are only supported at checkpoint boundaries).\n *\n * See `Query.object` for more details.\n */\nexport type ObjectKey = {\n /** The object's ID. */\n address: Scalars['SuiAddress']['input'];\n /** If specified, tries to fetch the latest version as of this checkpoint. Fails if the checkpoint is later than the RPC's latest checkpoint. */\n atCheckpoint?: InputMaybe<Scalars['UInt53']['input']>;\n /**\n * If specified, tries to fetch the latest version of the object at or before this version. Nested dynamic field accesses will also be subject to this bound.\n *\n * This can be used to fetch a child or ancestor object bounded by its root object's version. For any wrapped or child (object-owned) object, its root object can be defined recursively as:\n *\n * - The root object of the object it is wrapped in, if it is wrapped.\n * - The root object of its owner, if it is owned by another object.\n * - The object itself, if it is not object-owned or wrapped.\n */\n rootVersion?: InputMaybe<Scalars['UInt53']['input']>;\n /** If specified, tries to fetch the object at this exact version. */\n version?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n/** Object is exclusively owned by a single object, and is mutable. Note that the owning object may be inaccessible because it is wrapped. */\nexport type ObjectOwner = {\n __typename?: 'ObjectOwner';\n /** The owner's address. */\n address?: Maybe<Address>;\n};\n\n/**\n * Represents types that could contain references or free type parameters. Such types can appear\n * as function parameters, in fields of structs, or as actual type parameter.\n */\nexport type OpenMoveType = {\n __typename?: 'OpenMoveType';\n /** Flat representation of the type signature, as a displayable string. */\n repr: Scalars['String']['output'];\n /** Structured representation of the type signature. */\n signature: Scalars['OpenMoveTypeSignature']['output'];\n};\n\n/** Placeholder for unimplemented command types */\nexport type OtherCommand = {\n __typename?: 'OtherCommand';\n /** Placeholder field for unimplemented commands */\n _?: Maybe<Scalars['Boolean']['output']>;\n};\n\n/** A Move object, either immutable, or owned mutable. */\nexport type OwnedOrImmutable = {\n __typename?: 'OwnedOrImmutable';\n object?: Maybe<Object>;\n};\n\n/** The object's owner kind. */\nexport type Owner = AddressOwner | ConsensusAddressOwner | Immutable | ObjectOwner | Shared;\n\n/** Filter on who owns an object. */\nexport enum OwnerKind {\n /** Object is owned by an address. */\n Address = 'ADDRESS',\n /** Object is frozen. */\n Immutable = 'IMMUTABLE',\n /** Object is a child of another object (e.g. a dynamic field or dynamic object field). */\n Object = 'OBJECT',\n /** Object is shared among multiple owners. */\n Shared = 'SHARED'\n}\n\n/** Filter for paginating packages published within a range of checkpoints. */\nexport type PackageCheckpointFilter = {\n /** Filter to packages that were published strictly after this checkpoint, defaults to fetching from the earliest checkpoint known to this RPC (this could be the genesis checkpoint, or some later checkpoint if data has been pruned). */\n afterCheckpoint?: InputMaybe<Scalars['UInt53']['input']>;\n /** Filter to packages published strictly before this checkpoint, defaults to fetching up to the latest checkpoint (inclusive). */\n beforeCheckpoint?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n/**\n * Identifies a specific version of a package.\n *\n * The `address` field must be specified, as well as at most one of `version`, or `atCheckpoint`. If neither is provided, the package is fetched at the checkpoint being viewed.\n *\n * See `Query.package` for more details.\n */\nexport type PackageKey = {\n /** The object's ID. */\n address: Scalars['SuiAddress']['input'];\n /** If specified, tries to fetch the latest version as of this checkpoint. */\n atCheckpoint?: InputMaybe<Scalars['UInt53']['input']>;\n /** If specified, tries to fetch the package at this exact version. */\n version?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n/** Information about pagination in a connection */\nexport type PageInfo = {\n __typename?: 'PageInfo';\n /** When paginating forwards, the cursor to continue. */\n endCursor?: Maybe<Scalars['String']['output']>;\n /** When paginating forwards, are there more items? */\n hasNextPage: Scalars['Boolean']['output'];\n /** When paginating backwards, are there more items? */\n hasPreviousPage: Scalars['Boolean']['output'];\n /** When paginating backwards, the cursor to continue. */\n startCursor?: Maybe<Scalars['String']['output']>;\n};\n\n/** A Passkey public key. */\nexport type PasskeyPublicKey = {\n __typename?: 'PasskeyPublicKey';\n /** The raw public key bytes. */\n bytes?: Maybe<Scalars['Base64']['output']>;\n};\n\nexport type PasskeySignature = {\n __typename?: 'PasskeySignature';\n /** The authenticator data returned by the passkey device. */\n authenticatorData?: Maybe<Scalars['Base64']['output']>;\n /** The client data JSON string passed to the authenticator. */\n clientDataJson?: Maybe<Scalars['String']['output']>;\n /** The inner user signature (secp256r1). */\n signature?: Maybe<SignatureScheme>;\n};\n\nexport type PerEpochConfig = {\n __typename?: 'PerEpochConfig';\n /** The per-epoch configuration object as of when the transaction was executed. */\n object?: Maybe<Object>;\n};\n\n/** ProgrammableSystemTransaction is identical to ProgrammableTransaction, but GraphQL does not allow multiple variants with the same type. */\nexport type ProgrammableSystemTransaction = {\n __typename?: 'ProgrammableSystemTransaction';\n /** The transaction commands, executed sequentially. */\n commands?: Maybe<CommandConnection>;\n /** Input objects or primitive values. */\n inputs?: Maybe<TransactionInputConnection>;\n};\n\n\n/** ProgrammableSystemTransaction is identical to ProgrammableTransaction, but GraphQL does not allow multiple variants with the same type. */\nexport type ProgrammableSystemTransactionCommandsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** ProgrammableSystemTransaction is identical to ProgrammableTransaction, but GraphQL does not allow multiple variants with the same type. */\nexport type ProgrammableSystemTransactionInputsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\nexport type ProgrammableTransaction = {\n __typename?: 'ProgrammableTransaction';\n /** The transaction commands, executed sequentially. */\n commands?: Maybe<CommandConnection>;\n /** Input objects or primitive values. */\n inputs?: Maybe<TransactionInputConnection>;\n};\n\n\nexport type ProgrammableTransactionCommandsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\nexport type ProgrammableTransactionInputsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n/** A protocol configuration that can hold an arbitrary value (or no value at all). */\nexport type ProtocolConfig = {\n __typename?: 'ProtocolConfig';\n /** Configuration name. */\n key: Scalars['String']['output'];\n /** Configuration value. */\n value?: Maybe<Scalars['String']['output']>;\n};\n\n/**\n * Constants that control how the chain operates.\n *\n * These can only change during protocol upgrades which happen on epoch boundaries. Configuration is split into feature flags (which are just booleans), and configs which can take any value (including no value at all), and will be represented by a string.\n */\nexport type ProtocolConfigs = {\n __typename?: 'ProtocolConfigs';\n /** Query for the value of the configuration with name `key`. */\n config?: Maybe<ProtocolConfig>;\n /** List all available configurations and their values. */\n configs: Array<ProtocolConfig>;\n /** Query for the state of the feature flag with name `key`. */\n featureFlag?: Maybe<FeatureFlag>;\n /** List all available feature flags and their values. */\n featureFlags: Array<FeatureFlag>;\n protocolVersion: Scalars['UInt53']['output'];\n};\n\n\n/**\n * Constants that control how the chain operates.\n *\n * These can only change during protocol upgrades which happen on epoch boundaries. Configuration is split into feature flags (which are just booleans), and configs which can take any value (including no value at all), and will be represented by a string.\n */\nexport type ProtocolConfigsConfigArgs = {\n key: Scalars['String']['input'];\n};\n\n\n/**\n * Constants that control how the chain operates.\n *\n * These can only change during protocol upgrades which happen on epoch boundaries. Configuration is split into feature flags (which are just booleans), and configs which can take any value (including no value at all), and will be represented by a string.\n */\nexport type ProtocolConfigsFeatureFlagArgs = {\n key: Scalars['String']['input'];\n};\n\n/** Publishes a Move Package. */\nexport type PublishCommand = {\n __typename?: 'PublishCommand';\n /** IDs of the transitive dependencies of the package to be published. */\n dependencies?: Maybe<Array<Scalars['SuiAddress']['output']>>;\n /** Bytecode for the modules to be published, BCS serialized and Base64 encoded. */\n modules?: Maybe<Array<Scalars['Base64']['output']>>;\n};\n\n/** BCS encoded primitive value (not an object or Move struct). */\nexport type Pure = {\n __typename?: 'Pure';\n /** BCS serialized and Base64 encoded primitive value. */\n bytes?: Maybe<Scalars['Base64']['output']>;\n};\n\nexport type Query = {\n __typename?: 'Query';\n /**\n * Look-up an account by its SuiAddress.\n *\n * If `rootVersion` is specified, nested dynamic field accesses will be fetched at or before this version. This can be used to fetch a child or descendant object bounded by its root object's version, when its immediate parent is wrapped, or a value in a dynamic object field. For any wrapped or child (object-owned) object, its root object can be defined recursively as:\n *\n * - The root object of the object it is wrapped in, if it is wrapped.\n * - The root object of its owner, if it is owned by another object.\n * - The object itself, if it is not object-owned or wrapped.\n *\n * Specifying a `rootVersion` disables nested queries for paginating owned objects or dynamic fields (these queries are only supported at checkpoint boundaries).\n *\n * If `atCheckpoint` is specified, the address will be fetched at the latest version as of this checkpoint. This will fail if the provided checkpoint is after the RPC's latest checkpoint.\n *\n * If none of the above are specified, the address is fetched at the checkpoint being viewed.\n *\n * If the address is fetched by name and the name does not resolve to an address (e.g. the name does not exist or has expired), `null` is returned.\n */\n address?: Maybe<Address>;\n /** The network's genesis checkpoint digest (uniquely identifies the network), Base58-encoded. */\n chainIdentifier: Scalars['String']['output'];\n /**\n * Fetch a checkpoint by its sequence number or digest, or the latest checkpoint if neither is provided.\n *\n * It is an error to specify both `sequenceNumber` and `digest`.\n *\n * Returns `null` if the checkpoint does not exist in the store, either because it never existed or because it was pruned.\n */\n checkpoint?: Maybe<Checkpoint>;\n /** Paginate checkpoints in the network, optionally bounded to checkpoints in the given epoch. */\n checkpoints?: Maybe<CheckpointConnection>;\n /**\n * Fetch the CoinMetadata for a given coin type.\n *\n * Returns `null` if no CoinMetadata object exists for the given coin type.\n */\n coinMetadata?: Maybe<CoinMetadata>;\n /**\n * Fetch an epoch by its ID, or fetch the latest epoch if no ID is provided.\n *\n * Returns `null` if the epoch does not exist yet, or was pruned.\n */\n epoch?: Maybe<Epoch>;\n /** Paginate epochs that are in the network. */\n epochs?: Maybe<EpochConnection>;\n /** Paginate events that are emitted in the network, optionally filtered by event filters. */\n events?: Maybe<EventConnection>;\n /**\n * Fetch addresses by their keys.\n *\n * Returns a list of addresses that is guaranteed to be the same length as `keys`. If an address in `keys` is fetched by name and the name does not resolve to an address, its corresponding entry in the result will be `null`.\n */\n multiGetAddresses: Array<Maybe<Address>>;\n /**\n * Fetch checkpoints by their sequence numbers.\n *\n * Returns a list of checkpoints that is guaranteed to be the same length as `keys`. If a checkpoint in `keys` could not be found in the store, its corresponding entry in the result will be `null`. This could be because the checkpoint does not exist yet, or because it was pruned.\n */\n multiGetCheckpoints: Array<Maybe<Checkpoint>>;\n /**\n * Fetch epochs by their IDs.\n *\n * Returns a list of epochs that is guaranteed to be the same length as `keys`. If an epoch in `keys` could not be found in the store, its corresponding entry in the result will be `null`. This could be because the epoch does not exist yet, or because it was pruned.\n */\n multiGetEpochs: Array<Maybe<Epoch>>;\n /**\n * Fetch objects by their keys.\n *\n * Returns a list of objects that is guaranteed to be the same length as `keys`. If an object in `keys` could not be found in the store, its corresponding entry in the result will be `null`. This could be because the object never existed, or because it was pruned.\n */\n multiGetObjects: Array<Maybe<Object>>;\n /**\n * Fetch packages by their keys.\n *\n * Returns a list of packages that is guaranteed to be the same length as `keys`. If a package in `keys` could not be found in the store, its corresponding entry in the result will be `null`. This could be because that address never pointed to a package, or because the package was pruned.\n */\n multiGetPackages: Array<Maybe<MovePackage>>;\n /**\n * Fetch transaction effects by their transactions' digests.\n *\n * Returns a list of transaction effects that is guaranteed to be the same length as `keys`. If a digest in `keys` could not be found in the store, its corresponding entry in the result will be `null`. This could be because the transaction effects never existed, or because it was pruned.\n */\n multiGetTransactionEffects: Array<Maybe<TransactionEffects>>;\n /**\n * Fetch transactions by their digests.\n *\n * Returns a list of transactions that is guaranteed to be the same length as `keys`. If a digest in `keys` could not be found in the store, its corresponding entry in the result will be `null`. This could be because the transaction never existed, or because it was pruned.\n */\n multiGetTransactions: Array<Maybe<Transaction>>;\n /**\n * Fetch types by their string representations.\n *\n * Types are canonicalized: In the input they can be at any package address at or after the package that first defines them, and in the output they will be relocated to the package that first defines them.\n *\n * Returns a list of types that is guaranteed to be the same length as `keys`. If a type in `keys` could not be found, its corresponding entry in the result will be `null`.\n */\n multiGetTypes: Array<Maybe<MoveType>>;\n /**\n * Look-up a Name Service NameRecord by its domain name.\n *\n * Returns `null` if the record does not exist or has expired.\n */\n nameRecord?: Maybe<NameRecord>;\n /** Fetch a `Node` by its globally unique `ID`. Returns `null` if the node cannot be found (e.g., the underlying data was pruned or never existed). */\n node?: Maybe<Node>;\n /**\n * Fetch an object by its address.\n *\n * If `version` is specified, the object will be fetched at that exact version.\n *\n * If `rootVersion` is specified, the object will be fetched at the latest version at or before this version. Nested dynamic field accesses will also be subject to this bound. This can be used to fetch a child or ancestor object bounded by its root object's version. For any wrapped or child (object-owned) object, its root object can be defined recursively as:\n *\n * - The root object of the object it is wrapped in, if it is wrapped.\n * - The root object of its owner, if it is owned by another object.\n * - The object itself, if it is not object-owned or wrapped.\n *\n * Specifying a `version` or a `rootVersion` disables nested queries for paginating owned objects or dynamic fields (these queries are only supported at checkpoint boundaries).\n *\n * If `atCheckpoint` is specified, the object will be fetched at the latest version as of this checkpoint. This will fail if the provided checkpoint is after the RPC's latest checkpoint.\n *\n * If none of the above are specified, the object is fetched at the checkpoint being viewed.\n *\n * It is an error to specify more than one of `version`, `rootVersion`, or `atCheckpoint`.\n *\n * Returns `null` if an object cannot be found that meets this criteria.\n */\n object?: Maybe<Object>;\n /** Paginate all versions of an object at `address`, optionally bounding the versions exclusively from below with `filter.afterVersion` or from above with `filter.beforeVersion`. */\n objectVersions?: Maybe<ObjectConnection>;\n /**\n * Paginate objects in the live object set, optionally filtered by owner and/or type. `filter` can be one of:\n *\n * - A filter on type (all live objects whose type matches that filter).\n * - Fetching all objects owned by an address or object, optionally filtered by type.\n * - Fetching all shared or immutable objects, filtered by type.\n */\n objects?: Maybe<ObjectConnection>;\n /**\n * Fetch a package by its address.\n *\n * If `version` is specified, the package loaded is the one that shares its original ID with the package at `address`, but whose version is `version`.\n *\n * If `atCheckpoint` is specified, the package loaded is the one with the largest version among all packages sharing an original ID with the package at `address` and was published at or before `atCheckpoint`.\n *\n * If neither are specified, the package is fetched at the checkpoint being viewed.\n *\n * It is an error to specify both `version` and `atCheckpoint`, and `null` will be returned if the package cannot be found as of the latest checkpoint, or the address points to an object that is not a package.\n *\n * Note that this interpretation of `version` and \"latest\" differs from the one used by `Query.object`, because non-system package upgrades generate objects with different IDs. To fetch a package using the versioning semantics of objects, use `Object.asMovePackage` nested under `Query.object`.\n */\n package?: Maybe<MovePackage>;\n /**\n * Paginate all versions of a package at `address`, optionally bounding the versions exclusively from below with `filter.afterVersion` or from above with `filter.beforeVersion`.\n *\n * Different versions of a package will have different object IDs, unless they are system packages, but will share the same original ID.\n */\n packageVersions?: Maybe<MovePackageConnection>;\n /** Paginate all packages published on-chain, optionally bounded to packages published strictly after `filter.afterCheckpoint` and/or strictly before `filter.beforeCheckpoint`. */\n packages?: Maybe<MovePackageConnection>;\n /** Fetch the protocol config by protocol version, or the latest protocol config used on chain if no version is provided. */\n protocolConfigs?: Maybe<ProtocolConfigs>;\n /** Configuration for this RPC service. */\n serviceConfig: ServiceConfig;\n /**\n * Simulate a transaction to preview its effects without executing it on chain.\n *\n * Accepts a JSON transaction matching the [Sui gRPC API schema](https://docs.sui.io/references/fullnode-protocol#sui-rpc-v2-Transaction).\n * The JSON format allows for partial transaction specification where certain fields can be automatically resolved by the server.\n *\n * Alternatively, for already serialized transactions, you can pass BCS-encoded data:\n * `{\"bcs\": {\"value\": \"<base64>\"}}`\n *\n * Unlike `executeTransaction`, this does not require signatures since the transaction is not committed to the blockchain. This allows for previewing transaction effects, estimating gas costs, and testing transaction logic without spending gas or requiring valid signatures.\n *\n * - `checksEnabled`: If true, enables transaction validation checks during simulation. Defaults to true.\n * - `doGasSelection`: If true, enables automatic gas coin selection and budget estimation. Defaults to false.\n */\n simulateTransaction: SimulationResult;\n /**\n * Fetch a transaction by its digest.\n *\n * Returns `null` if the transaction does not exist in the store, either because it never existed or because it was pruned.\n */\n transaction?: Maybe<Transaction>;\n /**\n * Fetch transaction effects by its transaction's digest.\n *\n * Returns `null` if the transaction effects do not exist in the store, either because that transaction was not executed, or it was pruned.\n */\n transactionEffects?: Maybe<TransactionEffects>;\n /** The transactions that exist in the network, optionally filtered by transaction filters. */\n transactions?: Maybe<TransactionConnection>;\n /**\n * Fetch a structured representation of a concrete type, including its layout information.\n *\n * Types are canonicalized: In the input they can be at any package address at or after the package that first defines them, and in the output they will be relocated to the package that first defines them.\n *\n * Fails if the type is malformed, returns `null` if a type mentioned does not exist.\n */\n type?: Maybe<MoveType>;\n /**\n * Verify a signature is from the given `author`.\n *\n * Supports all signature types: Ed25519, Secp256k1, Secp256r1, MultiSig, ZkLogin, and\n * Passkey.\n *\n * Returns successfully if the signature is valid. If the signature is invalid, returns an\n * error with the reason for the failure.\n *\n * - `message` is either a serialized personal message or `TransactionData`, Base64-encoded.\n * - `signature` is a serialized signature, also Base64-encoded.\n * - `intentScope` indicates whether `message` is to be parsed as a personal message or\n * `TransactionData`.\n * - `author` is the signer's address.\n */\n verifySignature?: Maybe<SignatureVerifyResult>;\n /**\n * Verify a zkLogin signature is from the given `author`.\n *\n * Returns successfully if the signature is valid. If the signature is invalid, returns an error with the reason for the failure.\n *\n * - `bytes` are either the bytes of a serialized personal message, or `TransactionData`, Base64-encoded.\n * - `signature` is a serialized zkLogin signature, also Base64-encoded.\n * - `intentScope` indicates whether `bytes` are to be parsed as a personal message or `TransactionData`.\n * - `author` is the signer's address.\n * @deprecated Use `verifySignature` instead, which supports all signature types.\n */\n verifyZkLoginSignature?: Maybe<ZkLoginVerifyResult>;\n};\n\n\nexport type QueryAddressArgs = {\n address?: InputMaybe<Scalars['SuiAddress']['input']>;\n atCheckpoint?: InputMaybe<Scalars['UInt53']['input']>;\n name?: InputMaybe<Scalars['String']['input']>;\n rootVersion?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\nexport type QueryCheckpointArgs = {\n digest?: InputMaybe<Scalars['String']['input']>;\n sequenceNumber?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\nexport type QueryCheckpointsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<CheckpointFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\nexport type QueryCoinMetadataArgs = {\n coinType: Scalars['String']['input'];\n};\n\n\nexport type QueryEpochArgs = {\n epochId?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\nexport type QueryEpochsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\nexport type QueryEventsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<EventFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\nexport type QueryMultiGetAddressesArgs = {\n keys: Array<AddressKey>;\n};\n\n\nexport type QueryMultiGetCheckpointsArgs = {\n keys: Array<Scalars['UInt53']['input']>;\n};\n\n\nexport type QueryMultiGetEpochsArgs = {\n keys: Array<Scalars['UInt53']['input']>;\n};\n\n\nexport type QueryMultiGetObjectsArgs = {\n keys: Array<ObjectKey>;\n};\n\n\nexport type QueryMultiGetPackagesArgs = {\n keys: Array<PackageKey>;\n};\n\n\nexport type QueryMultiGetTransactionEffectsArgs = {\n keys: Array<Scalars['String']['input']>;\n};\n\n\nexport type QueryMultiGetTransactionsArgs = {\n keys: Array<Scalars['String']['input']>;\n};\n\n\nexport type QueryMultiGetTypesArgs = {\n keys: Array<Scalars['String']['input']>;\n};\n\n\nexport type QueryNameRecordArgs = {\n name: Scalars['String']['input'];\n};\n\n\nexport type QueryNodeArgs = {\n id: Scalars['ID']['input'];\n};\n\n\nexport type QueryObjectArgs = {\n address: Scalars['SuiAddress']['input'];\n atCheckpoint?: InputMaybe<Scalars['UInt53']['input']>;\n rootVersion?: InputMaybe<Scalars['UInt53']['input']>;\n version?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\nexport type QueryObjectVersionsArgs = {\n address: Scalars['SuiAddress']['input'];\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<VersionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\nexport type QueryObjectsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter: ObjectFilter;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\nexport type QueryPackageArgs = {\n address: Scalars['SuiAddress']['input'];\n atCheckpoint?: InputMaybe<Scalars['UInt53']['input']>;\n version?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\nexport type QueryPackageVersionsArgs = {\n address: Scalars['SuiAddress']['input'];\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<VersionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\nexport type QueryPackagesArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<PackageCheckpointFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\nexport type QueryProtocolConfigsArgs = {\n version?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n\nexport type QuerySimulateTransactionArgs = {\n checksEnabled?: InputMaybe<Scalars['Boolean']['input']>;\n doGasSelection?: InputMaybe<Scalars['Boolean']['input']>;\n transaction: Scalars['JSON']['input'];\n};\n\n\nexport type QueryTransactionArgs = {\n digest: Scalars['String']['input'];\n};\n\n\nexport type QueryTransactionEffectsArgs = {\n digest: Scalars['String']['input'];\n};\n\n\nexport type QueryTransactionsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<TransactionFilter>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\nexport type QueryTypeArgs = {\n type: Scalars['String']['input'];\n};\n\n\nexport type QueryVerifySignatureArgs = {\n author: Scalars['SuiAddress']['input'];\n intentScope: IntentScope;\n message: Scalars['Base64']['input'];\n signature: Scalars['Base64']['input'];\n};\n\n\nexport type QueryVerifyZkLoginSignatureArgs = {\n author: Scalars['SuiAddress']['input'];\n bytes: Scalars['Base64']['input'];\n intentScope: ZkLoginIntentScope;\n signature: Scalars['Base64']['input'];\n};\n\n/** System transaction for creating the on-chain randomness state. */\nexport type RandomnessStateCreateTransaction = {\n __typename?: 'RandomnessStateCreateTransaction';\n /** A workaround to define an empty variant of a GraphQL union. */\n _?: Maybe<Scalars['Boolean']['output']>;\n};\n\n/** System transaction to update the source of on-chain randomness. */\nexport type RandomnessStateUpdateTransaction = {\n __typename?: 'RandomnessStateUpdateTransaction';\n /** Epoch of the randomness state update transaction. */\n epoch?: Maybe<Scalars['Int']['output']>;\n /** Updated random bytes, Base64 encoded. */\n randomBytes?: Maybe<Scalars['Base64']['output']>;\n /** The initial version of the randomness object that it was shared at. */\n randomnessObjInitialSharedVersion?: Maybe<Scalars['Int']['output']>;\n /** Randomness round of the update. */\n randomnessRound?: Maybe<Scalars['Int']['output']>;\n};\n\n/** A transaction that wanted to read a consensus-managed object but couldn't because it became not-consensus-managed before the transaction executed (for example, it was deleted, turned into an owned object, or wrapped). */\nexport type ReadConsensusStreamEnded = {\n __typename?: 'ReadConsensusStreamEnded';\n /** The ID of the consensus-managed object. */\n address?: Maybe<Scalars['SuiAddress']['output']>;\n /** The sequence number associated with the consensus stream ending. */\n sequenceNumber?: Maybe<Scalars['UInt53']['output']>;\n};\n\n/** A Move object that can be received in this transaction. */\nexport type Receiving = {\n __typename?: 'Receiving';\n object?: Maybe<Object>;\n};\n\n/** Whether the currency is regulated or not. */\nexport enum RegulatedState {\n /** A `DenyCap` or a `RegulatedCoinMetadata` exists for this currency. */\n Regulated = 'REGULATED',\n /** The currency was created without a deny list. */\n Unregulated = 'UNREGULATED'\n}\n\n/** A Secp256k1 public key. */\nexport type Secp256K1PublicKey = {\n __typename?: 'Secp256K1PublicKey';\n /** The raw public key bytes. */\n bytes?: Maybe<Scalars['Base64']['output']>;\n};\n\n/** A Secp256k1 signature. */\nexport type Secp256K1Signature = {\n __typename?: 'Secp256K1Signature';\n /** The public key bytes. */\n publicKey?: Maybe<Scalars['Base64']['output']>;\n /** The raw signature bytes. */\n signature?: Maybe<Scalars['Base64']['output']>;\n};\n\n/** A Secp256r1 public key. */\nexport type Secp256R1PublicKey = {\n __typename?: 'Secp256R1PublicKey';\n /** The raw public key bytes. */\n bytes?: Maybe<Scalars['Base64']['output']>;\n};\n\n/** A Secp256r1 signature. */\nexport type Secp256R1Signature = {\n __typename?: 'Secp256R1Signature';\n /** The public key bytes. */\n publicKey?: Maybe<Scalars['Base64']['output']>;\n /** The raw signature bytes. */\n signature?: Maybe<Scalars['Base64']['output']>;\n};\n\nexport type ServiceConfig = {\n __typename?: 'ServiceConfig';\n /** Range of checkpoints for which data is available for a query type, field and optional filter. If filter is not provided, the strictest retention range for the query and type is returned. */\n availableRange: AvailableRange;\n /**\n * Number of elements a paginated connection will return if a page size is not supplied.\n *\n * Accepts `type` and `field` arguments which identify the connection that is being queried. If the field in question is paginated, its default page size is returned. If it does not exist or is not paginated, `null` is returned.\n */\n defaultPageSize?: Maybe<Scalars['Int']['output']>;\n /** Maximum output size of a disassembled MoveModule, in bytes. */\n maxDisassembledModuleSize?: Maybe<Scalars['Int']['output']>;\n /** Maximum depth of nested field access supported in display outputs. */\n maxDisplayFieldDepth?: Maybe<Scalars['Int']['output']>;\n /** Maximum number of components in a Display v2 format string. */\n maxDisplayFormatNodes?: Maybe<Scalars['Int']['output']>;\n /** Maximum number of objects that can be loaded while evaluating a display. */\n maxDisplayObjectLoads?: Maybe<Scalars['Int']['output']>;\n /** Maximum output size of a display output. */\n maxDisplayOutputSize?: Maybe<Scalars['Int']['output']>;\n /** Maximum budget in bytes to spend when outputting a structured `MoveValue`. */\n maxMoveValueBound?: Maybe<Scalars['Int']['output']>;\n /** Maximum nesting allowed in datatype fields when calculating the layout of a single type. */\n maxMoveValueDepth?: Maybe<Scalars['Int']['output']>;\n /** Maximum number of elements that can be requested from a multi-get query. A request to fetch more keys will result in an error. */\n maxMultiGetSize?: Maybe<Scalars['Int']['output']>;\n /**\n * Maximum number of estimated output nodes in a GraphQL response.\n *\n * The estimate is an upperbound of how many nodes there would be in the output assuming every requested field is present, paginated requests return full page sizes, and multi-get queries find all requested keys. Below is a worked example query:\n *\n * ```graphql\n * | 0: query { # 514 = total\n * | 1: checkpoint { # 1\n * | 2: sequenceNumber # 1\n * | 3: }\n * | 4:\n * | 5: multiGetObjects([$a, $b, $c]) { # 1 (* 3)\n * | 6: address # 3\n * | 7: digest # 3\n * | 8: }\n * | 9:\n * | 10: # default page size is 20\n * | 11: transactions { # 1 (* 20)\n * | 12: pageInfo { # 1\n * | 13: hasNextPage # 1\n * | 14: endCursor # 1\n * | 15: }\n * | 16:\n * | 17: nodes # 1\n * | 18: { # 20\n * | 19: digest # 20\n * | 20: effects { # 20\n * | 21: objectChanges(first: 10) { # 20 (* 10)\n * | 22: nodes # 20\n * | 23: { # 200\n * | 24: address # 200\n * | 25: }\n * | 26: }\n * | 27: }\n * | 28: }\n * | 29: }\n * | 30: }\n * ```\n */\n maxOutputNodes?: Maybe<Scalars['Int']['output']>;\n /**\n * Maximum number of elements that can be requested from a paginated connection. A request to fetch more elements will result in an error.\n *\n * Accepts `type` and `field` arguments which identify the connection that is being queried. If the field in question is paginated, its max page size is returned. If it does not exist or is not paginated, `null` is returned.\n */\n maxPageSize?: Maybe<Scalars['Int']['output']>;\n /** Maximum depth of a GraphQL query that can be accepted by this service. */\n maxQueryDepth?: Maybe<Scalars['Int']['output']>;\n /** The maximum number of nodes (field names) the service will accept in a single query. */\n maxQueryNodes?: Maybe<Scalars['Int']['output']>;\n /** Maximum size in bytes of a single GraphQL request, excluding the elements covered by `maxTransactionPayloadSize`. */\n maxQueryPayloadSize?: Maybe<Scalars['Int']['output']>;\n /** Maximum number of paginated fields that can return results in a single request. Queries on paginated fields that exceed this limit will return an error. */\n maxRichQueries?: Maybe<Scalars['Int']['output']>;\n /**\n * Maximum size in bytes allowed for the `txBytes` and `signatures` parameters of an `executeTransaction` or `simulateTransaction` field, or the `bytes` and `signature` parameters of a `verifyZkLoginSignature` field.\n *\n * This is cumulative across all matching fields in a single GraphQL request.\n */\n maxTransactionPayloadSize?: Maybe<Scalars['Int']['output']>;\n /** Maximum amount of nesting among type arguments (type arguments nest when a type argument is itself generic and has arguments). */\n maxTypeArgumentDepth?: Maybe<Scalars['Int']['output']>;\n /** Maximum number of type parameters a type can have. */\n maxTypeArgumentWidth?: Maybe<Scalars['Int']['output']>;\n /** Maximum number of datatypes that need to be processed when calculating the layout of a single type. */\n maxTypeNodes?: Maybe<Scalars['Int']['output']>;\n /** Maximum time in milliseconds spent waiting for a response from fullnode after issuing a transaction to execute. Note that the transaction may still succeed even in the case of a timeout. Transactions are idempotent, so a transaction that times out should be re-submitted until the network returns a definite response (success or failure, not timeout). */\n mutationTimeoutMs?: Maybe<Scalars['Int']['output']>;\n /** Maximum time in milliseconds that will be spent to serve one query request. */\n queryTimeoutMs?: Maybe<Scalars['Int']['output']>;\n};\n\n\nexport type ServiceConfigAvailableRangeArgs = {\n field?: InputMaybe<Scalars['String']['input']>;\n filters?: InputMaybe<Array<Scalars['String']['input']>>;\n type: Scalars['String']['input'];\n};\n\n\nexport type ServiceConfigDefaultPageSizeArgs = {\n field: Scalars['String']['input'];\n type: Scalars['String']['input'];\n};\n\n\nexport type ServiceConfigMaxPageSizeArgs = {\n field: Scalars['String']['input'];\n type: Scalars['String']['input'];\n};\n\n/** Object is shared, can be used by any address, and is mutable. */\nexport type Shared = {\n __typename?: 'Shared';\n /** The version at which the object became shared. */\n initialSharedVersion?: Maybe<Scalars['UInt53']['output']>;\n};\n\n/** A Move object that's shared. */\nexport type SharedInput = {\n __typename?: 'SharedInput';\n /** The address of the shared object. */\n address?: Maybe<Scalars['SuiAddress']['output']>;\n /** The version that this object was shared at. */\n initialSharedVersion?: Maybe<Scalars['UInt53']['output']>;\n /**\n * Controls whether the transaction block can reference the shared object as a mutable reference or by value.\n *\n * This has implications for scheduling: Transactions that just read shared objects at a certain version (mutable = false) can be executed concurrently, while transactions that write shared objects (mutable = true) must be executed serially with respect to each other.\n */\n mutable?: Maybe<Scalars['Boolean']['output']>;\n};\n\n/** The structured details of a signature, varying by scheme. */\nexport type SignatureScheme = Ed25519Signature | MultisigSignature | PasskeySignature | Secp256K1Signature | Secp256R1Signature | ZkLoginSignature;\n\n/** The result of signature verification. */\nexport type SignatureVerifyResult = {\n __typename?: 'SignatureVerifyResult';\n /** Whether the signature was verified successfully. */\n success?: Maybe<Scalars['Boolean']['output']>;\n};\n\n/** The result of simulating a transaction, including the predicted effects. */\nexport type SimulationResult = {\n __typename?: 'SimulationResult';\n /** The predicted effects of the transaction if it were executed. */\n effects?: Maybe<TransactionEffects>;\n /** The intermediate outputs for each command of the transaction simulation, including contents of mutated references and return values. */\n outputs?: Maybe<Array<CommandResult>>;\n};\n\n/** Splits off coins with denominations in `amounts` from `coin`, returning multiple results (as many as there are amounts.) */\nexport type SplitCoinsCommand = {\n __typename?: 'SplitCoinsCommand';\n /** The denominations to split off from the coin. */\n amounts: Array<TransactionArgument>;\n /** The coin to split. */\n coin?: Maybe<TransactionArgument>;\n};\n\n/** System transaction for storing execution time observations. */\nexport type StoreExecutionTimeObservationsTransaction = {\n __typename?: 'StoreExecutionTimeObservationsTransaction';\n /** A workaround to define an empty variant of a GraphQL union. */\n _?: Maybe<Scalars['Boolean']['output']>;\n};\n\n/** Future behavior of a currency's supply. */\nexport enum SupplyState {\n /** The supply can only decrease. */\n BurnOnly = 'BURN_ONLY',\n /** The supply can neither increase nor decrease. */\n Fixed = 'FIXED'\n}\n\n/** Description of a transaction, the unit of activity on Sui. */\nexport type Transaction = Node & {\n __typename?: 'Transaction';\n /** A 32-byte hash that uniquely identifies the transaction contents, encoded in Base58. */\n digest: Scalars['String']['output'];\n /** The results to the chain of executing this transaction. */\n effects?: Maybe<TransactionEffects>;\n /** This field is set by senders of a transaction block. It is an epoch reference that sets a deadline after which validators will no longer consider the transaction valid. By default, there is no deadline for when a transaction must execute. */\n expiration?: Maybe<Epoch>;\n /** The gas input field provides information on what objects were used as gas as well as the owner of the gas object(s) and information on the gas price and budget. */\n gasInput?: Maybe<GasInput>;\n /** The transaction's globally unique identifier, which can be passed to `Query.node` to refetch it. */\n id: Scalars['ID']['output'];\n /** The type of this transaction as well as the commands and/or parameters comprising the transaction of this kind. */\n kind?: Maybe<TransactionKind>;\n /** The address corresponding to the public key that signed this transaction. System transactions do not have senders. */\n sender?: Maybe<Address>;\n /** User signatures for this transaction. */\n signatures: Array<UserSignature>;\n /** The Base64-encoded BCS serialization of this transaction, as a `TransactionData`. */\n transactionBcs?: Maybe<Scalars['Base64']['output']>;\n /** The transaction as a JSON blob, matching the gRPC proto format (excluding BCS). */\n transactionJson?: Maybe<Scalars['JSON']['output']>;\n};\n\n/** An argument to a programmable transaction command. */\nexport type TransactionArgument = GasCoin | Input | TxResult;\n\nexport type TransactionConnection = {\n __typename?: 'TransactionConnection';\n /** A list of edges. */\n edges: Array<TransactionEdge>;\n /** A list of nodes. */\n nodes: Array<Transaction>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type TransactionEdge = {\n __typename?: 'TransactionEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: Transaction;\n};\n\n/** The results of executing a transaction. */\nexport type TransactionEffects = {\n __typename?: 'TransactionEffects';\n /** The effect this transaction had on the balances (sum of coin values per coin type) of addresses and objects. */\n balanceChanges?: Maybe<BalanceChangeConnection>;\n /** The balance changes as a JSON array, matching the gRPC proto format. */\n balanceChangesJson?: Maybe<Scalars['JSON']['output']>;\n /** The checkpoint this transaction was finalized in. */\n checkpoint?: Maybe<Checkpoint>;\n /** Transactions whose outputs this transaction depends upon. */\n dependencies?: Maybe<TransactionConnection>;\n /**\n * A 32-byte hash that uniquely identifies the transaction contents, encoded in Base58.\n *\n * Note that this is different from the execution digest, which is the unique hash of the transaction effects.\n */\n digest: Scalars['String']['output'];\n /** The Base64-encoded BCS serialization of these effects, as `TransactionEffects`. */\n effectsBcs?: Maybe<Scalars['Base64']['output']>;\n /** A 32-byte hash that uniquely identifies the effects contents, encoded in Base58. */\n effectsDigest?: Maybe<Scalars['String']['output']>;\n /** The effects as a JSON blob, matching the gRPC proto format (excluding BCS). */\n effectsJson?: Maybe<Scalars['JSON']['output']>;\n /** The epoch this transaction was finalized in. */\n epoch?: Maybe<Epoch>;\n /** Events emitted by this transaction. */\n events?: Maybe<EventConnection>;\n /** Rich execution error information for failed transactions. */\n executionError?: Maybe<ExecutionError>;\n /** Effects related to the gas object used for the transaction (costs incurred and the identity of the smashed gas object returned). */\n gasEffects?: Maybe<GasEffects>;\n /** The latest version of all objects (apart from packages) that have been created or modified by this transaction, immediately following this transaction. */\n lamportVersion?: Maybe<Scalars['UInt53']['output']>;\n /** The before and after state of objects that were modified by this transaction. */\n objectChanges?: Maybe<ObjectChangeConnection>;\n /** Whether the transaction executed successfully or not. */\n status?: Maybe<ExecutionStatus>;\n /**\n * Timestamp corresponding to the checkpoint this transaction was finalized in.\n *\n * `null` for executed/simulated transactions that have not been included in a checkpoint.\n */\n timestamp?: Maybe<Scalars['DateTime']['output']>;\n /** The transaction that ran to produce these effects. */\n transaction?: Maybe<Transaction>;\n /** The unchanged consensus-managed objects that were referenced by this transaction. */\n unchangedConsensusObjects?: Maybe<UnchangedConsensusObjectConnection>;\n /** The schema version of the effects struct. */\n version?: Maybe<Scalars['Int']['output']>;\n};\n\n\n/** The results of executing a transaction. */\nexport type TransactionEffectsBalanceChangesArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** The results of executing a transaction. */\nexport type TransactionEffectsDependenciesArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** The results of executing a transaction. */\nexport type TransactionEffectsEventsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** The results of executing a transaction. */\nexport type TransactionEffectsObjectChangesArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n\n/** The results of executing a transaction. */\nexport type TransactionEffectsUnchangedConsensusObjectsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\nexport type TransactionFilter = {\n /**\n * Limit to transactions that interacted with the given address.\n * The address could be a sender, sponsor, or recipient of the transaction.\n */\n affectedAddress?: InputMaybe<Scalars['SuiAddress']['input']>;\n /**\n * Limit to transactions that interacted with the given object.\n * The object could have been created, read, modified, deleted, wrapped, or unwrapped by the transaction.\n * Objects that were passed as a `Receiving` input are not considered to have been affected by a transaction unless they were actually received.\n */\n affectedObject?: InputMaybe<Scalars['SuiAddress']['input']>;\n /** Filter to transactions that occurred strictly after the given checkpoint. */\n afterCheckpoint?: InputMaybe<Scalars['UInt53']['input']>;\n /** Filter to transactions in the given checkpoint. */\n atCheckpoint?: InputMaybe<Scalars['UInt53']['input']>;\n /** Filter to transaction that occurred strictly before the given checkpoint. */\n beforeCheckpoint?: InputMaybe<Scalars['UInt53']['input']>;\n /** Filter transactions by move function called. Calls can be filtered by the `package`, `package::module`, or the `package::module::name` of their function. */\n function?: InputMaybe<Scalars['String']['input']>;\n /** An input filter selecting for either system or programmable transactions. */\n kind?: InputMaybe<TransactionKindInput>;\n /** Limit to transactions that were sent by the given address. */\n sentAddress?: InputMaybe<Scalars['SuiAddress']['input']>;\n};\n\n/** Input argument to a Programmable Transaction Block (PTB) command. */\nexport type TransactionInput = BalanceWithdraw | MoveValue | OwnedOrImmutable | Pure | Receiving | SharedInput;\n\nexport type TransactionInputConnection = {\n __typename?: 'TransactionInputConnection';\n /** A list of edges. */\n edges: Array<TransactionInputEdge>;\n /** A list of nodes. */\n nodes: Array<TransactionInput>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type TransactionInputEdge = {\n __typename?: 'TransactionInputEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: TransactionInput;\n};\n\n/** Different types of transactions that can be executed on the Sui network. */\nexport type TransactionKind = AuthenticatorStateUpdateTransaction | ChangeEpochTransaction | ConsensusCommitPrologueTransaction | EndOfEpochTransaction | GenesisTransaction | ProgrammableSystemTransaction | ProgrammableTransaction | RandomnessStateUpdateTransaction;\n\n/** An input filter selecting for either system or programmable transactions. */\nexport enum TransactionKindInput {\n /** A user submitted transaction block. */\n ProgrammableTx = 'PROGRAMMABLE_TX',\n /**\n * A system transaction can be one of several types of transactions.\n * See [unions/transaction-block-kind] for more details.\n */\n SystemTx = 'SYSTEM_TX'\n}\n\n/** Transfers `inputs` to `address`. All inputs must have the `store` ability (allows public transfer) and must not be previously immutable or shared. */\nexport type TransferObjectsCommand = {\n __typename?: 'TransferObjectsCommand';\n /** The address to transfer to. */\n address?: Maybe<TransactionArgument>;\n /** The objects to transfer. */\n inputs: Array<TransactionArgument>;\n};\n\n/** The result of another command. */\nexport type TxResult = {\n __typename?: 'TxResult';\n /** The index of the command that produced this result. */\n cmd?: Maybe<Scalars['Int']['output']>;\n /** For nested results, the index within the result. */\n ix?: Maybe<Scalars['Int']['output']>;\n};\n\n/** Information about which previous versions of a package introduced its types. */\nexport type TypeOrigin = {\n __typename?: 'TypeOrigin';\n /** The storage ID of the package that first defined this type. */\n definingId?: Maybe<Scalars['SuiAddress']['output']>;\n /** Module defining the type. */\n module?: Maybe<Scalars['String']['output']>;\n /** Name of the struct. */\n struct?: Maybe<Scalars['String']['output']>;\n};\n\n/** Details pertaining to consensus-managed objects that are referenced by but not changed by a transaction. */\nexport type UnchangedConsensusObject = ConsensusObjectCancelled | ConsensusObjectRead | MutateConsensusStreamEnded | PerEpochConfig | ReadConsensusStreamEnded;\n\nexport type UnchangedConsensusObjectConnection = {\n __typename?: 'UnchangedConsensusObjectConnection';\n /** A list of edges. */\n edges: Array<UnchangedConsensusObjectEdge>;\n /** A list of nodes. */\n nodes: Array<UnchangedConsensusObject>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type UnchangedConsensusObjectEdge = {\n __typename?: 'UnchangedConsensusObjectEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: UnchangedConsensusObject;\n};\n\n/** Upgrades a Move Package. */\nexport type UpgradeCommand = {\n __typename?: 'UpgradeCommand';\n /** ID of the package being upgraded. */\n currentPackage?: Maybe<Scalars['SuiAddress']['output']>;\n /** IDs of the transitive dependencies of the package to be published. */\n dependencies?: Maybe<Array<Scalars['SuiAddress']['output']>>;\n /** Bytecode for the modules to be published, BCS serialized and Base64 encoded. */\n modules?: Maybe<Array<Scalars['Base64']['output']>>;\n /** The `UpgradeTicket` authorizing the upgrade. */\n upgradeTicket?: Maybe<TransactionArgument>;\n};\n\nexport type UserSignature = {\n __typename?: 'UserSignature';\n /** The structured signature details, parsed by scheme. */\n scheme?: Maybe<SignatureScheme>;\n /**\n * The signature bytes, Base64-encoded.\n * For simple signatures: flag || signature || pubkey\n * For complex signatures: flag || bcs_serialized_struct\n */\n signatureBytes?: Maybe<Scalars['Base64']['output']>;\n};\n\nexport type Validator = {\n __typename?: 'Validator';\n /** The number of epochs for which this validator has been below the low stake threshold. */\n atRisk?: Maybe<Scalars['UInt53']['output']>;\n /** On-chain representation of the underlying `0x3::validator::Validator` value. */\n contents?: Maybe<MoveValue>;\n /** Other validators this validator has reported. */\n reportRecords?: Maybe<ValidatorConnection>;\n};\n\n\nexport type ValidatorReportRecordsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\nexport type ValidatorAggregatedSignature = {\n __typename?: 'ValidatorAggregatedSignature';\n /** The epoch when this aggregate signature was produced. */\n epoch?: Maybe<Epoch>;\n /** The Base64 encoded BLS12381 aggregated signature. */\n signature?: Maybe<Scalars['Base64']['output']>;\n /** The indexes of validators that contributed to this signature. */\n signersMap: Array<Scalars['Int']['output']>;\n};\n\nexport type ValidatorConnection = {\n __typename?: 'ValidatorConnection';\n /** A list of edges. */\n edges: Array<ValidatorEdge>;\n /** A list of nodes. */\n nodes: Array<Validator>;\n /** Information to aid in pagination. */\n pageInfo: PageInfo;\n};\n\n/** An edge in a connection. */\nexport type ValidatorEdge = {\n __typename?: 'ValidatorEdge';\n /** A cursor for use in pagination */\n cursor: Scalars['String']['output'];\n /** The item at the end of the edge */\n node: Validator;\n};\n\n/** Representation of `0x3::validator_set::ValidatorSet`. */\nexport type ValidatorSet = {\n __typename?: 'ValidatorSet';\n /** The validators currently in the committee for this validator set. */\n activeValidators?: Maybe<ValidatorConnection>;\n /** On-chain representation of the underlying `0x3::validator_set::ValidatorSet` value. */\n contents?: Maybe<MoveValue>;\n};\n\n\n/** Representation of `0x3::validator_set::ValidatorSet`. */\nexport type ValidatorSetActiveValidatorsArgs = {\n after?: InputMaybe<Scalars['String']['input']>;\n before?: InputMaybe<Scalars['String']['input']>;\n first?: InputMaybe<Scalars['Int']['input']>;\n last?: InputMaybe<Scalars['Int']['input']>;\n};\n\n/** Filter for paginating the history of an Object or MovePackage. */\nexport type VersionFilter = {\n /** Filter to versions that are strictly newer than this one, defaults to fetching from the earliest version known to this RPC (this could be the initial version, or some later version if the initial version has been pruned). */\n afterVersion?: InputMaybe<Scalars['UInt53']['input']>;\n /** Filter to versions that are strictly older than this one, defaults to fetching up to the latest version (inclusive). */\n beforeVersion?: InputMaybe<Scalars['UInt53']['input']>;\n};\n\n/** The account to withdraw funds from. */\nexport enum WithdrawFrom {\n /** The funds are withdrawn from the transaction sender's account. */\n Sender = 'SENDER',\n /** The funds are withdrawn from the sponsor's account. */\n Sponsor = 'SPONSOR'\n}\n\nexport type WithdrawMaxAmountU64 = {\n __typename?: 'WithdrawMaxAmountU64';\n amount?: Maybe<Scalars['BigInt']['output']>;\n};\n\n/** Reservation details for a withdrawal. */\nexport type WithdrawalReservation = WithdrawMaxAmountU64;\n\n/** System transaction for writing the pre-computed storage cost for accumulator objects. */\nexport type WriteAccumulatorStorageCostTransaction = {\n __typename?: 'WriteAccumulatorStorageCostTransaction';\n /** A workaround to define an empty variant of a GraphQL union. */\n _?: Maybe<Scalars['Boolean']['output']>;\n};\n\n/** A Base64-encoded claim from the JWT used in zkLogin. */\nexport type ZkLoginClaim = {\n __typename?: 'ZkLoginClaim';\n /** The index mod 4 used for Base64 decoding alignment. */\n indexMod4?: Maybe<Scalars['Int']['output']>;\n /** The Base64url-unpadded encoded claim value. */\n value?: Maybe<Scalars['String']['output']>;\n};\n\n/** The zkLogin inputs including proof, claim details, and JWT header. */\nexport type ZkLoginInputs = {\n __typename?: 'ZkLoginInputs';\n /** The address seed as a base10-encoded string. */\n addressSeed?: Maybe<Scalars['String']['output']>;\n /** The Base64-encoded JWT header. */\n headerBase64?: Maybe<Scalars['String']['output']>;\n /** The Base64-encoded issuer claim details. */\n issBase64Details?: Maybe<ZkLoginClaim>;\n /** The zero-knowledge proof points. */\n proofPoints?: Maybe<ZkLoginProof>;\n};\n\n/** An enum that specifies the intent scope to be used to parse the bytes for signature verification. */\nexport enum ZkLoginIntentScope {\n /** Indicates that the bytes are to be parsed as a personal message. */\n PersonalMessage = 'PERSONAL_MESSAGE',\n /** Indicates that the bytes are to be parsed as transaction data bytes. */\n TransactionData = 'TRANSACTION_DATA'\n}\n\n/** A JWK (JSON Web Key) identifier. */\nexport type ZkLoginJwkId = {\n __typename?: 'ZkLoginJwkId';\n /** The OIDC provider issuer string. */\n iss?: Maybe<Scalars['String']['output']>;\n /** The key ID that identifies the JWK. */\n kid?: Maybe<Scalars['String']['output']>;\n};\n\n/** The zero-knowledge proof consisting of three elliptic curve points. */\nexport type ZkLoginProof = {\n __typename?: 'ZkLoginProof';\n /** G1 point 'a'. */\n a?: Maybe<CircomG1>;\n /** G2 point 'b'. */\n b?: Maybe<CircomG2>;\n /** G1 point 'c'. */\n c?: Maybe<CircomG1>;\n};\n\n/** A zkLogin public identifier, containing the OAuth issuer and address seed. */\nexport type ZkLoginPublicIdentifier = {\n __typename?: 'ZkLoginPublicIdentifier';\n /** The address seed as a decimal string. */\n addressSeed?: Maybe<Scalars['String']['output']>;\n /** The OAuth provider issuer string (e.g. \"https://accounts.google.com\"). */\n iss?: Maybe<Scalars['String']['output']>;\n};\n\nexport type ZkLoginSignature = {\n __typename?: 'ZkLoginSignature';\n /** The zkLogin inputs including proof, claim details, and JWT header. */\n inputs?: Maybe<ZkLoginInputs>;\n /** The JWK identifier used to verify the zkLogin proof. */\n jwkId?: Maybe<ZkLoginJwkId>;\n /** The maximum epoch for which this signature is valid. */\n maxEpoch?: Maybe<Scalars['UInt53']['output']>;\n /** The public identifier (issuer + address seed) for this zkLogin authenticator. */\n publicIdentifier?: Maybe<ZkLoginPublicIdentifier>;\n /** The inner user signature (ed25519/secp256k1/secp256r1). */\n signature?: Maybe<SignatureScheme>;\n};\n\n/** The result of the zkLogin signature verification. */\nexport type ZkLoginVerifyResult = {\n __typename?: 'ZkLoginVerifyResult';\n /** Whether the signature was verified successfully. */\n success?: Maybe<Scalars['Boolean']['output']>;\n};\n\nexport type GetAllBalancesQueryVariables = Exact<{\n owner: Scalars['SuiAddress']['input'];\n limit?: InputMaybe<Scalars['Int']['input']>;\n cursor?: InputMaybe<Scalars['String']['input']>;\n}>;\n\n\nexport type GetAllBalancesQuery = { __typename?: 'Query', address?: { __typename?: 'Address', balances?: { __typename?: 'BalanceConnection', pageInfo: { __typename?: 'PageInfo', hasNextPage: boolean, endCursor?: string | null }, nodes: Array<{ __typename?: 'Balance', totalBalance?: string | null, addressBalance?: string | null, coinType?: { __typename?: 'MoveType', repr: string } | null }> } | null } | null };\n\nexport type GetBalanceQueryVariables = Exact<{\n owner: Scalars['SuiAddress']['input'];\n coinType?: InputMaybe<Scalars['String']['input']>;\n}>;\n\n\nexport type GetBalanceQuery = { __typename?: 'Query', address?: { __typename?: 'Address', balance?: { __typename?: 'Balance', totalBalance?: string | null, addressBalance?: string | null, coinType?: { __typename?: 'MoveType', repr: string } | null } | null } | null };\n\nexport type GetChainIdentifierQueryVariables = Exact<{ [key: string]: never; }>;\n\n\nexport type GetChainIdentifierQuery = { __typename?: 'Query', checkpoint?: { __typename?: 'Checkpoint', digest?: string | null } | null };\n\nexport type GetCoinMetadataQueryVariables = Exact<{\n coinType: Scalars['String']['input'];\n}>;\n\n\nexport type GetCoinMetadataQuery = { __typename?: 'Query', coinMetadata?: { __typename?: 'CoinMetadata', address: string, decimals?: number | null, name?: string | null, symbol?: string | null, description?: string | null, iconUrl?: string | null } | null };\n\nexport type GetCoinsQueryVariables = Exact<{\n owner: Scalars['SuiAddress']['input'];\n first?: InputMaybe<Scalars['Int']['input']>;\n cursor?: InputMaybe<Scalars['String']['input']>;\n type?: InputMaybe<Scalars['String']['input']>;\n}>;\n\n\nexport type GetCoinsQuery = { __typename?: 'Query', address?: { __typename?: 'Address', address: string, objects?: { __typename?: 'MoveObjectConnection', pageInfo: { __typename?: 'PageInfo', hasNextPage: boolean, endCursor?: string | null }, nodes: Array<{ __typename?: 'MoveObject', address: string, version?: number | null, digest?: string | null, owner?:\n | { __typename: 'AddressOwner', address?: { __typename?: 'Address', address: string } | null }\n | { __typename: 'ConsensusAddressOwner', startVersion?: number | null, address?: { __typename?: 'Address', address: string } | null }\n | { __typename: 'Immutable' }\n | { __typename: 'ObjectOwner', address?: { __typename?: 'Address', address: string } | null }\n | { __typename: 'Shared', initialSharedVersion?: number | null }\n | null, contents?: { __typename?: 'MoveValue', json?: unknown | null, type?: { __typename?: 'MoveType', repr: string } | null } | null }> } | null } | null };\n\nexport type GetCurrentSystemStateQueryVariables = Exact<{ [key: string]: never; }>;\n\n\nexport type GetCurrentSystemStateQuery = { __typename?: 'Query', epoch?: { __typename?: 'Epoch', epochId: number, referenceGasPrice?: string | null, startTimestamp?: string | null, protocolConfigs?: { __typename?: 'ProtocolConfigs', protocolVersion: number } | null, systemState?: { __typename?: 'MoveValue', json?: unknown | null } | null } | null };\n\nexport type GetDynamicFieldsQueryVariables = Exact<{\n parentId: Scalars['SuiAddress']['input'];\n first?: InputMaybe<Scalars['Int']['input']>;\n cursor?: InputMaybe<Scalars['String']['input']>;\n includeValue?: InputMaybe<Scalars['Boolean']['input']>;\n}>;\n\n\nexport type GetDynamicFieldsQuery = { __typename?: 'Query', address?: { __typename?: 'Address', dynamicFields?: { __typename?: 'DynamicFieldConnection', pageInfo: { __typename?: 'PageInfo', hasNextPage: boolean, endCursor?: string | null }, nodes: Array<{ __typename?: 'DynamicField', name?: { __typename?: 'MoveValue', bcs?: string | null, type?: { __typename?: 'MoveType', repr: string } | null } | null, value?:\n | { __typename: 'MoveObject', address: string, contents?: { __typename?: 'MoveValue', bcs?: string | null, type?: { __typename?: 'MoveType', repr: string } | null } | null }\n | { __typename: 'MoveValue', bcs?: string | null, type?: { __typename?: 'MoveType', repr: string } | null }\n | null }> } | null } | null };\n\nexport type GetMoveFunctionQueryVariables = Exact<{\n package: Scalars['SuiAddress']['input'];\n module: Scalars['String']['input'];\n function: Scalars['String']['input'];\n}>;\n\n\nexport type GetMoveFunctionQuery = { __typename?: 'Query', package?: { __typename?: 'MovePackage', module?: { __typename?: 'MoveModule', function?: { __typename?: 'MoveFunction', name: string, visibility?: MoveVisibility | null, isEntry?: boolean | null, typeParameters?: Array<{ __typename?: 'MoveFunctionTypeParameter', constraints: Array<MoveAbility> }> | null, parameters?: Array<{ __typename?: 'OpenMoveType', signature: OpenMoveTypeSignature }> | null, return?: Array<{ __typename?: 'OpenMoveType', signature: OpenMoveTypeSignature }> | null } | null } | null } | null };\n\nexport type GetProtocolConfigQueryVariables = Exact<{ [key: string]: never; }>;\n\n\nexport type GetProtocolConfigQuery = { __typename?: 'Query', epoch?: { __typename?: 'Epoch', protocolConfigs?: { __typename?: 'ProtocolConfigs', protocolVersion: number, featureFlags: Array<{ __typename?: 'FeatureFlag', key: string, value: boolean }>, configs: Array<{ __typename?: 'ProtocolConfig', key: string, value?: string | null }> } | null } | null };\n\nexport type GetReferenceGasPriceQueryVariables = Exact<{ [key: string]: never; }>;\n\n\nexport type GetReferenceGasPriceQuery = { __typename?: 'Query', epoch?: { __typename?: 'Epoch', referenceGasPrice?: string | null } | null };\n\nexport type DefaultSuinsNameQueryVariables = Exact<{\n address: Scalars['SuiAddress']['input'];\n}>;\n\n\nexport type DefaultSuinsNameQuery = { __typename?: 'Query', address?: { __typename?: 'Address', defaultNameRecord?: { __typename?: 'NameRecord', domain: string } | null } | null };\n\nexport type GetOwnedObjectsQueryVariables = Exact<{\n owner: Scalars['SuiAddress']['input'];\n limit?: InputMaybe<Scalars['Int']['input']>;\n cursor?: InputMaybe<Scalars['String']['input']>;\n filter?: InputMaybe<ObjectFilter>;\n includeContent?: InputMaybe<Scalars['Boolean']['input']>;\n includePreviousTransaction?: InputMaybe<Scalars['Boolean']['input']>;\n includeObjectBcs?: InputMaybe<Scalars['Boolean']['input']>;\n includeJson?: InputMaybe<Scalars['Boolean']['input']>;\n includeDisplay?: InputMaybe<Scalars['Boolean']['input']>;\n}>;\n\n\nexport type GetOwnedObjectsQuery = { __typename?: 'Query', address?: { __typename?: 'Address', objects?: { __typename?: 'MoveObjectConnection', pageInfo: { __typename?: 'PageInfo', hasNextPage: boolean, endCursor?: string | null }, nodes: Array<{ __typename?: 'MoveObject', address: string, digest?: string | null, version?: number | null, objectBcs?: string | null, contents?: { __typename?: 'MoveValue', bcs?: string | null, json?: unknown | null, display?: { __typename?: 'Display', output?: unknown | null, errors?: unknown | null } | null, type?: { __typename?: 'MoveType', repr: string } | null } | null, owner?:\n | { __typename: 'AddressOwner', address?: { __typename?: 'Address', address: string } | null }\n | { __typename: 'ConsensusAddressOwner', startVersion?: number | null, address?: { __typename?: 'Address', address: string } | null }\n | { __typename: 'Immutable' }\n | { __typename: 'ObjectOwner', address?: { __typename?: 'Address', address: string } | null }\n | { __typename: 'Shared', initialSharedVersion?: number | null }\n | null, previousTransaction?: { __typename?: 'Transaction', digest: string } | null }> } | null } | null };\n\nexport type MultiGetObjectsQueryVariables = Exact<{\n objectKeys: Array<ObjectKey> | ObjectKey;\n includeContent?: InputMaybe<Scalars['Boolean']['input']>;\n includePreviousTransaction?: InputMaybe<Scalars['Boolean']['input']>;\n includeObjectBcs?: InputMaybe<Scalars['Boolean']['input']>;\n includeJson?: InputMaybe<Scalars['Boolean']['input']>;\n includeDisplay?: InputMaybe<Scalars['Boolean']['input']>;\n}>;\n\n\nexport type MultiGetObjectsQuery = { __typename?: 'Query', multiGetObjects: Array<{ __typename?: 'Object', address: string, digest?: string | null, version?: number | null, objectBcs?: string | null, asMoveObject?: { __typename?: 'MoveObject', contents?: { __typename?: 'MoveValue', bcs?: string | null, json?: unknown | null, display?: { __typename?: 'Display', output?: unknown | null, errors?: unknown | null } | null, type?: { __typename?: 'MoveType', repr: string } | null } | null } | null, asMovePackage?: { __typename: 'MovePackage' } | null, owner?:\n | { __typename: 'AddressOwner', address?: { __typename?: 'Address', address: string } | null }\n | { __typename: 'ConsensusAddressOwner', startVersion?: number | null, address?: { __typename?: 'Address', address: string } | null }\n | { __typename: 'Immutable' }\n | { __typename: 'ObjectOwner', address?: { __typename?: 'Address', address: string } | null }\n | { __typename: 'Shared', initialSharedVersion?: number | null }\n | null, previousTransaction?: { __typename?: 'Transaction', digest: string } | null } | null> };\n\nexport type Object_FieldsFragment = { __typename?: 'Object', address: string, digest?: string | null, version?: number | null, objectBcs?: string | null, asMoveObject?: { __typename?: 'MoveObject', contents?: { __typename?: 'MoveValue', bcs?: string | null, json?: unknown | null, display?: { __typename?: 'Display', output?: unknown | null, errors?: unknown | null } | null, type?: { __typename?: 'MoveType', repr: string } | null } | null } | null, asMovePackage?: { __typename: 'MovePackage' } | null, owner?:\n | { __typename: 'AddressOwner', address?: { __typename?: 'Address', address: string } | null }\n | { __typename: 'ConsensusAddressOwner', startVersion?: number | null, address?: { __typename?: 'Address', address: string } | null }\n | { __typename: 'Immutable' }\n | { __typename: 'ObjectOwner', address?: { __typename?: 'Address', address: string } | null }\n | { __typename: 'Shared', initialSharedVersion?: number | null }\n | null, previousTransaction?: { __typename?: 'Transaction', digest: string } | null };\n\nexport type Move_Object_FieldsFragment = { __typename?: 'MoveObject', address: string, digest?: string | null, version?: number | null, objectBcs?: string | null, contents?: { __typename?: 'MoveValue', bcs?: string | null, json?: unknown | null, display?: { __typename?: 'Display', output?: unknown | null, errors?: unknown | null } | null, type?: { __typename?: 'MoveType', repr: string } | null } | null, owner?:\n | { __typename: 'AddressOwner', address?: { __typename?: 'Address', address: string } | null }\n | { __typename: 'ConsensusAddressOwner', startVersion?: number | null, address?: { __typename?: 'Address', address: string } | null }\n | { __typename: 'Immutable' }\n | { __typename: 'ObjectOwner', address?: { __typename?: 'Address', address: string } | null }\n | { __typename: 'Shared', initialSharedVersion?: number | null }\n | null, previousTransaction?: { __typename?: 'Transaction', digest: string } | null };\n\ntype Object_Owner_Fields_AddressOwner_Fragment = { __typename: 'AddressOwner', address?: { __typename?: 'Address', address: string } | null };\n\ntype Object_Owner_Fields_ConsensusAddressOwner_Fragment = { __typename: 'ConsensusAddressOwner', startVersion?: number | null, address?: { __typename?: 'Address', address: string } | null };\n\ntype Object_Owner_Fields_Immutable_Fragment = { __typename: 'Immutable' };\n\ntype Object_Owner_Fields_ObjectOwner_Fragment = { __typename: 'ObjectOwner', address?: { __typename?: 'Address', address: string } | null };\n\ntype Object_Owner_Fields_Shared_Fragment = { __typename: 'Shared', initialSharedVersion?: number | null };\n\nexport type Object_Owner_FieldsFragment =\n | Object_Owner_Fields_AddressOwner_Fragment\n | Object_Owner_Fields_ConsensusAddressOwner_Fragment\n | Object_Owner_Fields_Immutable_Fragment\n | Object_Owner_Fields_ObjectOwner_Fragment\n | Object_Owner_Fields_Shared_Fragment\n;\n\nexport type SimulateTransactionQueryVariables = Exact<{\n transaction: Scalars['JSON']['input'];\n includeTransaction?: InputMaybe<Scalars['Boolean']['input']>;\n includeEffects?: InputMaybe<Scalars['Boolean']['input']>;\n includeEvents?: InputMaybe<Scalars['Boolean']['input']>;\n includeBalanceChanges?: InputMaybe<Scalars['Boolean']['input']>;\n includeObjectTypes?: InputMaybe<Scalars['Boolean']['input']>;\n includeCommandResults?: InputMaybe<Scalars['Boolean']['input']>;\n includeBcs?: InputMaybe<Scalars['Boolean']['input']>;\n doGasSelection?: InputMaybe<Scalars['Boolean']['input']>;\n checksEnabled?: InputMaybe<Scalars['Boolean']['input']>;\n}>;\n\n\nexport type SimulateTransactionQuery = { __typename?: 'Query', simulateTransaction: { __typename?: 'SimulationResult', effects?: { __typename?: 'TransactionEffects', transaction?: { __typename?: 'Transaction', digest: string, transactionJson?: unknown | null, transactionBcs?: string | null, signatures: Array<{ __typename?: 'UserSignature', signatureBytes?: string | null }>, effects?: { __typename?: 'TransactionEffects', status?: ExecutionStatus | null, effectsBcs?: string | null, effectsJson?: unknown | null, balanceChangesJson?: unknown | null, executionError?: { __typename?: 'ExecutionError', message: string, abortCode?: string | null, identifier?: string | null, constant?: string | null, sourceLineNumber?: number | null, instructionOffset?: number | null, module?: { __typename?: 'MoveModule', name: string, package?: { __typename?: 'MovePackage', address: string } | null } | null, function?: { __typename?: 'MoveFunction', name: string } | null } | null, epoch?: { __typename?: 'Epoch', epochId: number } | null, objectChanges?: { __typename?: 'ObjectChangeConnection', nodes: Array<{ __typename?: 'ObjectChange', address: string, outputState?: { __typename?: 'Object', asMoveObject?: { __typename?: 'MoveObject', contents?: { __typename?: 'MoveValue', type?: { __typename?: 'MoveType', repr: string } | null } | null } | null } | null }> } | null, events?: { __typename?: 'EventConnection', pageInfo: { __typename?: 'PageInfo', hasNextPage: boolean }, nodes: Array<{ __typename?: 'Event', transactionModule?: { __typename?: 'MoveModule', name: string, package?: { __typename?: 'MovePackage', address: string } | null } | null, sender?: { __typename?: 'Address', address: string } | null, contents?: { __typename?: 'MoveValue', bcs?: string | null, json?: unknown | null, type?: { __typename?: 'MoveType', repr: string } | null } | null }> } | null } | null } | null } | null, outputs?: Array<{ __typename?: 'CommandResult', returnValues?: Array<{ __typename?: 'CommandOutput', value?: { __typename?: 'MoveValue', bcs?: string | null } | null }> | null, mutatedReferences?: Array<{ __typename?: 'CommandOutput', value?: { __typename?: 'MoveValue', bcs?: string | null } | null }> | null }> | null } };\n\nexport type ExecuteTransactionMutationVariables = Exact<{\n transactionDataBcs: Scalars['Base64']['input'];\n signatures: Array<Scalars['Base64']['input']> | Scalars['Base64']['input'];\n includeTransaction?: InputMaybe<Scalars['Boolean']['input']>;\n includeEffects?: InputMaybe<Scalars['Boolean']['input']>;\n includeEvents?: InputMaybe<Scalars['Boolean']['input']>;\n includeBalanceChanges?: InputMaybe<Scalars['Boolean']['input']>;\n includeObjectTypes?: InputMaybe<Scalars['Boolean']['input']>;\n includeBcs?: InputMaybe<Scalars['Boolean']['input']>;\n}>;\n\n\nexport type ExecuteTransactionMutation = { __typename?: 'Mutation', executeTransaction: { __typename?: 'ExecutionResult', effects?: { __typename?: 'TransactionEffects', transaction?: { __typename?: 'Transaction', digest: string, transactionJson?: unknown | null, transactionBcs?: string | null, signatures: Array<{ __typename?: 'UserSignature', signatureBytes?: string | null }>, effects?: { __typename?: 'TransactionEffects', status?: ExecutionStatus | null, effectsBcs?: string | null, effectsJson?: unknown | null, balanceChangesJson?: unknown | null, executionError?: { __typename?: 'ExecutionError', message: string, abortCode?: string | null, identifier?: string | null, constant?: string | null, sourceLineNumber?: number | null, instructionOffset?: number | null, module?: { __typename?: 'MoveModule', name: string, package?: { __typename?: 'MovePackage', address: string } | null } | null, function?: { __typename?: 'MoveFunction', name: string } | null } | null, epoch?: { __typename?: 'Epoch', epochId: number } | null, objectChanges?: { __typename?: 'ObjectChangeConnection', nodes: Array<{ __typename?: 'ObjectChange', address: string, outputState?: { __typename?: 'Object', asMoveObject?: { __typename?: 'MoveObject', contents?: { __typename?: 'MoveValue', type?: { __typename?: 'MoveType', repr: string } | null } | null } | null } | null }> } | null, events?: { __typename?: 'EventConnection', pageInfo: { __typename?: 'PageInfo', hasNextPage: boolean }, nodes: Array<{ __typename?: 'Event', transactionModule?: { __typename?: 'MoveModule', name: string, package?: { __typename?: 'MovePackage', address: string } | null } | null, sender?: { __typename?: 'Address', address: string } | null, contents?: { __typename?: 'MoveValue', bcs?: string | null, json?: unknown | null, type?: { __typename?: 'MoveType', repr: string } | null } | null }> } | null } | null } | null } | null } };\n\nexport type GetTransactionBlockQueryVariables = Exact<{\n digest: Scalars['String']['input'];\n includeTransaction?: InputMaybe<Scalars['Boolean']['input']>;\n includeEffects?: InputMaybe<Scalars['Boolean']['input']>;\n includeEvents?: InputMaybe<Scalars['Boolean']['input']>;\n includeBalanceChanges?: InputMaybe<Scalars['Boolean']['input']>;\n includeObjectTypes?: InputMaybe<Scalars['Boolean']['input']>;\n includeBcs?: InputMaybe<Scalars['Boolean']['input']>;\n}>;\n\n\nexport type GetTransactionBlockQuery = { __typename?: 'Query', transaction?: { __typename?: 'Transaction', digest: string, transactionJson?: unknown | null, transactionBcs?: string | null, signatures: Array<{ __typename?: 'UserSignature', signatureBytes?: string | null }>, effects?: { __typename?: 'TransactionEffects', status?: ExecutionStatus | null, effectsBcs?: string | null, effectsJson?: unknown | null, balanceChangesJson?: unknown | null, executionError?: { __typename?: 'ExecutionError', message: string, abortCode?: string | null, identifier?: string | null, constant?: string | null, sourceLineNumber?: number | null, instructionOffset?: number | null, module?: { __typename?: 'MoveModule', name: string, package?: { __typename?: 'MovePackage', address: string } | null } | null, function?: { __typename?: 'MoveFunction', name: string } | null } | null, epoch?: { __typename?: 'Epoch', epochId: number } | null, objectChanges?: { __typename?: 'ObjectChangeConnection', nodes: Array<{ __typename?: 'ObjectChange', address: string, outputState?: { __typename?: 'Object', asMoveObject?: { __typename?: 'MoveObject', contents?: { __typename?: 'MoveValue', type?: { __typename?: 'MoveType', repr: string } | null } | null } | null } | null }> } | null, events?: { __typename?: 'EventConnection', pageInfo: { __typename?: 'PageInfo', hasNextPage: boolean }, nodes: Array<{ __typename?: 'Event', transactionModule?: { __typename?: 'MoveModule', name: string, package?: { __typename?: 'MovePackage', address: string } | null } | null, sender?: { __typename?: 'Address', address: string } | null, contents?: { __typename?: 'MoveValue', bcs?: string | null, json?: unknown | null, type?: { __typename?: 'MoveType', repr: string } | null } | null }> } | null } | null } | null };\n\nexport type Transaction_FieldsFragment = { __typename?: 'Transaction', digest: string, transactionJson?: unknown | null, transactionBcs?: string | null, signatures: Array<{ __typename?: 'UserSignature', signatureBytes?: string | null }>, effects?: { __typename?: 'TransactionEffects', status?: ExecutionStatus | null, effectsBcs?: string | null, effectsJson?: unknown | null, balanceChangesJson?: unknown | null, executionError?: { __typename?: 'ExecutionError', message: string, abortCode?: string | null, identifier?: string | null, constant?: string | null, sourceLineNumber?: number | null, instructionOffset?: number | null, module?: { __typename?: 'MoveModule', name: string, package?: { __typename?: 'MovePackage', address: string } | null } | null, function?: { __typename?: 'MoveFunction', name: string } | null } | null, epoch?: { __typename?: 'Epoch', epochId: number } | null, objectChanges?: { __typename?: 'ObjectChangeConnection', nodes: Array<{ __typename?: 'ObjectChange', address: string, outputState?: { __typename?: 'Object', asMoveObject?: { __typename?: 'MoveObject', contents?: { __typename?: 'MoveValue', type?: { __typename?: 'MoveType', repr: string } | null } | null } | null } | null }> } | null, events?: { __typename?: 'EventConnection', pageInfo: { __typename?: 'PageInfo', hasNextPage: boolean }, nodes: Array<{ __typename?: 'Event', transactionModule?: { __typename?: 'MoveModule', name: string, package?: { __typename?: 'MovePackage', address: string } | null } | null, sender?: { __typename?: 'Address', address: string } | null, contents?: { __typename?: 'MoveValue', bcs?: string | null, json?: unknown | null, type?: { __typename?: 'MoveType', repr: string } | null } | null }> } | null } | null };\n\nexport type ResolveTransactionQueryVariables = Exact<{\n transaction: Scalars['JSON']['input'];\n doGasSelection?: InputMaybe<Scalars['Boolean']['input']>;\n}>;\n\n\nexport type ResolveTransactionQuery = { __typename?: 'Query', simulateTransaction: { __typename?: 'SimulationResult', effects?: { __typename?: 'TransactionEffects', transaction?: { __typename?: 'Transaction', transactionBcs?: string | null, effects?: { __typename?: 'TransactionEffects', status?: ExecutionStatus | null, executionError?: { __typename?: 'ExecutionError', message: string, abortCode?: string | null, identifier?: string | null, constant?: string | null, sourceLineNumber?: number | null, instructionOffset?: number | null, module?: { __typename?: 'MoveModule', name: string, package?: { __typename?: 'MovePackage', address: string } | null } | null, function?: { __typename?: 'MoveFunction', name: string } | null } | null } | null } | null } | null } };\n\nexport type VerifyZkLoginSignatureQueryVariables = Exact<{\n bytes: Scalars['Base64']['input'];\n signature: Scalars['Base64']['input'];\n intentScope: ZkLoginIntentScope;\n author: Scalars['SuiAddress']['input'];\n}>;\n\n\nexport type VerifyZkLoginSignatureQuery = { __typename?: 'Query', verifyZkLoginSignature?: { __typename?: 'ZkLoginVerifyResult', success?: boolean | null } | null };\n\nexport class TypedDocumentString<TResult, TVariables>\n extends String\n implements DocumentTypeDecoration<TResult, TVariables>\n{\n __apiType?: NonNullable<DocumentTypeDecoration<TResult, TVariables>['__apiType']>;\n private value: string;\n public __meta__?: Record<string, any> | undefined;\n\n constructor(value: string, __meta__?: Record<string, any> | undefined) {\n super(value);\n this.value = value;\n this.__meta__ = __meta__;\n }\n\n override toString(): string & DocumentTypeDecoration<TResult, TVariables> {\n return this.value;\n }\n}\nexport const Object_Owner_FieldsFragmentDoc = new TypedDocumentString(`\n fragment OBJECT_OWNER_FIELDS on Owner {\n __typename\n ... on AddressOwner {\n address {\n address\n }\n }\n ... on ObjectOwner {\n address {\n address\n }\n }\n ... on Shared {\n initialSharedVersion\n }\n ... on ConsensusAddressOwner {\n startVersion\n address {\n address\n }\n }\n}\n `, {\"fragmentName\":\"OBJECT_OWNER_FIELDS\"}) as unknown as TypedDocumentString<Object_Owner_FieldsFragment, unknown>;\nexport const Object_FieldsFragmentDoc = new TypedDocumentString(`\n fragment OBJECT_FIELDS on Object {\n address\n digest\n version\n objectBcs @include(if: $includeObjectBcs)\n asMoveObject {\n contents {\n bcs @include(if: $includeContent)\n json @include(if: $includeJson)\n display @include(if: $includeDisplay) {\n output\n errors\n }\n type {\n repr\n }\n }\n }\n asMovePackage {\n __typename\n }\n owner {\n ...OBJECT_OWNER_FIELDS\n }\n previousTransaction @include(if: $includePreviousTransaction) {\n digest\n }\n}\n fragment OBJECT_OWNER_FIELDS on Owner {\n __typename\n ... on AddressOwner {\n address {\n address\n }\n }\n ... on ObjectOwner {\n address {\n address\n }\n }\n ... on Shared {\n initialSharedVersion\n }\n ... on ConsensusAddressOwner {\n startVersion\n address {\n address\n }\n }\n}`, {\"fragmentName\":\"OBJECT_FIELDS\"}) as unknown as TypedDocumentString<Object_FieldsFragment, unknown>;\nexport const Move_Object_FieldsFragmentDoc = new TypedDocumentString(`\n fragment MOVE_OBJECT_FIELDS on MoveObject {\n address\n digest\n version\n objectBcs @include(if: $includeObjectBcs)\n contents {\n bcs @include(if: $includeContent)\n json @include(if: $includeJson)\n display @include(if: $includeDisplay) {\n output\n errors\n }\n type {\n repr\n }\n }\n owner {\n ...OBJECT_OWNER_FIELDS\n }\n previousTransaction @include(if: $includePreviousTransaction) {\n digest\n }\n}\n fragment OBJECT_OWNER_FIELDS on Owner {\n __typename\n ... on AddressOwner {\n address {\n address\n }\n }\n ... on ObjectOwner {\n address {\n address\n }\n }\n ... on Shared {\n initialSharedVersion\n }\n ... on ConsensusAddressOwner {\n startVersion\n address {\n address\n }\n }\n}`, {\"fragmentName\":\"MOVE_OBJECT_FIELDS\"}) as unknown as TypedDocumentString<Move_Object_FieldsFragment, unknown>;\nexport const Transaction_FieldsFragmentDoc = new TypedDocumentString(`\n fragment TRANSACTION_FIELDS on Transaction {\n digest\n transactionJson @include(if: $includeTransaction)\n transactionBcs @include(if: $includeBcs)\n signatures {\n signatureBytes\n }\n effects {\n status\n executionError {\n message\n abortCode\n identifier\n constant\n sourceLineNumber\n instructionOffset\n module {\n name\n package {\n address\n }\n }\n function {\n name\n }\n }\n epoch {\n epochId\n }\n effectsBcs @include(if: $includeEffects)\n effectsJson @include(if: $includeObjectTypes)\n objectChanges(first: 50) @include(if: $includeObjectTypes) {\n nodes {\n address\n outputState {\n asMoveObject {\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n balanceChangesJson @include(if: $includeBalanceChanges)\n events(first: 50) @include(if: $includeEvents) {\n pageInfo {\n hasNextPage\n }\n nodes {\n transactionModule {\n package {\n address\n }\n name\n }\n sender {\n address\n }\n contents {\n type {\n repr\n }\n bcs\n json\n }\n }\n }\n }\n}\n `, {\"fragmentName\":\"TRANSACTION_FIELDS\"}) as unknown as TypedDocumentString<Transaction_FieldsFragment, unknown>;\nexport const GetAllBalancesDocument = new TypedDocumentString(`\n query getAllBalances($owner: SuiAddress!, $limit: Int, $cursor: String) {\n address(address: $owner) {\n balances(first: $limit, after: $cursor) {\n pageInfo {\n hasNextPage\n endCursor\n }\n nodes {\n coinType {\n repr\n }\n totalBalance\n addressBalance\n }\n }\n }\n}\n `) as unknown as TypedDocumentString<GetAllBalancesQuery, GetAllBalancesQueryVariables>;\nexport const GetBalanceDocument = new TypedDocumentString(`\n query getBalance($owner: SuiAddress!, $coinType: String = \"0x2::sui::SUI\") {\n address(address: $owner) {\n balance(coinType: $coinType) {\n coinType {\n repr\n }\n totalBalance\n addressBalance\n }\n }\n}\n `) as unknown as TypedDocumentString<GetBalanceQuery, GetBalanceQueryVariables>;\nexport const GetChainIdentifierDocument = new TypedDocumentString(`\n query getChainIdentifier {\n checkpoint(sequenceNumber: 0) {\n digest\n }\n}\n `) as unknown as TypedDocumentString<GetChainIdentifierQuery, GetChainIdentifierQueryVariables>;\nexport const GetCoinMetadataDocument = new TypedDocumentString(`\n query getCoinMetadata($coinType: String!) {\n coinMetadata(coinType: $coinType) {\n address\n decimals\n name\n symbol\n description\n iconUrl\n }\n}\n `) as unknown as TypedDocumentString<GetCoinMetadataQuery, GetCoinMetadataQueryVariables>;\nexport const GetCoinsDocument = new TypedDocumentString(`\n query getCoins($owner: SuiAddress!, $first: Int, $cursor: String, $type: String = \"0x2::coin::Coin<0x2::sui::SUI>\") {\n address(address: $owner) {\n address\n objects(first: $first, after: $cursor, filter: {type: $type}) {\n pageInfo {\n hasNextPage\n endCursor\n }\n nodes {\n owner {\n ...OBJECT_OWNER_FIELDS\n }\n contents {\n json\n type {\n repr\n }\n }\n address\n version\n digest\n }\n }\n }\n}\n fragment OBJECT_OWNER_FIELDS on Owner {\n __typename\n ... on AddressOwner {\n address {\n address\n }\n }\n ... on ObjectOwner {\n address {\n address\n }\n }\n ... on Shared {\n initialSharedVersion\n }\n ... on ConsensusAddressOwner {\n startVersion\n address {\n address\n }\n }\n}`) as unknown as TypedDocumentString<GetCoinsQuery, GetCoinsQueryVariables>;\nexport const GetCurrentSystemStateDocument = new TypedDocumentString(`\n query getCurrentSystemState {\n epoch {\n epochId\n referenceGasPrice\n startTimestamp\n protocolConfigs {\n protocolVersion\n }\n systemState {\n json\n }\n }\n}\n `) as unknown as TypedDocumentString<GetCurrentSystemStateQuery, GetCurrentSystemStateQueryVariables>;\nexport const GetDynamicFieldsDocument = new TypedDocumentString(`\n query getDynamicFields($parentId: SuiAddress!, $first: Int, $cursor: String, $includeValue: Boolean = false) {\n address(address: $parentId) {\n dynamicFields(first: $first, after: $cursor) {\n pageInfo {\n hasNextPage\n endCursor\n }\n nodes {\n name {\n bcs\n type {\n repr\n }\n }\n value {\n __typename\n ... on MoveValue {\n bcs @include(if: $includeValue)\n type {\n repr\n }\n }\n ... on MoveObject {\n address\n contents {\n bcs @include(if: $includeValue)\n type {\n repr\n }\n }\n }\n }\n }\n }\n }\n}\n `) as unknown as TypedDocumentString<GetDynamicFieldsQuery, GetDynamicFieldsQueryVariables>;\nexport const GetMoveFunctionDocument = new TypedDocumentString(`\n query getMoveFunction($package: SuiAddress!, $module: String!, $function: String!) {\n package(address: $package) {\n module(name: $module) {\n function(name: $function) {\n name\n visibility\n isEntry\n typeParameters {\n constraints\n }\n parameters {\n signature\n }\n return {\n signature\n }\n }\n }\n }\n}\n `) as unknown as TypedDocumentString<GetMoveFunctionQuery, GetMoveFunctionQueryVariables>;\nexport const GetProtocolConfigDocument = new TypedDocumentString(`\n query getProtocolConfig {\n epoch {\n protocolConfigs {\n protocolVersion\n featureFlags {\n key\n value\n }\n configs {\n key\n value\n }\n }\n }\n}\n `) as unknown as TypedDocumentString<GetProtocolConfigQuery, GetProtocolConfigQueryVariables>;\nexport const GetReferenceGasPriceDocument = new TypedDocumentString(`\n query getReferenceGasPrice {\n epoch {\n referenceGasPrice\n }\n}\n `) as unknown as TypedDocumentString<GetReferenceGasPriceQuery, GetReferenceGasPriceQueryVariables>;\nexport const DefaultSuinsNameDocument = new TypedDocumentString(`\n query defaultSuinsName($address: SuiAddress!) {\n address(address: $address) {\n defaultNameRecord {\n domain\n }\n }\n}\n `) as unknown as TypedDocumentString<DefaultSuinsNameQuery, DefaultSuinsNameQueryVariables>;\nexport const GetOwnedObjectsDocument = new TypedDocumentString(`\n query getOwnedObjects($owner: SuiAddress!, $limit: Int, $cursor: String, $filter: ObjectFilter, $includeContent: Boolean = false, $includePreviousTransaction: Boolean = false, $includeObjectBcs: Boolean = false, $includeJson: Boolean = false, $includeDisplay: Boolean = false) {\n address(address: $owner) {\n objects(first: $limit, after: $cursor, filter: $filter) {\n pageInfo {\n hasNextPage\n endCursor\n }\n nodes {\n ...MOVE_OBJECT_FIELDS\n }\n }\n }\n}\n fragment MOVE_OBJECT_FIELDS on MoveObject {\n address\n digest\n version\n objectBcs @include(if: $includeObjectBcs)\n contents {\n bcs @include(if: $includeContent)\n json @include(if: $includeJson)\n display @include(if: $includeDisplay) {\n output\n errors\n }\n type {\n repr\n }\n }\n owner {\n ...OBJECT_OWNER_FIELDS\n }\n previousTransaction @include(if: $includePreviousTransaction) {\n digest\n }\n}\nfragment OBJECT_OWNER_FIELDS on Owner {\n __typename\n ... on AddressOwner {\n address {\n address\n }\n }\n ... on ObjectOwner {\n address {\n address\n }\n }\n ... on Shared {\n initialSharedVersion\n }\n ... on ConsensusAddressOwner {\n startVersion\n address {\n address\n }\n }\n}`) as unknown as TypedDocumentString<GetOwnedObjectsQuery, GetOwnedObjectsQueryVariables>;\nexport const MultiGetObjectsDocument = new TypedDocumentString(`\n query multiGetObjects($objectKeys: [ObjectKey!]!, $includeContent: Boolean = false, $includePreviousTransaction: Boolean = false, $includeObjectBcs: Boolean = false, $includeJson: Boolean = false, $includeDisplay: Boolean = false) {\n multiGetObjects(keys: $objectKeys) {\n ...OBJECT_FIELDS\n }\n}\n fragment OBJECT_FIELDS on Object {\n address\n digest\n version\n objectBcs @include(if: $includeObjectBcs)\n asMoveObject {\n contents {\n bcs @include(if: $includeContent)\n json @include(if: $includeJson)\n display @include(if: $includeDisplay) {\n output\n errors\n }\n type {\n repr\n }\n }\n }\n asMovePackage {\n __typename\n }\n owner {\n ...OBJECT_OWNER_FIELDS\n }\n previousTransaction @include(if: $includePreviousTransaction) {\n digest\n }\n}\nfragment OBJECT_OWNER_FIELDS on Owner {\n __typename\n ... on AddressOwner {\n address {\n address\n }\n }\n ... on ObjectOwner {\n address {\n address\n }\n }\n ... on Shared {\n initialSharedVersion\n }\n ... on ConsensusAddressOwner {\n startVersion\n address {\n address\n }\n }\n}`) as unknown as TypedDocumentString<MultiGetObjectsQuery, MultiGetObjectsQueryVariables>;\nexport const SimulateTransactionDocument = new TypedDocumentString(`\n query simulateTransaction($transaction: JSON!, $includeTransaction: Boolean = false, $includeEffects: Boolean = false, $includeEvents: Boolean = false, $includeBalanceChanges: Boolean = false, $includeObjectTypes: Boolean = false, $includeCommandResults: Boolean = false, $includeBcs: Boolean = false, $doGasSelection: Boolean = false, $checksEnabled: Boolean = true) {\n simulateTransaction(\n transaction: $transaction\n doGasSelection: $doGasSelection\n checksEnabled: $checksEnabled\n ) {\n effects {\n transaction {\n ...TRANSACTION_FIELDS\n }\n }\n outputs @include(if: $includeCommandResults) {\n returnValues {\n value {\n bcs\n }\n }\n mutatedReferences {\n value {\n bcs\n }\n }\n }\n }\n}\n fragment TRANSACTION_FIELDS on Transaction {\n digest\n transactionJson @include(if: $includeTransaction)\n transactionBcs @include(if: $includeBcs)\n signatures {\n signatureBytes\n }\n effects {\n status\n executionError {\n message\n abortCode\n identifier\n constant\n sourceLineNumber\n instructionOffset\n module {\n name\n package {\n address\n }\n }\n function {\n name\n }\n }\n epoch {\n epochId\n }\n effectsBcs @include(if: $includeEffects)\n effectsJson @include(if: $includeObjectTypes)\n objectChanges(first: 50) @include(if: $includeObjectTypes) {\n nodes {\n address\n outputState {\n asMoveObject {\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n balanceChangesJson @include(if: $includeBalanceChanges)\n events(first: 50) @include(if: $includeEvents) {\n pageInfo {\n hasNextPage\n }\n nodes {\n transactionModule {\n package {\n address\n }\n name\n }\n sender {\n address\n }\n contents {\n type {\n repr\n }\n bcs\n json\n }\n }\n }\n }\n}`) as unknown as TypedDocumentString<SimulateTransactionQuery, SimulateTransactionQueryVariables>;\nexport const ExecuteTransactionDocument = new TypedDocumentString(`\n mutation executeTransaction($transactionDataBcs: Base64!, $signatures: [Base64!]!, $includeTransaction: Boolean = false, $includeEffects: Boolean = false, $includeEvents: Boolean = false, $includeBalanceChanges: Boolean = false, $includeObjectTypes: Boolean = false, $includeBcs: Boolean = false) {\n executeTransaction(\n transactionDataBcs: $transactionDataBcs\n signatures: $signatures\n ) {\n effects {\n transaction {\n ...TRANSACTION_FIELDS\n }\n }\n }\n}\n fragment TRANSACTION_FIELDS on Transaction {\n digest\n transactionJson @include(if: $includeTransaction)\n transactionBcs @include(if: $includeBcs)\n signatures {\n signatureBytes\n }\n effects {\n status\n executionError {\n message\n abortCode\n identifier\n constant\n sourceLineNumber\n instructionOffset\n module {\n name\n package {\n address\n }\n }\n function {\n name\n }\n }\n epoch {\n epochId\n }\n effectsBcs @include(if: $includeEffects)\n effectsJson @include(if: $includeObjectTypes)\n objectChanges(first: 50) @include(if: $includeObjectTypes) {\n nodes {\n address\n outputState {\n asMoveObject {\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n balanceChangesJson @include(if: $includeBalanceChanges)\n events(first: 50) @include(if: $includeEvents) {\n pageInfo {\n hasNextPage\n }\n nodes {\n transactionModule {\n package {\n address\n }\n name\n }\n sender {\n address\n }\n contents {\n type {\n repr\n }\n bcs\n json\n }\n }\n }\n }\n}`) as unknown as TypedDocumentString<ExecuteTransactionMutation, ExecuteTransactionMutationVariables>;\nexport const GetTransactionBlockDocument = new TypedDocumentString(`\n query getTransactionBlock($digest: String!, $includeTransaction: Boolean = false, $includeEffects: Boolean = false, $includeEvents: Boolean = false, $includeBalanceChanges: Boolean = false, $includeObjectTypes: Boolean = false, $includeBcs: Boolean = false) {\n transaction(digest: $digest) {\n ...TRANSACTION_FIELDS\n }\n}\n fragment TRANSACTION_FIELDS on Transaction {\n digest\n transactionJson @include(if: $includeTransaction)\n transactionBcs @include(if: $includeBcs)\n signatures {\n signatureBytes\n }\n effects {\n status\n executionError {\n message\n abortCode\n identifier\n constant\n sourceLineNumber\n instructionOffset\n module {\n name\n package {\n address\n }\n }\n function {\n name\n }\n }\n epoch {\n epochId\n }\n effectsBcs @include(if: $includeEffects)\n effectsJson @include(if: $includeObjectTypes)\n objectChanges(first: 50) @include(if: $includeObjectTypes) {\n nodes {\n address\n outputState {\n asMoveObject {\n contents {\n type {\n repr\n }\n }\n }\n }\n }\n }\n balanceChangesJson @include(if: $includeBalanceChanges)\n events(first: 50) @include(if: $includeEvents) {\n pageInfo {\n hasNextPage\n }\n nodes {\n transactionModule {\n package {\n address\n }\n name\n }\n sender {\n address\n }\n contents {\n type {\n repr\n }\n bcs\n json\n }\n }\n }\n }\n}`) as unknown as TypedDocumentString<GetTransactionBlockQuery, GetTransactionBlockQueryVariables>;\nexport const ResolveTransactionDocument = new TypedDocumentString(`\n query resolveTransaction($transaction: JSON!, $doGasSelection: Boolean = true) {\n simulateTransaction(transaction: $transaction, doGasSelection: $doGasSelection) {\n effects {\n transaction {\n transactionBcs\n effects {\n status\n executionError {\n message\n abortCode\n identifier\n constant\n sourceLineNumber\n instructionOffset\n module {\n name\n package {\n address\n }\n }\n function {\n name\n }\n }\n }\n }\n }\n }\n}\n `) as unknown as TypedDocumentString<ResolveTransactionQuery, ResolveTransactionQueryVariables>;\nexport const VerifyZkLoginSignatureDocument = new TypedDocumentString(`\n query verifyZkLoginSignature($bytes: Base64!, $signature: Base64!, $intentScope: ZkLoginIntentScope!, $author: SuiAddress!) {\n verifyZkLoginSignature(\n bytes: $bytes\n signature: $signature\n intentScope: $intentScope\n author: $author\n ) {\n success\n }\n}\n `) as unknown as TypedDocumentString<VerifyZkLoginSignatureQuery, VerifyZkLoginSignatureQueryVariables>;","// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { CoreClient } from '../client/core.js';\nimport type { SuiClientTypes } from '../client/types.js';\nimport { SUI_TYPE_ARG } from '../utils/constants.js';\nimport type { GraphQLQueryOptions, SuiGraphQLClient } from './client.js';\nimport type {\n\tObject_Owner_FieldsFragment,\n\tTransaction_FieldsFragment,\n} from './generated/queries.js';\n\ntype GraphQLExecutionError = NonNullable<\n\tNonNullable<Transaction_FieldsFragment['effects']>['executionError']\n>;\nimport {\n\tDefaultSuinsNameDocument,\n\tExecuteTransactionDocument,\n\tExecutionStatus,\n\tGetAllBalancesDocument,\n\tGetBalanceDocument,\n\tGetChainIdentifierDocument,\n\tGetCoinMetadataDocument,\n\tGetCoinsDocument,\n\tGetCurrentSystemStateDocument,\n\tGetMoveFunctionDocument,\n\tGetProtocolConfigDocument,\n\tGetOwnedObjectsDocument,\n\tGetReferenceGasPriceDocument,\n\tGetTransactionBlockDocument,\n\tMultiGetObjectsDocument,\n\tResolveTransactionDocument,\n\tSimulateTransactionDocument,\n\tVerifyZkLoginSignatureDocument,\n\tZkLoginIntentScope,\n} from './generated/queries.js';\nimport { ObjectError, SimulationError } from '../client/errors.js';\nimport { chunk, fromBase64, toBase64 } from '@mysten/utils';\nimport { normalizeSuiAddress } from '../utils/sui-types.js';\nimport { formatMoveAbortMessage, parseTransactionEffectsBcs } from '../client/utils.js';\nimport type { OpenMoveTypeSignatureBody, OpenMoveTypeSignature } from './types.js';\nimport {\n\ttransactionDataToGrpcTransaction,\n\ttransactionToGrpcJson,\n\tgrpcTransactionToTransactionData,\n} from '../client/transaction-resolver.js';\nimport { BalanceChange as BalanceChangeType } from '../grpc/proto/sui/rpc/v2/balance_change.js';\nimport { TransactionEffects as TransactionEffectsType } from '../grpc/proto/sui/rpc/v2/effects.js';\nimport { Transaction as GrpcTransactionType } from '../grpc/proto/sui/rpc/v2/transaction.js';\nimport { TransactionDataBuilder } from '../transactions/TransactionData.js';\nimport type { BuildTransactionOptions } from '../transactions/index.js';\n\nexport class GraphQLCoreClient extends CoreClient {\n\t#graphqlClient: SuiGraphQLClient;\n\n\tconstructor({\n\t\tgraphqlClient,\n\t\tmvr,\n\t}: {\n\t\tgraphqlClient: SuiGraphQLClient;\n\t\tmvr?: SuiClientTypes.MvrOptions;\n\t}) {\n\t\tsuper({ network: graphqlClient.network, base: graphqlClient, mvr });\n\t\tthis.#graphqlClient = graphqlClient;\n\t}\n\n\tasync #graphqlQuery<\n\t\tResult = Record<string, unknown>,\n\t\tVariables = Record<string, unknown>,\n\t\tData = Result,\n\t>(\n\t\toptions: GraphQLQueryOptions<Result, Variables>,\n\t\tgetData?: (result: Result) => Data,\n\t): Promise<NonNullable<Data>> {\n\t\tconst { data, errors } = await this.#graphqlClient.query(options);\n\n\t\thandleGraphQLErrors(errors);\n\n\t\tconst extractedData = data && (getData ? getData(data) : data);\n\n\t\tif (extractedData == null) {\n\t\t\tthrow new Error('Missing response data');\n\t\t}\n\n\t\treturn extractedData as NonNullable<Data>;\n\t}\n\n\tasync getObjects<Include extends SuiClientTypes.ObjectInclude = {}>(\n\t\toptions: SuiClientTypes.GetObjectsOptions<Include>,\n\t): Promise<SuiClientTypes.GetObjectsResponse<Include>> {\n\t\tconst batches = chunk(options.objectIds, 50);\n\t\tconst results: SuiClientTypes.GetObjectsResponse<Include>['objects'] = [];\n\n\t\tfor (const batch of batches) {\n\t\t\tconst page = await this.#graphqlQuery(\n\t\t\t\t{\n\t\t\t\t\tquery: MultiGetObjectsDocument,\n\t\t\t\t\tvariables: {\n\t\t\t\t\t\tobjectKeys: batch.map((address) => ({ address })),\n\t\t\t\t\t\tincludeContent: options.include?.content ?? false,\n\t\t\t\t\t\tincludePreviousTransaction: options.include?.previousTransaction ?? false,\n\t\t\t\t\t\tincludeObjectBcs: options.include?.objectBcs ?? false,\n\t\t\t\t\t\tincludeJson: options.include?.json ?? false,\n\t\t\t\t\t\tincludeDisplay: options.include?.display ?? false,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t(result) => result.multiGetObjects,\n\t\t\t);\n\t\t\tresults.push(\n\t\t\t\t...batch\n\t\t\t\t\t.map((id) => normalizeSuiAddress(id))\n\t\t\t\t\t.map(\n\t\t\t\t\t\t(id) =>\n\t\t\t\t\t\t\tpage.find((obj) => obj?.address === id) ??\n\t\t\t\t\t\t\tnew ObjectError('notFound', `Object ${id} not found`),\n\t\t\t\t\t)\n\t\t\t\t\t.map((obj) => {\n\t\t\t\t\t\tif (obj instanceof ObjectError) {\n\t\t\t\t\t\t\treturn obj;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst bcsContent = obj.asMoveObject?.contents?.bcs\n\t\t\t\t\t\t\t? fromBase64(obj.asMoveObject.contents.bcs)\n\t\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\t\tconst objectBcs = obj.objectBcs ? fromBase64(obj.objectBcs) : undefined;\n\n\t\t\t\t\t\t// Determine object type: package or Move object\n\t\t\t\t\t\t// GraphQL already returns normalized struct tags\n\t\t\t\t\t\tlet type: string;\n\t\t\t\t\t\tif (obj.asMovePackage) {\n\t\t\t\t\t\t\ttype = 'package';\n\t\t\t\t\t\t} else if (obj.asMoveObject?.contents?.type?.repr) {\n\t\t\t\t\t\t\ttype = obj.asMoveObject.contents.type.repr;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttype = '';\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst jsonContent = options.include?.json\n\t\t\t\t\t\t\t? obj.asMoveObject?.contents?.json\n\t\t\t\t\t\t\t\t? (obj.asMoveObject.contents.json as Record<string, unknown>)\n\t\t\t\t\t\t\t\t: null\n\t\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\t\tconst displayData = mapDisplay(\n\t\t\t\t\t\t\toptions.include?.display,\n\t\t\t\t\t\t\tobj.asMoveObject?.contents?.display,\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tobjectId: obj.address,\n\t\t\t\t\t\t\tversion: obj.version?.toString()!,\n\t\t\t\t\t\t\tdigest: obj.digest!,\n\t\t\t\t\t\t\towner: mapOwner(obj.owner!),\n\t\t\t\t\t\t\ttype,\n\t\t\t\t\t\t\tcontent: bcsContent as SuiClientTypes.Object<Include>['content'],\n\t\t\t\t\t\t\tpreviousTransaction: (obj.previousTransaction?.digest ??\n\t\t\t\t\t\t\t\tundefined) as SuiClientTypes.Object<Include>['previousTransaction'],\n\t\t\t\t\t\t\tobjectBcs: objectBcs as SuiClientTypes.Object<Include>['objectBcs'],\n\t\t\t\t\t\t\tjson: jsonContent as SuiClientTypes.Object<Include>['json'],\n\t\t\t\t\t\t\tdisplay: displayData as SuiClientTypes.Object<Include>['display'],\n\t\t\t\t\t\t};\n\t\t\t\t\t}),\n\t\t\t);\n\t\t}\n\n\t\treturn {\n\t\t\tobjects: results,\n\t\t};\n\t}\n\tasync listOwnedObjects<Include extends SuiClientTypes.ObjectInclude = {}>(\n\t\toptions: SuiClientTypes.ListOwnedObjectsOptions<Include>,\n\t): Promise<SuiClientTypes.ListOwnedObjectsResponse<Include>> {\n\t\tconst objects = await this.#graphqlQuery(\n\t\t\t{\n\t\t\t\tquery: GetOwnedObjectsDocument,\n\t\t\t\tvariables: {\n\t\t\t\t\towner: options.owner,\n\t\t\t\t\tlimit: options.limit,\n\t\t\t\t\tcursor: options.cursor,\n\t\t\t\t\tfilter: options.type\n\t\t\t\t\t\t? { type: (await this.mvr.resolveType({ type: options.type })).type }\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\tincludeContent: options.include?.content ?? false,\n\t\t\t\t\tincludePreviousTransaction: options.include?.previousTransaction ?? false,\n\t\t\t\t\tincludeObjectBcs: options.include?.objectBcs ?? false,\n\t\t\t\t\tincludeJson: options.include?.json ?? false,\n\t\t\t\t\tincludeDisplay: options.include?.display ?? false,\n\t\t\t\t},\n\t\t\t},\n\t\t\t(result) => result.address?.objects,\n\t\t);\n\n\t\treturn {\n\t\t\tobjects: objects.nodes.map(\n\t\t\t\t(obj): SuiClientTypes.Object<Include> => ({\n\t\t\t\t\tobjectId: obj.address,\n\t\t\t\t\tversion: obj.version?.toString()!,\n\t\t\t\t\tdigest: obj.digest!,\n\t\t\t\t\towner: mapOwner(obj.owner!),\n\t\t\t\t\ttype: obj.contents?.type?.repr!,\n\t\t\t\t\tcontent: (obj.contents?.bcs\n\t\t\t\t\t\t? fromBase64(obj.contents.bcs)\n\t\t\t\t\t\t: undefined) as SuiClientTypes.Object<Include>['content'],\n\t\t\t\t\tpreviousTransaction: (obj.previousTransaction?.digest ??\n\t\t\t\t\t\tundefined) as SuiClientTypes.Object<Include>['previousTransaction'],\n\t\t\t\t\tobjectBcs: (obj.objectBcs\n\t\t\t\t\t\t? fromBase64(obj.objectBcs)\n\t\t\t\t\t\t: undefined) as SuiClientTypes.Object<Include>['objectBcs'],\n\t\t\t\t\tjson: (options.include?.json\n\t\t\t\t\t\t? obj.contents?.json\n\t\t\t\t\t\t\t? (obj.contents.json as Record<string, unknown>)\n\t\t\t\t\t\t\t: null\n\t\t\t\t\t\t: undefined) as SuiClientTypes.Object<Include>['json'],\n\t\t\t\t\tdisplay: mapDisplay(\n\t\t\t\t\t\toptions.include?.display,\n\t\t\t\t\t\tobj.contents?.display,\n\t\t\t\t\t) as SuiClientTypes.Object<Include>['display'],\n\t\t\t\t}),\n\t\t\t),\n\t\t\thasNextPage: objects.pageInfo.hasNextPage,\n\t\t\tcursor: objects.pageInfo.endCursor ?? null,\n\t\t};\n\t}\n\tasync listCoins(\n\t\toptions: SuiClientTypes.ListCoinsOptions,\n\t): Promise<SuiClientTypes.ListCoinsResponse> {\n\t\tconst coinType = options.coinType ?? SUI_TYPE_ARG;\n\t\tconst coins = await this.#graphqlQuery(\n\t\t\t{\n\t\t\t\tquery: GetCoinsDocument,\n\t\t\t\tvariables: {\n\t\t\t\t\towner: options.owner,\n\t\t\t\t\tcursor: options.cursor,\n\t\t\t\t\tfirst: options.limit,\n\t\t\t\t\ttype: `0x2::coin::Coin<${(await this.mvr.resolveType({ type: coinType })).type}>`,\n\t\t\t\t},\n\t\t\t},\n\t\t\t(result) => result.address?.objects,\n\t\t);\n\n\t\treturn {\n\t\t\tcursor: coins.pageInfo.endCursor ?? null,\n\t\t\thasNextPage: coins.pageInfo.hasNextPage,\n\t\t\tobjects: coins.nodes.map(\n\t\t\t\t(coin): SuiClientTypes.Coin => ({\n\t\t\t\t\tobjectId: coin.address,\n\t\t\t\t\tversion: coin.version?.toString()!,\n\t\t\t\t\tdigest: coin.digest!,\n\t\t\t\t\towner: mapOwner(coin.owner!),\n\t\t\t\t\ttype: coin.contents?.type?.repr!,\n\t\t\t\t\tbalance: (coin.contents?.json as { balance: string })?.balance,\n\t\t\t\t}),\n\t\t\t),\n\t\t};\n\t}\n\n\tasync getBalance(\n\t\toptions: SuiClientTypes.GetBalanceOptions,\n\t): Promise<SuiClientTypes.GetBalanceResponse> {\n\t\tconst coinType = options.coinType ?? SUI_TYPE_ARG;\n\t\tconst result = await this.#graphqlQuery(\n\t\t\t{\n\t\t\t\tquery: GetBalanceDocument,\n\t\t\t\tvariables: {\n\t\t\t\t\towner: options.owner,\n\t\t\t\t\tcoinType: (await this.mvr.resolveType({ type: coinType })).type,\n\t\t\t\t},\n\t\t\t},\n\t\t\t(result) => result.address?.balance,\n\t\t);\n\n\t\tconst addressBalance = BigInt(result.addressBalance ?? '0');\n\t\tconst coinBalance = BigInt(result.totalBalance ?? '0') - addressBalance;\n\n\t\treturn {\n\t\t\tbalance: {\n\t\t\t\tcoinType: result.coinType?.repr ?? coinType,\n\t\t\t\tbalance: result.totalBalance ?? '0',\n\t\t\t\tcoinBalance: coinBalance.toString(),\n\t\t\t\taddressBalance: addressBalance.toString(),\n\t\t\t},\n\t\t};\n\t}\n\tasync getCoinMetadata(\n\t\toptions: SuiClientTypes.GetCoinMetadataOptions,\n\t): Promise<SuiClientTypes.GetCoinMetadataResponse> {\n\t\tconst coinType = (await this.mvr.resolveType({ type: options.coinType })).type;\n\n\t\tconst { data, errors } = await this.#graphqlClient.query({\n\t\t\tquery: GetCoinMetadataDocument,\n\t\t\tvariables: {\n\t\t\t\tcoinType,\n\t\t\t},\n\t\t});\n\n\t\thandleGraphQLErrors(errors);\n\n\t\tif (!data?.coinMetadata) {\n\t\t\treturn { coinMetadata: null };\n\t\t}\n\n\t\treturn {\n\t\t\tcoinMetadata: {\n\t\t\t\tid: data.coinMetadata.address!,\n\t\t\t\tdecimals: data.coinMetadata.decimals!,\n\t\t\t\tname: data.coinMetadata.name!,\n\t\t\t\tsymbol: data.coinMetadata.symbol!,\n\t\t\t\tdescription: data.coinMetadata.description!,\n\t\t\t\ticonUrl: data.coinMetadata.iconUrl ?? null,\n\t\t\t},\n\t\t};\n\t}\n\n\tasync listBalances(\n\t\toptions: SuiClientTypes.ListBalancesOptions,\n\t): Promise<SuiClientTypes.ListBalancesResponse> {\n\t\tconst balances = await this.#graphqlQuery(\n\t\t\t{\n\t\t\t\tquery: GetAllBalancesDocument,\n\t\t\t\tvariables: { owner: options.owner },\n\t\t\t},\n\t\t\t(result) => result.address?.balances,\n\t\t);\n\n\t\treturn {\n\t\t\tcursor: balances.pageInfo.endCursor ?? null,\n\t\t\thasNextPage: balances.pageInfo.hasNextPage,\n\t\t\tbalances: balances.nodes.map((balance) => {\n\t\t\t\tconst addressBalance = BigInt(balance.addressBalance ?? '0');\n\t\t\t\tconst coinBalance = BigInt(balance.totalBalance ?? '0') - addressBalance;\n\t\t\t\treturn {\n\t\t\t\t\tcoinType: balance.coinType?.repr!,\n\t\t\t\t\tbalance: balance.totalBalance!,\n\t\t\t\t\tcoinBalance: coinBalance.toString(),\n\t\t\t\t\taddressBalance: addressBalance.toString(),\n\t\t\t\t};\n\t\t\t}),\n\t\t};\n\t}\n\tasync getTransaction<Include extends SuiClientTypes.TransactionInclude = {}>(\n\t\toptions: SuiClientTypes.GetTransactionOptions<Include>,\n\t): Promise<SuiClientTypes.TransactionResult<Include>> {\n\t\tconst result = await this.#graphqlQuery(\n\t\t\t{\n\t\t\t\tquery: GetTransactionBlockDocument,\n\t\t\t\tvariables: {\n\t\t\t\t\tdigest: options.digest,\n\t\t\t\t\tincludeTransaction: options.include?.transaction ?? false,\n\t\t\t\t\tincludeEffects: options.include?.effects ?? false,\n\t\t\t\t\tincludeEvents: options.include?.events ?? false,\n\t\t\t\t\tincludeBalanceChanges: options.include?.balanceChanges ?? false,\n\t\t\t\t\tincludeObjectTypes: options.include?.objectTypes ?? false,\n\t\t\t\t\tincludeBcs: options.include?.bcs ?? false,\n\t\t\t\t},\n\t\t\t},\n\t\t\t(result) => result.transaction,\n\t\t);\n\n\t\treturn parseTransaction(result, options.include);\n\t}\n\tasync executeTransaction<Include extends SuiClientTypes.TransactionInclude = {}>(\n\t\toptions: SuiClientTypes.ExecuteTransactionOptions<Include>,\n\t): Promise<SuiClientTypes.TransactionResult<Include>> {\n\t\tconst result = await this.#graphqlQuery(\n\t\t\t{\n\t\t\t\tquery: ExecuteTransactionDocument,\n\t\t\t\tvariables: {\n\t\t\t\t\ttransactionDataBcs: toBase64(options.transaction),\n\t\t\t\t\tsignatures: options.signatures,\n\t\t\t\t\tincludeTransaction: options.include?.transaction ?? false,\n\t\t\t\t\tincludeEffects: options.include?.effects ?? false,\n\t\t\t\t\tincludeEvents: options.include?.events ?? false,\n\t\t\t\t\tincludeBalanceChanges: options.include?.balanceChanges ?? false,\n\t\t\t\t\tincludeObjectTypes: options.include?.objectTypes ?? false,\n\t\t\t\t\tincludeBcs: options.include?.bcs ?? false,\n\t\t\t\t},\n\t\t\t},\n\t\t\t(result) => result.executeTransaction,\n\t\t);\n\n\t\treturn parseTransaction(result.effects?.transaction!, options.include);\n\t}\n\tasync simulateTransaction<Include extends SuiClientTypes.SimulateTransactionInclude = {}>(\n\t\toptions: SuiClientTypes.SimulateTransactionOptions<Include>,\n\t): Promise<SuiClientTypes.SimulateTransactionResult<Include>> {\n\t\tif (!(options.transaction instanceof Uint8Array)) {\n\t\t\tawait options.transaction.prepareForSerialization({ client: this });\n\t\t}\n\n\t\tconst result = await this.#graphqlQuery(\n\t\t\t{\n\t\t\t\tquery: SimulateTransactionDocument,\n\t\t\t\tvariables: {\n\t\t\t\t\ttransaction:\n\t\t\t\t\t\toptions.transaction instanceof Uint8Array\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tbcs: {\n\t\t\t\t\t\t\t\t\t\tvalue: toBase64(options.transaction),\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: transactionToGrpcJson(options.transaction),\n\t\t\t\t\tincludeTransaction: options.include?.transaction ?? false,\n\t\t\t\t\tincludeEffects: options.include?.effects ?? false,\n\t\t\t\t\tincludeEvents: options.include?.events ?? false,\n\t\t\t\t\tincludeBalanceChanges: options.include?.balanceChanges ?? false,\n\t\t\t\t\tincludeObjectTypes: options.include?.objectTypes ?? false,\n\t\t\t\t\tincludeCommandResults: options.include?.commandResults ?? false,\n\t\t\t\t\tincludeBcs: options.include?.bcs ?? false,\n\t\t\t\t\tchecksEnabled: options.checksEnabled ?? true,\n\t\t\t\t},\n\t\t\t},\n\t\t\t(result) => result.simulateTransaction,\n\t\t);\n\n\t\tconst transactionResult = parseTransaction(result.effects?.transaction!, options.include);\n\n\t\tconst commandResults =\n\t\t\toptions.include?.commandResults && result.outputs\n\t\t\t\t? result.outputs.map((output) => ({\n\t\t\t\t\t\treturnValues: (output.returnValues ?? []).map((rv) => ({\n\t\t\t\t\t\t\tbcs: rv.value?.bcs ? fromBase64(rv.value.bcs) : null,\n\t\t\t\t\t\t})),\n\t\t\t\t\t\tmutatedReferences: (output.mutatedReferences ?? []).map((mr) => ({\n\t\t\t\t\t\t\tbcs: mr.value?.bcs ? fromBase64(mr.value.bcs) : null,\n\t\t\t\t\t\t})),\n\t\t\t\t\t}))\n\t\t\t\t: undefined;\n\n\t\tif (transactionResult.$kind === 'Transaction') {\n\t\t\treturn {\n\t\t\t\t$kind: 'Transaction',\n\t\t\t\tTransaction: transactionResult.Transaction,\n\t\t\t\tcommandResults:\n\t\t\t\t\tcommandResults as SuiClientTypes.SimulateTransactionResult<Include>['commandResults'],\n\t\t\t};\n\t\t} else {\n\t\t\treturn {\n\t\t\t\t$kind: 'FailedTransaction',\n\t\t\t\tFailedTransaction: transactionResult.FailedTransaction,\n\t\t\t\tcommandResults:\n\t\t\t\t\tcommandResults as SuiClientTypes.SimulateTransactionResult<Include>['commandResults'],\n\t\t\t};\n\t\t}\n\t}\n\tasync getReferenceGasPrice(): Promise<SuiClientTypes.GetReferenceGasPriceResponse> {\n\t\tconst result = await this.#graphqlQuery(\n\t\t\t{\n\t\t\t\tquery: GetReferenceGasPriceDocument,\n\t\t\t},\n\t\t\t(result) => result.epoch?.referenceGasPrice,\n\t\t);\n\n\t\treturn {\n\t\t\treferenceGasPrice: result ?? '',\n\t\t};\n\t}\n\n\tasync getProtocolConfig(): Promise<SuiClientTypes.GetProtocolConfigResponse> {\n\t\tconst result = await this.#graphqlQuery(\n\t\t\t{\n\t\t\t\tquery: GetProtocolConfigDocument,\n\t\t\t},\n\t\t\t(result) => result.epoch?.protocolConfigs,\n\t\t);\n\n\t\tconst featureFlags: Record<string, boolean> = {};\n\t\tfor (const flag of result?.featureFlags ?? []) {\n\t\t\tfeatureFlags[flag.key] = flag.value;\n\t\t}\n\t\tconst attributes: Record<string, string | null> = {};\n\t\tfor (const config of result?.configs ?? []) {\n\t\t\tattributes[config.key] = config.value ?? null;\n\t\t}\n\n\t\treturn {\n\t\t\tprotocolConfig: {\n\t\t\t\tprotocolVersion: result?.protocolVersion?.toString() ?? (null as never),\n\t\t\t\tfeatureFlags,\n\t\t\t\tattributes,\n\t\t\t},\n\t\t};\n\t}\n\n\tasync getCurrentSystemState(): Promise<SuiClientTypes.GetCurrentSystemStateResponse> {\n\t\tconst result = await this.#graphqlQuery(\n\t\t\t{\n\t\t\t\tquery: GetCurrentSystemStateDocument,\n\t\t\t},\n\t\t\t(result) => result.epoch,\n\t\t);\n\n\t\tif (!result) {\n\t\t\tthrow new Error('Epoch data not found in response');\n\t\t}\n\n\t\tconst startMs = result.startTimestamp\n\t\t\t? new Date(result.startTimestamp).getTime().toString()\n\t\t\t: (null as never);\n\n\t\t// Parse the system state JSON from the MoveValue\n\t\tconst systemStateJson = result.systemState?.json as\n\t\t\t| {\n\t\t\t\t\tsystem_state_version?: string | number;\n\t\t\t\t\tsafe_mode?: boolean;\n\t\t\t\t\tsafe_mode_storage_rewards?: string;\n\t\t\t\t\tsafe_mode_computation_rewards?: string;\n\t\t\t\t\tsafe_mode_storage_rebates?: string | number;\n\t\t\t\t\tsafe_mode_non_refundable_storage_fee?: string | number;\n\t\t\t\t\tparameters?: {\n\t\t\t\t\t\tepoch_duration_ms?: string | number;\n\t\t\t\t\t\tstake_subsidy_start_epoch?: string | number;\n\t\t\t\t\t\tmax_validator_count?: string | number;\n\t\t\t\t\t\tmin_validator_joining_stake?: string | number;\n\t\t\t\t\t\tvalidator_low_stake_threshold?: string | number;\n\t\t\t\t\t\tvalidator_low_stake_grace_period?: string | number;\n\t\t\t\t\t};\n\t\t\t\t\tstorage_fund?: {\n\t\t\t\t\t\ttotal_object_storage_rebates?: string;\n\t\t\t\t\t\tnon_refundable_balance?: string;\n\t\t\t\t\t};\n\t\t\t\t\tstake_subsidy?: {\n\t\t\t\t\t\tbalance?: string;\n\t\t\t\t\t\tdistribution_counter?: string | number;\n\t\t\t\t\t\tcurrent_distribution_amount?: string | number;\n\t\t\t\t\t\tstake_subsidy_period_length?: string | number;\n\t\t\t\t\t\tstake_subsidy_decrease_rate?: number;\n\t\t\t\t\t};\n\t\t\t }\n\t\t\t| undefined;\n\n\t\treturn {\n\t\t\tsystemState: {\n\t\t\t\tsystemStateVersion: systemStateJson?.system_state_version?.toString() ?? (null as never),\n\t\t\t\tepoch: result.epochId?.toString() ?? (null as never),\n\t\t\t\tprotocolVersion: result.protocolConfigs?.protocolVersion?.toString() ?? (null as never),\n\t\t\t\treferenceGasPrice: result.referenceGasPrice ?? (null as never),\n\t\t\t\tepochStartTimestampMs: startMs,\n\t\t\t\tsafeMode: systemStateJson?.safe_mode ?? false,\n\t\t\t\tsafeModeStorageRewards: systemStateJson?.safe_mode_storage_rewards ?? (null as never),\n\t\t\t\tsafeModeComputationRewards:\n\t\t\t\t\tsystemStateJson?.safe_mode_computation_rewards ?? (null as never),\n\t\t\t\tsafeModeStorageRebates:\n\t\t\t\t\tsystemStateJson?.safe_mode_storage_rebates?.toString() ?? (null as never),\n\t\t\t\tsafeModeNonRefundableStorageFee:\n\t\t\t\t\tsystemStateJson?.safe_mode_non_refundable_storage_fee?.toString() ?? (null as never),\n\t\t\t\tparameters: {\n\t\t\t\t\tepochDurationMs:\n\t\t\t\t\t\tsystemStateJson?.parameters?.epoch_duration_ms?.toString() ?? (null as never),\n\t\t\t\t\tstakeSubsidyStartEpoch:\n\t\t\t\t\t\tsystemStateJson?.parameters?.stake_subsidy_start_epoch?.toString() ?? (null as never),\n\t\t\t\t\tmaxValidatorCount:\n\t\t\t\t\t\tsystemStateJson?.parameters?.max_validator_count?.toString() ?? (null as never),\n\t\t\t\t\tminValidatorJoiningStake:\n\t\t\t\t\t\tsystemStateJson?.parameters?.min_validator_joining_stake?.toString() ?? (null as never),\n\t\t\t\t\tvalidatorLowStakeThreshold:\n\t\t\t\t\t\tsystemStateJson?.parameters?.validator_low_stake_threshold?.toString() ??\n\t\t\t\t\t\t(null as never),\n\t\t\t\t\tvalidatorLowStakeGracePeriod:\n\t\t\t\t\t\tsystemStateJson?.parameters?.validator_low_stake_grace_period?.toString() ??\n\t\t\t\t\t\t(null as never),\n\t\t\t\t},\n\t\t\t\tstorageFund: {\n\t\t\t\t\ttotalObjectStorageRebates:\n\t\t\t\t\t\tsystemStateJson?.storage_fund?.total_object_storage_rebates ?? (null as never),\n\t\t\t\t\tnonRefundableBalance:\n\t\t\t\t\t\tsystemStateJson?.storage_fund?.non_refundable_balance ?? (null as never),\n\t\t\t\t},\n\t\t\t\tstakeSubsidy: {\n\t\t\t\t\tbalance: systemStateJson?.stake_subsidy?.balance ?? (null as never),\n\t\t\t\t\tdistributionCounter:\n\t\t\t\t\t\tsystemStateJson?.stake_subsidy?.distribution_counter?.toString() ?? (null as never),\n\t\t\t\t\tcurrentDistributionAmount:\n\t\t\t\t\t\tsystemStateJson?.stake_subsidy?.current_distribution_amount?.toString() ??\n\t\t\t\t\t\t(null as never),\n\t\t\t\t\tstakeSubsidyPeriodLength:\n\t\t\t\t\t\tsystemStateJson?.stake_subsidy?.stake_subsidy_period_length?.toString() ??\n\t\t\t\t\t\t(null as never),\n\t\t\t\t\tstakeSubsidyDecreaseRate:\n\t\t\t\t\t\tsystemStateJson?.stake_subsidy?.stake_subsidy_decrease_rate ?? (null as never),\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\n\tasync listDynamicFields(\n\t\toptions: SuiClientTypes.ListDynamicFieldsOptions,\n\t): Promise<SuiClientTypes.ListDynamicFieldsResponse> {\n\t\treturn this.#graphqlClient.listDynamicFields(options);\n\t}\n\n\tasync verifyZkLoginSignature(\n\t\toptions: SuiClientTypes.VerifyZkLoginSignatureOptions,\n\t): Promise<SuiClientTypes.ZkLoginVerifyResponse> {\n\t\tconst intentScope =\n\t\t\toptions.intentScope === 'TransactionData'\n\t\t\t\t? ZkLoginIntentScope.TransactionData\n\t\t\t\t: ZkLoginIntentScope.PersonalMessage;\n\n\t\tconst { data } = await this.#graphqlClient.query({\n\t\t\tquery: VerifyZkLoginSignatureDocument,\n\t\t\tvariables: {\n\t\t\t\tbytes: options.bytes,\n\t\t\t\tsignature: options.signature,\n\t\t\t\tintentScope,\n\t\t\t\tauthor: options.address,\n\t\t\t},\n\t\t});\n\n\t\treturn {\n\t\t\tsuccess: data?.verifyZkLoginSignature?.success ?? false,\n\t\t\terrors: [],\n\t\t};\n\t}\n\n\tasync defaultNameServiceName(\n\t\toptions: SuiClientTypes.DefaultNameServiceNameOptions,\n\t): Promise<SuiClientTypes.DefaultNameServiceNameResponse> {\n\t\tconst name = await this.#graphqlQuery(\n\t\t\t{\n\t\t\t\tquery: DefaultSuinsNameDocument,\n\t\t\t\tsignal: options.signal,\n\t\t\t\tvariables: {\n\t\t\t\t\taddress: options.address,\n\t\t\t\t},\n\t\t\t},\n\t\t\t(result) => result.address?.defaultNameRecord?.domain ?? null,\n\t\t);\n\n\t\treturn {\n\t\t\tdata: { name: name },\n\t\t};\n\t}\n\n\tasync getMoveFunction(\n\t\toptions: SuiClientTypes.GetMoveFunctionOptions,\n\t): Promise<SuiClientTypes.GetMoveFunctionResponse> {\n\t\tconst moveFunction = await this.#graphqlQuery(\n\t\t\t{\n\t\t\t\tquery: GetMoveFunctionDocument,\n\t\t\t\tvariables: {\n\t\t\t\t\tpackage: (await this.mvr.resolvePackage({ package: options.packageId })).package,\n\t\t\t\t\tmodule: options.moduleName,\n\t\t\t\t\tfunction: options.name,\n\t\t\t\t},\n\t\t\t},\n\t\t\t(result) => result.package?.module?.function,\n\t\t);\n\n\t\tlet visibility: 'public' | 'private' | 'friend' | 'unknown' = 'unknown';\n\n\t\tswitch (moveFunction.visibility) {\n\t\t\tcase 'PUBLIC':\n\t\t\t\tvisibility = 'public';\n\t\t\t\tbreak;\n\t\t\tcase 'PRIVATE':\n\t\t\t\tvisibility = 'private';\n\t\t\t\tbreak;\n\t\t\tcase 'FRIEND':\n\t\t\t\tvisibility = 'friend';\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn {\n\t\t\tfunction: {\n\t\t\t\tpackageId: normalizeSuiAddress(options.packageId),\n\t\t\t\tmoduleName: options.moduleName,\n\t\t\t\tname: moveFunction.name,\n\t\t\t\tvisibility,\n\t\t\t\tisEntry: moveFunction.isEntry ?? false,\n\t\t\t\ttypeParameters:\n\t\t\t\t\tmoveFunction.typeParameters?.map(({ constraints }) => ({\n\t\t\t\t\t\tisPhantom: false,\n\t\t\t\t\t\tconstraints:\n\t\t\t\t\t\t\tconstraints.map((constraint) => {\n\t\t\t\t\t\t\t\tswitch (constraint) {\n\t\t\t\t\t\t\t\t\tcase 'COPY':\n\t\t\t\t\t\t\t\t\t\treturn 'copy';\n\t\t\t\t\t\t\t\t\tcase 'DROP':\n\t\t\t\t\t\t\t\t\t\treturn 'drop';\n\t\t\t\t\t\t\t\t\tcase 'STORE':\n\t\t\t\t\t\t\t\t\t\treturn 'store';\n\t\t\t\t\t\t\t\t\tcase 'KEY':\n\t\t\t\t\t\t\t\t\t\treturn 'key';\n\t\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t\treturn 'unknown';\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}) ?? [],\n\t\t\t\t\t})) ?? [],\n\t\t\t\tparameters:\n\t\t\t\t\tmoveFunction.parameters?.map((param) => parseNormalizedSuiMoveType(param.signature)) ??\n\t\t\t\t\t[],\n\t\t\t\treturns:\n\t\t\t\t\tmoveFunction.return?.map(({ signature }) => parseNormalizedSuiMoveType(signature)) ?? [],\n\t\t\t},\n\t\t};\n\t}\n\n\tasync getChainIdentifier(\n\t\t_options?: SuiClientTypes.GetChainIdentifierOptions,\n\t): Promise<SuiClientTypes.GetChainIdentifierResponse> {\n\t\treturn this.cache.read(['chainIdentifier'], async () => {\n\t\t\tconst checkpoint = await this.#graphqlQuery(\n\t\t\t\t{\n\t\t\t\t\tquery: GetChainIdentifierDocument,\n\t\t\t\t},\n\t\t\t\t(result) => result.checkpoint,\n\t\t\t);\n\t\t\tif (!checkpoint?.digest) {\n\t\t\t\tthrow new Error('Genesis checkpoint digest not found');\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tchainIdentifier: checkpoint.digest,\n\t\t\t};\n\t\t});\n\t}\n\n\tresolveTransactionPlugin() {\n\t\tconst graphqlClient = this.#graphqlClient;\n\t\treturn async function resolveTransactionData(\n\t\t\ttransactionData: TransactionDataBuilder,\n\t\t\toptions: BuildTransactionOptions,\n\t\t\tnext: () => Promise<void>,\n\t\t) {\n\t\t\tconst snapshot = transactionData.snapshot();\n\t\t\t// If sender is not set, use a dummy address for resolution purposes\n\t\t\tif (!snapshot.sender) {\n\t\t\t\tsnapshot.sender = '0x0000000000000000000000000000000000000000000000000000000000000000';\n\t\t\t}\n\t\t\tconst grpcTransaction = transactionDataToGrpcTransaction(snapshot);\n\t\t\tconst transactionJson = GrpcTransactionType.toJson(grpcTransaction);\n\n\t\t\tconst { data, errors } = await graphqlClient.query({\n\t\t\t\tquery: ResolveTransactionDocument,\n\t\t\t\tvariables: {\n\t\t\t\t\ttransaction: transactionJson,\n\t\t\t\t\tdoGasSelection:\n\t\t\t\t\t\t!options.onlyTransactionKind &&\n\t\t\t\t\t\t(snapshot.gasData.budget == null || snapshot.gasData.payment == null),\n\t\t\t\t},\n\t\t\t});\n\n\t\t\thandleGraphQLErrors(errors);\n\n\t\t\tconst transactionEffects = data?.simulateTransaction?.effects?.transaction?.effects;\n\t\t\tif (!options.onlyTransactionKind && transactionEffects?.status === ExecutionStatus.Failure) {\n\t\t\t\tconst executionError = parseGraphQLExecutionError(transactionEffects.executionError);\n\t\t\t\tconst errorMessage = executionError?.message ?? 'Transaction failed';\n\t\t\t\tthrow new SimulationError(`Transaction resolution failed: ${errorMessage}`, {\n\t\t\t\t\texecutionError,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst resolvedTransactionBcs =\n\t\t\t\tdata?.simulateTransaction?.effects?.transaction?.transactionBcs;\n\n\t\t\tif (!resolvedTransactionBcs) {\n\t\t\t\tthrow new Error('simulateTransaction did not return resolved transaction data');\n\t\t\t}\n\n\t\t\tconst resolvedBuilder = TransactionDataBuilder.fromBytes(fromBase64(resolvedTransactionBcs));\n\t\t\tconst resolved = resolvedBuilder.snapshot();\n\n\t\t\tif (options.onlyTransactionKind) {\n\t\t\t\ttransactionData.applyResolvedData({\n\t\t\t\t\t...resolved,\n\t\t\t\t\tgasData: {\n\t\t\t\t\t\tbudget: null,\n\t\t\t\t\t\towner: null,\n\t\t\t\t\t\tpayment: null,\n\t\t\t\t\t\tprice: null,\n\t\t\t\t\t},\n\t\t\t\t\texpiration: null,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ttransactionData.applyResolvedData(resolved);\n\t\t\t}\n\n\t\t\treturn await next();\n\t\t};\n\t}\n}\nexport type GraphQLResponseErrors = Array<{\n\tmessage: string;\n\tlocations?: { line: number; column: number }[];\n\tpath?: (string | number)[];\n}>;\n\nfunction mapDisplay(\n\tinclude: boolean | undefined,\n\tdisplay: { output?: unknown | null; errors?: unknown | null } | null | undefined,\n): SuiClientTypes.Display | null | undefined {\n\tif (!include) return undefined;\n\tif (!display) return null;\n\treturn {\n\t\toutput: (display.output as Record<string, unknown> | null) ?? null,\n\t\terrors: (display.errors as Record<string, string> | null) ?? null,\n\t};\n}\n\nfunction handleGraphQLErrors(errors: GraphQLResponseErrors | undefined): void {\n\tif (!errors || errors.length === 0) return;\n\n\tconst errorInstances = errors.map((error) => new GraphQLResponseError(error));\n\n\tif (errorInstances.length === 1) {\n\t\tthrow errorInstances[0];\n\t}\n\n\tthrow new AggregateError(errorInstances);\n}\n\nclass GraphQLResponseError extends Error {\n\tlocations?: Array<{ line: number; column: number }>;\n\n\tconstructor(error: GraphQLResponseErrors[0]) {\n\t\tsuper(error.message);\n\t\tthis.locations = error.locations;\n\t}\n}\n\nfunction mapOwner(owner: Object_Owner_FieldsFragment): SuiClientTypes.ObjectOwner {\n\tswitch (owner.__typename) {\n\t\tcase 'AddressOwner':\n\t\t\treturn { $kind: 'AddressOwner', AddressOwner: owner.address?.address! };\n\t\tcase 'ConsensusAddressOwner':\n\t\t\treturn {\n\t\t\t\t$kind: 'ConsensusAddressOwner',\n\t\t\t\tConsensusAddressOwner: {\n\t\t\t\t\towner: owner?.address?.address!,\n\t\t\t\t\tstartVersion: String(owner.startVersion),\n\t\t\t\t},\n\t\t\t};\n\t\tcase 'ObjectOwner':\n\t\t\treturn { $kind: 'ObjectOwner', ObjectOwner: owner.address?.address! };\n\t\tcase 'Immutable':\n\t\t\treturn { $kind: 'Immutable', Immutable: true };\n\t\tcase 'Shared':\n\t\t\treturn {\n\t\t\t\t$kind: 'Shared',\n\t\t\t\tShared: { initialSharedVersion: String(owner.initialSharedVersion) },\n\t\t\t};\n\t}\n}\n\nfunction parseTransaction<Include extends SuiClientTypes.TransactionInclude = {}>(\n\ttransaction: Transaction_FieldsFragment,\n\tinclude?: Include,\n): SuiClientTypes.TransactionResult<Include> {\n\tconst objectTypes: Record<string, string> = {};\n\n\tif (include?.objectTypes) {\n\t\tconst effectsJson = transaction.effects?.effectsJson;\n\t\tif (effectsJson) {\n\t\t\tconst effects = TransactionEffectsType.fromJson(\n\t\t\t\teffectsJson as Parameters<typeof TransactionEffectsType.fromJson>[0],\n\t\t\t);\n\t\t\teffects.changedObjects?.forEach((change) => {\n\t\t\t\tif (change.objectId && change.objectType) {\n\t\t\t\t\tobjectTypes[change.objectId] = change.objectType;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tconst objectChanges = transaction.effects?.objectChanges?.nodes;\n\t\tif (objectChanges) {\n\t\t\tfor (const change of objectChanges) {\n\t\t\t\tconst type = change.outputState?.asMoveObject?.contents?.type?.repr;\n\t\t\t\tif (change.address && type) {\n\t\t\t\t\tobjectTypes[change.address] = type;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tlet balanceChanges: SuiClientTypes.BalanceChange[] | undefined;\n\tif (include?.balanceChanges) {\n\t\tconst balanceChangesJson = transaction.effects?.balanceChangesJson;\n\t\tif (Array.isArray(balanceChangesJson)) {\n\t\t\tbalanceChanges = balanceChangesJson.map((json) => {\n\t\t\t\tconst change = BalanceChangeType.fromJson(\n\t\t\t\t\tjson as Parameters<typeof BalanceChangeType.fromJson>[0],\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tcoinType: change.coinType!,\n\t\t\t\t\taddress: change.address!,\n\t\t\t\t\tamount: change.amount!,\n\t\t\t\t};\n\t\t\t});\n\t\t} else {\n\t\t\tbalanceChanges = [];\n\t\t}\n\t}\n\n\t// Get status from GraphQL response\n\tconst status: SuiClientTypes.ExecutionStatus =\n\t\ttransaction.effects?.status === ExecutionStatus.Success\n\t\t\t? { success: true, error: null }\n\t\t\t: {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: parseGraphQLExecutionError(transaction.effects?.executionError),\n\t\t\t\t};\n\n\tlet transactionData: SuiClientTypes.TransactionData | undefined;\n\tif (include?.transaction && transaction.transactionJson) {\n\t\tconst grpcTx = GrpcTransactionType.fromJson(\n\t\t\ttransaction.transactionJson as Parameters<typeof GrpcTransactionType.fromJson>[0],\n\t\t);\n\t\tconst resolved = grpcTransactionToTransactionData(grpcTx);\n\t\ttransactionData = {\n\t\t\tgasData: resolved.gasData,\n\t\t\tsender: resolved.sender,\n\t\t\texpiration: resolved.expiration,\n\t\t\tcommands: resolved.commands,\n\t\t\tinputs: resolved.inputs,\n\t\t\tversion: resolved.version,\n\t\t};\n\t}\n\n\tconst bcsBytes =\n\t\tinclude?.bcs && transaction.transactionBcs ? fromBase64(transaction.transactionBcs) : undefined;\n\n\tconst result: SuiClientTypes.Transaction<Include> = {\n\t\tdigest: transaction.digest!,\n\t\tstatus,\n\t\teffects: (include?.effects\n\t\t\t? parseTransactionEffectsBcs(fromBase64(transaction.effects?.effectsBcs!))\n\t\t\t: undefined) as SuiClientTypes.Transaction<Include>['effects'],\n\t\tepoch: transaction.effects?.epoch?.epochId?.toString() ?? null,\n\t\tobjectTypes: (include?.objectTypes\n\t\t\t? objectTypes\n\t\t\t: undefined) as SuiClientTypes.Transaction<Include>['objectTypes'],\n\t\ttransaction: transactionData as SuiClientTypes.Transaction<Include>['transaction'],\n\t\tbcs: bcsBytes as SuiClientTypes.Transaction<Include>['bcs'],\n\t\tsignatures: transaction.signatures.map((sig) => sig.signatureBytes!),\n\t\tbalanceChanges: balanceChanges as SuiClientTypes.Transaction<Include>['balanceChanges'],\n\t\tevents: (include?.events\n\t\t\t? (transaction.effects?.events?.nodes.map((event) => {\n\t\t\t\t\tconst eventType = event.contents?.type?.repr!;\n\t\t\t\t\tconst [packageId, module] = eventType.split('::');\n\t\t\t\t\treturn {\n\t\t\t\t\t\tpackageId,\n\t\t\t\t\t\tmodule,\n\t\t\t\t\t\tsender: event.sender?.address!,\n\t\t\t\t\t\teventType,\n\t\t\t\t\t\tbcs: event.contents?.bcs ? fromBase64(event.contents.bcs) : new Uint8Array(),\n\t\t\t\t\t\tjson: (event.contents?.json as Record<string, unknown>) ?? null,\n\t\t\t\t\t};\n\t\t\t\t}) ?? [])\n\t\t\t: undefined) as SuiClientTypes.Transaction<Include>['events'],\n\t};\n\n\treturn status.success\n\t\t? { $kind: 'Transaction', Transaction: result, FailedTransaction: undefined as never }\n\t\t: { $kind: 'FailedTransaction', Transaction: undefined as never, FailedTransaction: result };\n}\n\nfunction parseNormalizedSuiMoveType(type: OpenMoveTypeSignature): SuiClientTypes.OpenSignature {\n\tlet reference: 'mutable' | 'immutable' | null = null;\n\n\tif (type.ref === '&') {\n\t\treference = 'immutable';\n\t} else if (type.ref === '&mut') {\n\t\treference = 'mutable';\n\t}\n\n\treturn {\n\t\treference,\n\t\tbody: parseNormalizedSuiMoveTypeBody(type.body),\n\t};\n}\n\nfunction parseGraphQLExecutionError(\n\texecutionError: GraphQLExecutionError | null | undefined,\n): SuiClientTypes.ExecutionError {\n\tconst name = mapGraphQLExecutionErrorKind(executionError);\n\n\tif (name === 'MoveAbort' && executionError?.abortCode != null) {\n\t\tconst location = parseGraphQLMoveLocation(executionError);\n\t\tconst cleverError = parseGraphQLCleverError(executionError);\n\t\tconst commandMatch = executionError.message?.match(/in (\\d+)\\w* command/);\n\t\tconst command = commandMatch ? parseInt(commandMatch[1], 10) - 1 : undefined;\n\n\t\treturn {\n\t\t\t$kind: 'MoveAbort',\n\t\t\tmessage: formatMoveAbortMessage({\n\t\t\t\tcommand,\n\t\t\t\tlocation: location\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tpackage: location.package,\n\t\t\t\t\t\t\tmodule: location.module,\n\t\t\t\t\t\t\tfunctionName: location.functionName,\n\t\t\t\t\t\t\tinstruction: location.instruction,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\t\tabortCode: executionError.abortCode!,\n\t\t\t\tcleverError: cleverError\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tlineNumber: cleverError.lineNumber,\n\t\t\t\t\t\t\tconstantName: cleverError.constantName,\n\t\t\t\t\t\t\tvalue: cleverError.value,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\t}),\n\t\t\tcommand,\n\t\t\tMoveAbort: {\n\t\t\t\tabortCode: executionError.abortCode!,\n\t\t\t\tlocation,\n\t\t\t\tcleverError,\n\t\t\t},\n\t\t};\n\t}\n\n\treturn {\n\t\t$kind: 'Unknown',\n\t\tmessage: executionError?.message ?? 'Transaction failed',\n\t\tUnknown: null,\n\t};\n}\n\nfunction mapGraphQLExecutionErrorKind(\n\texecutionError: GraphQLExecutionError | null | undefined,\n): string {\n\tif (executionError?.abortCode != null) {\n\t\treturn 'MoveAbort';\n\t}\n\n\tconst match = executionError?.message?.match(/^(\\w+)/);\n\treturn match?.[1] ?? 'Unknown';\n}\n\nfunction parseGraphQLMoveLocation(\n\texecutionError: GraphQLExecutionError,\n): SuiClientTypes.MoveLocation | undefined {\n\tconst hasLocation = executionError.module?.package?.address && executionError.module?.name;\n\tif (!hasLocation) {\n\t\treturn undefined;\n\t}\n\n\treturn {\n\t\tpackage: executionError.module?.package?.address,\n\t\tmodule: executionError.module?.name,\n\t\tfunctionName: executionError.function?.name,\n\t\tinstruction: executionError.instructionOffset ?? undefined,\n\t};\n}\n\nfunction parseGraphQLCleverError(\n\texecutionError: GraphQLExecutionError,\n): SuiClientTypes.CleverError | undefined {\n\tconst hasCleverError = executionError.identifier || executionError.constant;\n\tif (!hasCleverError) {\n\t\treturn undefined;\n\t}\n\n\treturn {\n\t\tconstantName: executionError.identifier ?? undefined,\n\t\tvalue: executionError.constant ?? undefined,\n\t\tlineNumber: executionError.sourceLineNumber ?? undefined,\n\t};\n}\n\nfunction parseNormalizedSuiMoveTypeBody(\n\ttype: OpenMoveTypeSignatureBody,\n): SuiClientTypes.OpenSignatureBody {\n\tswitch (type) {\n\t\tcase 'address':\n\t\t\treturn { $kind: 'address' };\n\t\tcase 'bool':\n\t\t\treturn { $kind: 'bool' };\n\t\tcase 'u8':\n\t\t\treturn { $kind: 'u8' };\n\t\tcase 'u16':\n\t\t\treturn { $kind: 'u16' };\n\t\tcase 'u32':\n\t\t\treturn { $kind: 'u32' };\n\t\tcase 'u64':\n\t\t\treturn { $kind: 'u64' };\n\t\tcase 'u128':\n\t\t\treturn { $kind: 'u128' };\n\t\tcase 'u256':\n\t\t\treturn { $kind: 'u256' };\n\t}\n\n\tif (typeof type === 'string') {\n\t\tthrow new Error(`Unknown type: ${type}`);\n\t}\n\n\tif ('vector' in type) {\n\t\treturn {\n\t\t\t$kind: 'vector',\n\t\t\tvector: parseNormalizedSuiMoveTypeBody(type.vector),\n\t\t};\n\t}\n\n\tif ('datatype' in type) {\n\t\treturn {\n\t\t\t$kind: 'datatype',\n\t\t\tdatatype: {\n\t\t\t\ttypeName: `${normalizeSuiAddress(type.datatype.package)}::${type.datatype.module}::${type.datatype.type}`,\n\t\t\t\ttypeParameters: type.datatype.typeParameters.map((t) => parseNormalizedSuiMoveTypeBody(t)),\n\t\t\t},\n\t\t};\n\t}\n\n\tif ('typeParameter' in type) {\n\t\treturn {\n\t\t\t$kind: 'typeParameter',\n\t\t\tindex: type.typeParameter,\n\t\t};\n\t}\n\n\tthrow new Error(`Unknown type: ${JSON.stringify(type)}`);\n}\n","export function devAssert(condition, message) {\n const booleanCondition = Boolean(condition);\n\n if (!booleanCondition) {\n throw new Error(message);\n }\n}\n","/**\n * Contains a range of UTF-8 character offsets and token references that\n * identify the region of the source from which the AST derived.\n */\nexport class Location {\n /**\n * The character offset at which this Node begins.\n */\n\n /**\n * The character offset at which this Node ends.\n */\n\n /**\n * The Token at which this Node begins.\n */\n\n /**\n * The Token at which this Node ends.\n */\n\n /**\n * The Source document the AST represents.\n */\n constructor(startToken, endToken, source) {\n this.start = startToken.start;\n this.end = endToken.end;\n this.startToken = startToken;\n this.endToken = endToken;\n this.source = source;\n }\n\n get [Symbol.toStringTag]() {\n return 'Location';\n }\n\n toJSON() {\n return {\n start: this.start,\n end: this.end,\n };\n }\n}\n/**\n * Represents a range of characters represented by a lexical token\n * within a Source.\n */\n\nexport class Token {\n /**\n * The kind of Token.\n */\n\n /**\n * The character offset at which this Node begins.\n */\n\n /**\n * The character offset at which this Node ends.\n */\n\n /**\n * The 1-indexed line number on which this Token appears.\n */\n\n /**\n * The 1-indexed column number at which this Token begins.\n */\n\n /**\n * For non-punctuation tokens, represents the interpreted value of the token.\n *\n * Note: is undefined for punctuation tokens, but typed as string for\n * convenience in the parser.\n */\n\n /**\n * Tokens exist as nodes in a double-linked-list amongst all tokens\n * including ignored tokens. <SOF> is always the first node and <EOF>\n * the last.\n */\n constructor(kind, start, end, line, column, value) {\n this.kind = kind;\n this.start = start;\n this.end = end;\n this.line = line;\n this.column = column; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n\n this.value = value;\n this.prev = null;\n this.next = null;\n }\n\n get [Symbol.toStringTag]() {\n return 'Token';\n }\n\n toJSON() {\n return {\n kind: this.kind,\n value: this.value,\n line: this.line,\n column: this.column,\n };\n }\n}\n/**\n * The list of all possible AST node types.\n */\n\n/**\n * @internal\n */\nexport const QueryDocumentKeys = {\n Name: [],\n Document: ['definitions'],\n OperationDefinition: [\n 'description',\n 'name',\n 'variableDefinitions',\n 'directives',\n 'selectionSet',\n ],\n VariableDefinition: [\n 'description',\n 'variable',\n 'type',\n 'defaultValue',\n 'directives',\n ],\n Variable: ['name'],\n SelectionSet: ['selections'],\n Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'],\n Argument: ['name', 'value'],\n FragmentSpread: ['name', 'directives'],\n InlineFragment: ['typeCondition', 'directives', 'selectionSet'],\n FragmentDefinition: [\n 'description',\n 'name', // Note: fragment variable definitions are deprecated and will removed in v17.0.0\n 'variableDefinitions',\n 'typeCondition',\n 'directives',\n 'selectionSet',\n ],\n IntValue: [],\n FloatValue: [],\n StringValue: [],\n BooleanValue: [],\n NullValue: [],\n EnumValue: [],\n ListValue: ['values'],\n ObjectValue: ['fields'],\n ObjectField: ['name', 'value'],\n Directive: ['name', 'arguments'],\n NamedType: ['name'],\n ListType: ['type'],\n NonNullType: ['type'],\n SchemaDefinition: ['description', 'directives', 'operationTypes'],\n OperationTypeDefinition: ['type'],\n ScalarTypeDefinition: ['description', 'name', 'directives'],\n ObjectTypeDefinition: [\n 'description',\n 'name',\n 'interfaces',\n 'directives',\n 'fields',\n ],\n FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'],\n InputValueDefinition: [\n 'description',\n 'name',\n 'type',\n 'defaultValue',\n 'directives',\n ],\n InterfaceTypeDefinition: [\n 'description',\n 'name',\n 'interfaces',\n 'directives',\n 'fields',\n ],\n UnionTypeDefinition: ['description', 'name', 'directives', 'types'],\n EnumTypeDefinition: ['description', 'name', 'directives', 'values'],\n EnumValueDefinition: ['description', 'name', 'directives'],\n InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'],\n DirectiveDefinition: ['description', 'name', 'arguments', 'locations'],\n SchemaExtension: ['directives', 'operationTypes'],\n ScalarTypeExtension: ['name', 'directives'],\n ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'],\n InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'],\n UnionTypeExtension: ['name', 'directives', 'types'],\n EnumTypeExtension: ['name', 'directives', 'values'],\n InputObjectTypeExtension: ['name', 'directives', 'fields'],\n TypeCoordinate: ['name'],\n MemberCoordinate: ['name', 'memberName'],\n ArgumentCoordinate: ['name', 'fieldName', 'argumentName'],\n DirectiveCoordinate: ['name'],\n DirectiveArgumentCoordinate: ['name', 'argumentName'],\n};\nconst kindValues = new Set(Object.keys(QueryDocumentKeys));\n/**\n * @internal\n */\n\nexport function isNode(maybeNode) {\n const maybeKind =\n maybeNode === null || maybeNode === void 0 ? void 0 : maybeNode.kind;\n return typeof maybeKind === 'string' && kindValues.has(maybeKind);\n}\n/** Name */\n\nvar OperationTypeNode;\n\n(function (OperationTypeNode) {\n OperationTypeNode['QUERY'] = 'query';\n OperationTypeNode['MUTATION'] = 'mutation';\n OperationTypeNode['SUBSCRIPTION'] = 'subscription';\n})(OperationTypeNode || (OperationTypeNode = {}));\n\nexport { OperationTypeNode };\n","/**\n * The set of allowed kind values for AST nodes.\n */\nvar Kind;\n\n(function (Kind) {\n Kind['NAME'] = 'Name';\n Kind['DOCUMENT'] = 'Document';\n Kind['OPERATION_DEFINITION'] = 'OperationDefinition';\n Kind['VARIABLE_DEFINITION'] = 'VariableDefinition';\n Kind['SELECTION_SET'] = 'SelectionSet';\n Kind['FIELD'] = 'Field';\n Kind['ARGUMENT'] = 'Argument';\n Kind['FRAGMENT_SPREAD'] = 'FragmentSpread';\n Kind['INLINE_FRAGMENT'] = 'InlineFragment';\n Kind['FRAGMENT_DEFINITION'] = 'FragmentDefinition';\n Kind['VARIABLE'] = 'Variable';\n Kind['INT'] = 'IntValue';\n Kind['FLOAT'] = 'FloatValue';\n Kind['STRING'] = 'StringValue';\n Kind['BOOLEAN'] = 'BooleanValue';\n Kind['NULL'] = 'NullValue';\n Kind['ENUM'] = 'EnumValue';\n Kind['LIST'] = 'ListValue';\n Kind['OBJECT'] = 'ObjectValue';\n Kind['OBJECT_FIELD'] = 'ObjectField';\n Kind['DIRECTIVE'] = 'Directive';\n Kind['NAMED_TYPE'] = 'NamedType';\n Kind['LIST_TYPE'] = 'ListType';\n Kind['NON_NULL_TYPE'] = 'NonNullType';\n Kind['SCHEMA_DEFINITION'] = 'SchemaDefinition';\n Kind['OPERATION_TYPE_DEFINITION'] = 'OperationTypeDefinition';\n Kind['SCALAR_TYPE_DEFINITION'] = 'ScalarTypeDefinition';\n Kind['OBJECT_TYPE_DEFINITION'] = 'ObjectTypeDefinition';\n Kind['FIELD_DEFINITION'] = 'FieldDefinition';\n Kind['INPUT_VALUE_DEFINITION'] = 'InputValueDefinition';\n Kind['INTERFACE_TYPE_DEFINITION'] = 'InterfaceTypeDefinition';\n Kind['UNION_TYPE_DEFINITION'] = 'UnionTypeDefinition';\n Kind['ENUM_TYPE_DEFINITION'] = 'EnumTypeDefinition';\n Kind['ENUM_VALUE_DEFINITION'] = 'EnumValueDefinition';\n Kind['INPUT_OBJECT_TYPE_DEFINITION'] = 'InputObjectTypeDefinition';\n Kind['DIRECTIVE_DEFINITION'] = 'DirectiveDefinition';\n Kind['SCHEMA_EXTENSION'] = 'SchemaExtension';\n Kind['SCALAR_TYPE_EXTENSION'] = 'ScalarTypeExtension';\n Kind['OBJECT_TYPE_EXTENSION'] = 'ObjectTypeExtension';\n Kind['INTERFACE_TYPE_EXTENSION'] = 'InterfaceTypeExtension';\n Kind['UNION_TYPE_EXTENSION'] = 'UnionTypeExtension';\n Kind['ENUM_TYPE_EXTENSION'] = 'EnumTypeExtension';\n Kind['INPUT_OBJECT_TYPE_EXTENSION'] = 'InputObjectTypeExtension';\n Kind['TYPE_COORDINATE'] = 'TypeCoordinate';\n Kind['MEMBER_COORDINATE'] = 'MemberCoordinate';\n Kind['ARGUMENT_COORDINATE'] = 'ArgumentCoordinate';\n Kind['DIRECTIVE_COORDINATE'] = 'DirectiveCoordinate';\n Kind['DIRECTIVE_ARGUMENT_COORDINATE'] = 'DirectiveArgumentCoordinate';\n})(Kind || (Kind = {}));\n\nexport { Kind };\n/**\n * The enum type representing the possible kind values of AST nodes.\n *\n * @deprecated Please use `Kind`. Will be remove in v17.\n */\n","/**\n * ```\n * WhiteSpace ::\n * - \"Horizontal Tab (U+0009)\"\n * - \"Space (U+0020)\"\n * ```\n * @internal\n */\nexport function isWhiteSpace(code) {\n return code === 0x0009 || code === 0x0020;\n}\n/**\n * ```\n * Digit :: one of\n * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9`\n * ```\n * @internal\n */\n\nexport function isDigit(code) {\n return code >= 0x0030 && code <= 0x0039;\n}\n/**\n * ```\n * Letter :: one of\n * - `A` `B` `C` `D` `E` `F` `G` `H` `I` `J` `K` `L` `M`\n * - `N` `O` `P` `Q` `R` `S` `T` `U` `V` `W` `X` `Y` `Z`\n * - `a` `b` `c` `d` `e` `f` `g` `h` `i` `j` `k` `l` `m`\n * - `n` `o` `p` `q` `r` `s` `t` `u` `v` `w` `x` `y` `z`\n * ```\n * @internal\n */\n\nexport function isLetter(code) {\n return (\n (code >= 0x0061 && code <= 0x007a) || // A-Z\n (code >= 0x0041 && code <= 0x005a) // a-z\n );\n}\n/**\n * ```\n * NameStart ::\n * - Letter\n * - `_`\n * ```\n * @internal\n */\n\nexport function isNameStart(code) {\n return isLetter(code) || code === 0x005f;\n}\n/**\n * ```\n * NameContinue ::\n * - Letter\n * - Digit\n * - `_`\n * ```\n * @internal\n */\n\nexport function isNameContinue(code) {\n return isLetter(code) || isDigit(code) || code === 0x005f;\n}\n","import { isWhiteSpace } from './characterClasses.mjs';\n/**\n * Produces the value of a block string from its parsed raw value, similar to\n * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc.\n *\n * This implements the GraphQL spec's BlockStringValue() static algorithm.\n *\n * @internal\n */\n\nexport function dedentBlockStringLines(lines) {\n var _firstNonEmptyLine2;\n\n let commonIndent = Number.MAX_SAFE_INTEGER;\n let firstNonEmptyLine = null;\n let lastNonEmptyLine = -1;\n\n for (let i = 0; i < lines.length; ++i) {\n var _firstNonEmptyLine;\n\n const line = lines[i];\n const indent = leadingWhitespace(line);\n\n if (indent === line.length) {\n continue; // skip empty lines\n }\n\n firstNonEmptyLine =\n (_firstNonEmptyLine = firstNonEmptyLine) !== null &&\n _firstNonEmptyLine !== void 0\n ? _firstNonEmptyLine\n : i;\n lastNonEmptyLine = i;\n\n if (i !== 0 && indent < commonIndent) {\n commonIndent = indent;\n }\n }\n\n return lines // Remove common indentation from all lines but first.\n .map((line, i) => (i === 0 ? line : line.slice(commonIndent))) // Remove leading and trailing blank lines.\n .slice(\n (_firstNonEmptyLine2 = firstNonEmptyLine) !== null &&\n _firstNonEmptyLine2 !== void 0\n ? _firstNonEmptyLine2\n : 0,\n lastNonEmptyLine + 1,\n );\n}\n\nfunction leadingWhitespace(str) {\n let i = 0;\n\n while (i < str.length && isWhiteSpace(str.charCodeAt(i))) {\n ++i;\n }\n\n return i;\n}\n/**\n * @internal\n */\n\nexport function isPrintableAsBlockString(value) {\n if (value === '') {\n return true; // empty string is printable\n }\n\n let isEmptyLine = true;\n let hasIndent = false;\n let hasCommonIndent = true;\n let seenNonEmptyLine = false;\n\n for (let i = 0; i < value.length; ++i) {\n switch (value.codePointAt(i)) {\n case 0x0000:\n case 0x0001:\n case 0x0002:\n case 0x0003:\n case 0x0004:\n case 0x0005:\n case 0x0006:\n case 0x0007:\n case 0x0008:\n case 0x000b:\n case 0x000c:\n case 0x000e:\n case 0x000f:\n return false;\n // Has non-printable characters\n\n case 0x000d:\n // \\r\n return false;\n // Has \\r or \\r\\n which will be replaced as \\n\n\n case 10:\n // \\n\n if (isEmptyLine && !seenNonEmptyLine) {\n return false; // Has leading new line\n }\n\n seenNonEmptyLine = true;\n isEmptyLine = true;\n hasIndent = false;\n break;\n\n case 9: // \\t\n\n case 32:\n // <space>\n hasIndent || (hasIndent = isEmptyLine);\n break;\n\n default:\n hasCommonIndent && (hasCommonIndent = hasIndent);\n isEmptyLine = false;\n }\n }\n\n if (isEmptyLine) {\n return false; // Has trailing empty lines\n }\n\n if (hasCommonIndent && seenNonEmptyLine) {\n return false; // Has internal indent\n }\n\n return true;\n}\n/**\n * Print a block string in the indented block form by adding a leading and\n * trailing blank line. However, if a block string starts with whitespace and is\n * a single-line, adding a leading blank line would strip that whitespace.\n *\n * @internal\n */\n\nexport function printBlockString(value, options) {\n const escapedValue = value.replace(/\"\"\"/g, '\\\\\"\"\"'); // Expand a block string's raw value into independent lines.\n\n const lines = escapedValue.split(/\\r\\n|[\\n\\r]/g);\n const isSingleLine = lines.length === 1; // If common indentation is found we can fix some of those cases by adding leading new line\n\n const forceLeadingNewLine =\n lines.length > 1 &&\n lines\n .slice(1)\n .every((line) => line.length === 0 || isWhiteSpace(line.charCodeAt(0))); // Trailing triple quotes just looks confusing but doesn't force trailing new line\n\n const hasTrailingTripleQuotes = escapedValue.endsWith('\\\\\"\"\"'); // Trailing quote (single or double) or slash forces trailing new line\n\n const hasTrailingQuote = value.endsWith('\"') && !hasTrailingTripleQuotes;\n const hasTrailingSlash = value.endsWith('\\\\');\n const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash;\n const printAsMultipleLines =\n !(options !== null && options !== void 0 && options.minimize) && // add leading and trailing new lines only if it improves readability\n (!isSingleLine ||\n value.length > 70 ||\n forceTrailingNewline ||\n forceLeadingNewLine ||\n hasTrailingTripleQuotes);\n let result = ''; // Format a multi-line block quote to account for leading space.\n\n const skipLeadingNewLine = isSingleLine && isWhiteSpace(value.charCodeAt(0));\n\n if ((printAsMultipleLines && !skipLeadingNewLine) || forceLeadingNewLine) {\n result += '\\n';\n }\n\n result += escapedValue;\n\n if (printAsMultipleLines || forceTrailingNewline) {\n result += '\\n';\n }\n\n return '\"\"\"' + result + '\"\"\"';\n}\n","const MAX_ARRAY_LENGTH = 10;\nconst MAX_RECURSIVE_DEPTH = 2;\n/**\n * Used to print values in error messages.\n */\n\nexport function inspect(value) {\n return formatValue(value, []);\n}\n\nfunction formatValue(value, seenValues) {\n switch (typeof value) {\n case 'string':\n return JSON.stringify(value);\n\n case 'function':\n return value.name ? `[function ${value.name}]` : '[function]';\n\n case 'object':\n return formatObjectValue(value, seenValues);\n\n default:\n return String(value);\n }\n}\n\nfunction formatObjectValue(value, previouslySeenValues) {\n if (value === null) {\n return 'null';\n }\n\n if (previouslySeenValues.includes(value)) {\n return '[Circular]';\n }\n\n const seenValues = [...previouslySeenValues, value];\n\n if (isJSONable(value)) {\n const jsonValue = value.toJSON(); // check for infinite recursion\n\n if (jsonValue !== value) {\n return typeof jsonValue === 'string'\n ? jsonValue\n : formatValue(jsonValue, seenValues);\n }\n } else if (Array.isArray(value)) {\n return formatArray(value, seenValues);\n }\n\n return formatObject(value, seenValues);\n}\n\nfunction isJSONable(value) {\n return typeof value.toJSON === 'function';\n}\n\nfunction formatObject(object, seenValues) {\n const entries = Object.entries(object);\n\n if (entries.length === 0) {\n return '{}';\n }\n\n if (seenValues.length > MAX_RECURSIVE_DEPTH) {\n return '[' + getObjectTag(object) + ']';\n }\n\n const properties = entries.map(\n ([key, value]) => key + ': ' + formatValue(value, seenValues),\n );\n return '{ ' + properties.join(', ') + ' }';\n}\n\nfunction formatArray(array, seenValues) {\n if (array.length === 0) {\n return '[]';\n }\n\n if (seenValues.length > MAX_RECURSIVE_DEPTH) {\n return '[Array]';\n }\n\n const len = Math.min(MAX_ARRAY_LENGTH, array.length);\n const remaining = array.length - len;\n const items = [];\n\n for (let i = 0; i < len; ++i) {\n items.push(formatValue(array[i], seenValues));\n }\n\n if (remaining === 1) {\n items.push('... 1 more item');\n } else if (remaining > 1) {\n items.push(`... ${remaining} more items`);\n }\n\n return '[' + items.join(', ') + ']';\n}\n\nfunction getObjectTag(object) {\n const tag = Object.prototype.toString\n .call(object)\n .replace(/^\\[object /, '')\n .replace(/]$/, '');\n\n if (tag === 'Object' && typeof object.constructor === 'function') {\n const name = object.constructor.name;\n\n if (typeof name === 'string' && name !== '') {\n return name;\n }\n }\n\n return tag;\n}\n","/**\n * Prints a string as a GraphQL StringValue literal. Replaces control characters\n * and excluded characters (\" U+0022 and \\\\ U+005C) with escape sequences.\n */\nexport function printString(str) {\n return `\"${str.replace(escapedRegExp, escapedReplacer)}\"`;\n} // eslint-disable-next-line no-control-regex\n\nconst escapedRegExp = /[\\x00-\\x1f\\x22\\x5c\\x7f-\\x9f]/g;\n\nfunction escapedReplacer(str) {\n return escapeSequences[str.charCodeAt(0)];\n} // prettier-ignore\n\nconst escapeSequences = [\n '\\\\u0000',\n '\\\\u0001',\n '\\\\u0002',\n '\\\\u0003',\n '\\\\u0004',\n '\\\\u0005',\n '\\\\u0006',\n '\\\\u0007',\n '\\\\b',\n '\\\\t',\n '\\\\n',\n '\\\\u000B',\n '\\\\f',\n '\\\\r',\n '\\\\u000E',\n '\\\\u000F',\n '\\\\u0010',\n '\\\\u0011',\n '\\\\u0012',\n '\\\\u0013',\n '\\\\u0014',\n '\\\\u0015',\n '\\\\u0016',\n '\\\\u0017',\n '\\\\u0018',\n '\\\\u0019',\n '\\\\u001A',\n '\\\\u001B',\n '\\\\u001C',\n '\\\\u001D',\n '\\\\u001E',\n '\\\\u001F',\n '',\n '',\n '\\\\\"',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '', // 2F\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '', // 3F\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '', // 4F\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '\\\\\\\\',\n '',\n '',\n '', // 5F\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '', // 6F\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '\\\\u007F',\n '\\\\u0080',\n '\\\\u0081',\n '\\\\u0082',\n '\\\\u0083',\n '\\\\u0084',\n '\\\\u0085',\n '\\\\u0086',\n '\\\\u0087',\n '\\\\u0088',\n '\\\\u0089',\n '\\\\u008A',\n '\\\\u008B',\n '\\\\u008C',\n '\\\\u008D',\n '\\\\u008E',\n '\\\\u008F',\n '\\\\u0090',\n '\\\\u0091',\n '\\\\u0092',\n '\\\\u0093',\n '\\\\u0094',\n '\\\\u0095',\n '\\\\u0096',\n '\\\\u0097',\n '\\\\u0098',\n '\\\\u0099',\n '\\\\u009A',\n '\\\\u009B',\n '\\\\u009C',\n '\\\\u009D',\n '\\\\u009E',\n '\\\\u009F',\n];\n","import { devAssert } from '../jsutils/devAssert.mjs';\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { isNode, QueryDocumentKeys } from './ast.mjs';\nimport { Kind } from './kinds.mjs';\n/**\n * A visitor is provided to visit, it contains the collection of\n * relevant functions to be called during the visitor's traversal.\n */\n\nexport const BREAK = Object.freeze({});\n/**\n * visit() will walk through an AST using a depth-first traversal, calling\n * the visitor's enter function at each node in the traversal, and calling the\n * leave function after visiting that node and all of its child nodes.\n *\n * By returning different values from the enter and leave functions, the\n * behavior of the visitor can be altered, including skipping over a sub-tree of\n * the AST (by returning false), editing the AST by returning a value or null\n * to remove the value, or to stop the whole traversal by returning BREAK.\n *\n * When using visit() to edit an AST, the original AST will not be modified, and\n * a new version of the AST with the changes applied will be returned from the\n * visit function.\n *\n * ```ts\n * const editedAST = visit(ast, {\n * enter(node, key, parent, path, ancestors) {\n * // @return\n * // undefined: no action\n * // false: skip visiting this node\n * // visitor.BREAK: stop visiting altogether\n * // null: delete this node\n * // any value: replace this node with the returned value\n * },\n * leave(node, key, parent, path, ancestors) {\n * // @return\n * // undefined: no action\n * // false: no action\n * // visitor.BREAK: stop visiting altogether\n * // null: delete this node\n * // any value: replace this node with the returned value\n * }\n * });\n * ```\n *\n * Alternatively to providing enter() and leave() functions, a visitor can\n * instead provide functions named the same as the kinds of AST nodes, or\n * enter/leave visitors at a named key, leading to three permutations of the\n * visitor API:\n *\n * 1) Named visitors triggered when entering a node of a specific kind.\n *\n * ```ts\n * visit(ast, {\n * Kind(node) {\n * // enter the \"Kind\" node\n * }\n * })\n * ```\n *\n * 2) Named visitors that trigger upon entering and leaving a node of a specific kind.\n *\n * ```ts\n * visit(ast, {\n * Kind: {\n * enter(node) {\n * // enter the \"Kind\" node\n * }\n * leave(node) {\n * // leave the \"Kind\" node\n * }\n * }\n * })\n * ```\n *\n * 3) Generic visitors that trigger upon entering and leaving any node.\n *\n * ```ts\n * visit(ast, {\n * enter(node) {\n * // enter any node\n * },\n * leave(node) {\n * // leave any node\n * }\n * })\n * ```\n */\n\nexport function visit(root, visitor, visitorKeys = QueryDocumentKeys) {\n const enterLeaveMap = new Map();\n\n for (const kind of Object.values(Kind)) {\n enterLeaveMap.set(kind, getEnterLeaveForKind(visitor, kind));\n }\n /* eslint-disable no-undef-init */\n\n let stack = undefined;\n let inArray = Array.isArray(root);\n let keys = [root];\n let index = -1;\n let edits = [];\n let node = root;\n let key = undefined;\n let parent = undefined;\n const path = [];\n const ancestors = [];\n /* eslint-enable no-undef-init */\n\n do {\n index++;\n const isLeaving = index === keys.length;\n const isEdited = isLeaving && edits.length !== 0;\n\n if (isLeaving) {\n key = ancestors.length === 0 ? undefined : path[path.length - 1];\n node = parent;\n parent = ancestors.pop();\n\n if (isEdited) {\n if (inArray) {\n node = node.slice();\n let editOffset = 0;\n\n for (const [editKey, editValue] of edits) {\n const arrayKey = editKey - editOffset;\n\n if (editValue === null) {\n node.splice(arrayKey, 1);\n editOffset++;\n } else {\n node[arrayKey] = editValue;\n }\n }\n } else {\n node = { ...node };\n\n for (const [editKey, editValue] of edits) {\n node[editKey] = editValue;\n }\n }\n }\n\n index = stack.index;\n keys = stack.keys;\n edits = stack.edits;\n inArray = stack.inArray;\n stack = stack.prev;\n } else if (parent) {\n key = inArray ? index : keys[index];\n node = parent[key];\n\n if (node === null || node === undefined) {\n continue;\n }\n\n path.push(key);\n }\n\n let result;\n\n if (!Array.isArray(node)) {\n var _enterLeaveMap$get, _enterLeaveMap$get2;\n\n isNode(node) || devAssert(false, `Invalid AST Node: ${inspect(node)}.`);\n const visitFn = isLeaving\n ? (_enterLeaveMap$get = enterLeaveMap.get(node.kind)) === null ||\n _enterLeaveMap$get === void 0\n ? void 0\n : _enterLeaveMap$get.leave\n : (_enterLeaveMap$get2 = enterLeaveMap.get(node.kind)) === null ||\n _enterLeaveMap$get2 === void 0\n ? void 0\n : _enterLeaveMap$get2.enter;\n result =\n visitFn === null || visitFn === void 0\n ? void 0\n : visitFn.call(visitor, node, key, parent, path, ancestors);\n\n if (result === BREAK) {\n break;\n }\n\n if (result === false) {\n if (!isLeaving) {\n path.pop();\n continue;\n }\n } else if (result !== undefined) {\n edits.push([key, result]);\n\n if (!isLeaving) {\n if (isNode(result)) {\n node = result;\n } else {\n path.pop();\n continue;\n }\n }\n }\n }\n\n if (result === undefined && isEdited) {\n edits.push([key, node]);\n }\n\n if (isLeaving) {\n path.pop();\n } else {\n var _node$kind;\n\n stack = {\n inArray,\n index,\n keys,\n edits,\n prev: stack,\n };\n inArray = Array.isArray(node);\n keys = inArray\n ? node\n : (_node$kind = visitorKeys[node.kind]) !== null &&\n _node$kind !== void 0\n ? _node$kind\n : [];\n index = -1;\n edits = [];\n\n if (parent) {\n ancestors.push(parent);\n }\n\n parent = node;\n }\n } while (stack !== undefined);\n\n if (edits.length !== 0) {\n // New root\n return edits[edits.length - 1][1];\n }\n\n return root;\n}\n/**\n * Creates a new visitor instance which delegates to many visitors to run in\n * parallel. Each visitor will be visited for each node before moving on.\n *\n * If a prior visitor edits a node, no following visitors will see that node.\n */\n\nexport function visitInParallel(visitors) {\n const skipping = new Array(visitors.length).fill(null);\n const mergedVisitor = Object.create(null);\n\n for (const kind of Object.values(Kind)) {\n let hasVisitor = false;\n const enterList = new Array(visitors.length).fill(undefined);\n const leaveList = new Array(visitors.length).fill(undefined);\n\n for (let i = 0; i < visitors.length; ++i) {\n const { enter, leave } = getEnterLeaveForKind(visitors[i], kind);\n hasVisitor || (hasVisitor = enter != null || leave != null);\n enterList[i] = enter;\n leaveList[i] = leave;\n }\n\n if (!hasVisitor) {\n continue;\n }\n\n const mergedEnterLeave = {\n enter(...args) {\n const node = args[0];\n\n for (let i = 0; i < visitors.length; i++) {\n if (skipping[i] === null) {\n var _enterList$i;\n\n const result =\n (_enterList$i = enterList[i]) === null || _enterList$i === void 0\n ? void 0\n : _enterList$i.apply(visitors[i], args);\n\n if (result === false) {\n skipping[i] = node;\n } else if (result === BREAK) {\n skipping[i] = BREAK;\n } else if (result !== undefined) {\n return result;\n }\n }\n }\n },\n\n leave(...args) {\n const node = args[0];\n\n for (let i = 0; i < visitors.length; i++) {\n if (skipping[i] === null) {\n var _leaveList$i;\n\n const result =\n (_leaveList$i = leaveList[i]) === null || _leaveList$i === void 0\n ? void 0\n : _leaveList$i.apply(visitors[i], args);\n\n if (result === BREAK) {\n skipping[i] = BREAK;\n } else if (result !== undefined && result !== false) {\n return result;\n }\n } else if (skipping[i] === node) {\n skipping[i] = null;\n }\n }\n },\n };\n mergedVisitor[kind] = mergedEnterLeave;\n }\n\n return mergedVisitor;\n}\n/**\n * Given a visitor instance and a node kind, return EnterLeaveVisitor for that kind.\n */\n\nexport function getEnterLeaveForKind(visitor, kind) {\n const kindVisitor = visitor[kind];\n\n if (typeof kindVisitor === 'object') {\n // { Kind: { enter() {}, leave() {} } }\n return kindVisitor;\n } else if (typeof kindVisitor === 'function') {\n // { Kind() {} }\n return {\n enter: kindVisitor,\n leave: undefined,\n };\n } // { enter() {}, leave() {} }\n\n return {\n enter: visitor.enter,\n leave: visitor.leave,\n };\n}\n/**\n * Given a visitor instance, if it is leaving or not, and a node kind, return\n * the function the visitor runtime should call.\n *\n * @deprecated Please use `getEnterLeaveForKind` instead. Will be removed in v17\n */\n\n/* c8 ignore next 8 */\n\nexport function getVisitFn(visitor, kind, isLeaving) {\n const { enter, leave } = getEnterLeaveForKind(visitor, kind);\n return isLeaving ? leave : enter;\n}\n","import { printBlockString } from './blockString.mjs';\nimport { printString } from './printString.mjs';\nimport { visit } from './visitor.mjs';\n/**\n * Converts an AST into a string, using one set of reasonable\n * formatting rules.\n */\n\nexport function print(ast) {\n return visit(ast, printDocASTReducer);\n}\nconst MAX_LINE_LENGTH = 80;\nconst printDocASTReducer = {\n Name: {\n leave: (node) => node.value,\n },\n Variable: {\n leave: (node) => '$' + node.name,\n },\n // Document\n Document: {\n leave: (node) => join(node.definitions, '\\n\\n'),\n },\n OperationDefinition: {\n leave(node) {\n const varDefs = hasMultilineItems(node.variableDefinitions)\n ? wrap('(\\n', join(node.variableDefinitions, '\\n'), '\\n)')\n : wrap('(', join(node.variableDefinitions, ', '), ')');\n const prefix =\n wrap('', node.description, '\\n') +\n join(\n [\n node.operation,\n join([node.name, varDefs]),\n join(node.directives, ' '),\n ],\n ' ',\n ); // Anonymous queries with no directives or variable definitions can use\n // the query short form.\n\n return (prefix === 'query' ? '' : prefix + ' ') + node.selectionSet;\n },\n },\n VariableDefinition: {\n leave: ({ variable, type, defaultValue, directives, description }) =>\n wrap('', description, '\\n') +\n variable +\n ': ' +\n type +\n wrap(' = ', defaultValue) +\n wrap(' ', join(directives, ' ')),\n },\n SelectionSet: {\n leave: ({ selections }) => block(selections),\n },\n Field: {\n leave({ alias, name, arguments: args, directives, selectionSet }) {\n const prefix = wrap('', alias, ': ') + name;\n let argsLine = prefix + wrap('(', join(args, ', '), ')');\n\n if (argsLine.length > MAX_LINE_LENGTH) {\n argsLine = prefix + wrap('(\\n', indent(join(args, '\\n')), '\\n)');\n }\n\n return join([argsLine, join(directives, ' '), selectionSet], ' ');\n },\n },\n Argument: {\n leave: ({ name, value }) => name + ': ' + value,\n },\n // Fragments\n FragmentSpread: {\n leave: ({ name, directives }) =>\n '...' + name + wrap(' ', join(directives, ' ')),\n },\n InlineFragment: {\n leave: ({ typeCondition, directives, selectionSet }) =>\n join(\n [\n '...',\n wrap('on ', typeCondition),\n join(directives, ' '),\n selectionSet,\n ],\n ' ',\n ),\n },\n FragmentDefinition: {\n leave: ({\n name,\n typeCondition,\n variableDefinitions,\n directives,\n selectionSet,\n description,\n }) =>\n wrap('', description, '\\n') + // Note: fragment variable definitions are experimental and may be changed\n // or removed in the future.\n `fragment ${name}${wrap('(', join(variableDefinitions, ', '), ')')} ` +\n `on ${typeCondition} ${wrap('', join(directives, ' '), ' ')}` +\n selectionSet,\n },\n // Value\n IntValue: {\n leave: ({ value }) => value,\n },\n FloatValue: {\n leave: ({ value }) => value,\n },\n StringValue: {\n leave: ({ value, block: isBlockString }) =>\n isBlockString ? printBlockString(value) : printString(value),\n },\n BooleanValue: {\n leave: ({ value }) => (value ? 'true' : 'false'),\n },\n NullValue: {\n leave: () => 'null',\n },\n EnumValue: {\n leave: ({ value }) => value,\n },\n ListValue: {\n leave: ({ values }) => '[' + join(values, ', ') + ']',\n },\n ObjectValue: {\n leave: ({ fields }) => '{' + join(fields, ', ') + '}',\n },\n ObjectField: {\n leave: ({ name, value }) => name + ': ' + value,\n },\n // Directive\n Directive: {\n leave: ({ name, arguments: args }) =>\n '@' + name + wrap('(', join(args, ', '), ')'),\n },\n // Type\n NamedType: {\n leave: ({ name }) => name,\n },\n ListType: {\n leave: ({ type }) => '[' + type + ']',\n },\n NonNullType: {\n leave: ({ type }) => type + '!',\n },\n // Type System Definitions\n SchemaDefinition: {\n leave: ({ description, directives, operationTypes }) =>\n wrap('', description, '\\n') +\n join(['schema', join(directives, ' '), block(operationTypes)], ' '),\n },\n OperationTypeDefinition: {\n leave: ({ operation, type }) => operation + ': ' + type,\n },\n ScalarTypeDefinition: {\n leave: ({ description, name, directives }) =>\n wrap('', description, '\\n') +\n join(['scalar', name, join(directives, ' ')], ' '),\n },\n ObjectTypeDefinition: {\n leave: ({ description, name, interfaces, directives, fields }) =>\n wrap('', description, '\\n') +\n join(\n [\n 'type',\n name,\n wrap('implements ', join(interfaces, ' & ')),\n join(directives, ' '),\n block(fields),\n ],\n ' ',\n ),\n },\n FieldDefinition: {\n leave: ({ description, name, arguments: args, type, directives }) =>\n wrap('', description, '\\n') +\n name +\n (hasMultilineItems(args)\n ? wrap('(\\n', indent(join(args, '\\n')), '\\n)')\n : wrap('(', join(args, ', '), ')')) +\n ': ' +\n type +\n wrap(' ', join(directives, ' ')),\n },\n InputValueDefinition: {\n leave: ({ description, name, type, defaultValue, directives }) =>\n wrap('', description, '\\n') +\n join(\n [name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')],\n ' ',\n ),\n },\n InterfaceTypeDefinition: {\n leave: ({ description, name, interfaces, directives, fields }) =>\n wrap('', description, '\\n') +\n join(\n [\n 'interface',\n name,\n wrap('implements ', join(interfaces, ' & ')),\n join(directives, ' '),\n block(fields),\n ],\n ' ',\n ),\n },\n UnionTypeDefinition: {\n leave: ({ description, name, directives, types }) =>\n wrap('', description, '\\n') +\n join(\n ['union', name, join(directives, ' '), wrap('= ', join(types, ' | '))],\n ' ',\n ),\n },\n EnumTypeDefinition: {\n leave: ({ description, name, directives, values }) =>\n wrap('', description, '\\n') +\n join(['enum', name, join(directives, ' '), block(values)], ' '),\n },\n EnumValueDefinition: {\n leave: ({ description, name, directives }) =>\n wrap('', description, '\\n') + join([name, join(directives, ' ')], ' '),\n },\n InputObjectTypeDefinition: {\n leave: ({ description, name, directives, fields }) =>\n wrap('', description, '\\n') +\n join(['input', name, join(directives, ' '), block(fields)], ' '),\n },\n DirectiveDefinition: {\n leave: ({ description, name, arguments: args, repeatable, locations }) =>\n wrap('', description, '\\n') +\n 'directive @' +\n name +\n (hasMultilineItems(args)\n ? wrap('(\\n', indent(join(args, '\\n')), '\\n)')\n : wrap('(', join(args, ', '), ')')) +\n (repeatable ? ' repeatable' : '') +\n ' on ' +\n join(locations, ' | '),\n },\n SchemaExtension: {\n leave: ({ directives, operationTypes }) =>\n join(\n ['extend schema', join(directives, ' '), block(operationTypes)],\n ' ',\n ),\n },\n ScalarTypeExtension: {\n leave: ({ name, directives }) =>\n join(['extend scalar', name, join(directives, ' ')], ' '),\n },\n ObjectTypeExtension: {\n leave: ({ name, interfaces, directives, fields }) =>\n join(\n [\n 'extend type',\n name,\n wrap('implements ', join(interfaces, ' & ')),\n join(directives, ' '),\n block(fields),\n ],\n ' ',\n ),\n },\n InterfaceTypeExtension: {\n leave: ({ name, interfaces, directives, fields }) =>\n join(\n [\n 'extend interface',\n name,\n wrap('implements ', join(interfaces, ' & ')),\n join(directives, ' '),\n block(fields),\n ],\n ' ',\n ),\n },\n UnionTypeExtension: {\n leave: ({ name, directives, types }) =>\n join(\n [\n 'extend union',\n name,\n join(directives, ' '),\n wrap('= ', join(types, ' | ')),\n ],\n ' ',\n ),\n },\n EnumTypeExtension: {\n leave: ({ name, directives, values }) =>\n join(['extend enum', name, join(directives, ' '), block(values)], ' '),\n },\n InputObjectTypeExtension: {\n leave: ({ name, directives, fields }) =>\n join(['extend input', name, join(directives, ' '), block(fields)], ' '),\n },\n // Schema Coordinates\n TypeCoordinate: {\n leave: ({ name }) => name,\n },\n MemberCoordinate: {\n leave: ({ name, memberName }) => join([name, wrap('.', memberName)]),\n },\n ArgumentCoordinate: {\n leave: ({ name, fieldName, argumentName }) =>\n join([name, wrap('.', fieldName), wrap('(', argumentName, ':)')]),\n },\n DirectiveCoordinate: {\n leave: ({ name }) => join(['@', name]),\n },\n DirectiveArgumentCoordinate: {\n leave: ({ name, argumentName }) =>\n join(['@', name, wrap('(', argumentName, ':)')]),\n },\n};\n/**\n * Given maybeArray, print an empty string if it is null or empty, otherwise\n * print all items together separated by separator if provided\n */\n\nfunction join(maybeArray, separator = '') {\n var _maybeArray$filter$jo;\n\n return (_maybeArray$filter$jo =\n maybeArray === null || maybeArray === void 0\n ? void 0\n : maybeArray.filter((x) => x).join(separator)) !== null &&\n _maybeArray$filter$jo !== void 0\n ? _maybeArray$filter$jo\n : '';\n}\n/**\n * Given array, print each item on its own line, wrapped in an indented `{ }` block.\n */\n\nfunction block(array) {\n return wrap('{\\n', indent(join(array, '\\n')), '\\n}');\n}\n/**\n * If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string.\n */\n\nfunction wrap(start, maybeString, end = '') {\n return maybeString != null && maybeString !== ''\n ? start + maybeString + end\n : '';\n}\n\nfunction indent(str) {\n return wrap(' ', str.replace(/\\n/g, '\\n '));\n}\n\nfunction hasMultilineItems(maybeArray) {\n var _maybeArray$some;\n\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n\n /* c8 ignore next */\n return (_maybeArray$some =\n maybeArray === null || maybeArray === void 0\n ? void 0\n : maybeArray.some((str) => str.includes('\\n'))) !== null &&\n _maybeArray$some !== void 0\n ? _maybeArray$some\n : false;\n}\n","// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { TypedDocumentNode } from '@graphql-typed-document-node/core';\nimport type { TadaDocumentNode } from 'gql.tada';\nimport type { DocumentNode } from 'graphql';\nimport { print } from 'graphql';\nimport { BaseClient } from '../client/index.js';\nimport type { SuiClientTypes } from '../client/index.js';\nimport { GraphQLCoreClient } from './core.js';\nimport type { TypedDocumentString } from './generated/queries.js';\nimport { GetDynamicFieldsDocument } from './generated/queries.js';\nimport { fromBase64 } from '@mysten/utils';\nimport { normalizeStructTag } from '../utils/sui-types.js';\nimport { deriveDynamicFieldID } from '../utils/dynamic-fields.js';\nimport type { TransactionPlugin } from '../transactions/index.js';\n\nexport type GraphQLDocument<\n\tResult = Record<string, unknown>,\n\tVariables = Record<string, unknown>,\n> =\n\t| string\n\t| DocumentNode\n\t| TypedDocumentString<Result, Variables>\n\t| TypedDocumentNode<Result, Variables>\n\t| TadaDocumentNode<Result, Variables>;\n\nexport type GraphQLQueryOptions<\n\tResult = Record<string, unknown>,\n\tVariables = Record<string, unknown>,\n> = {\n\tquery: GraphQLDocument<Result, Variables>;\n\toperationName?: string;\n\textensions?: Record<string, unknown>;\n\tsignal?: AbortSignal;\n} & (Variables extends { [key: string]: never }\n\t? { variables?: Variables }\n\t: {\n\t\t\tvariables: Variables;\n\t\t});\n\nexport type GraphQLQueryResult<Result = Record<string, unknown>> = {\n\tdata?: Result;\n\terrors?: GraphQLResponseErrors;\n\textensions?: Record<string, unknown>;\n};\n\nexport type GraphQLResponseErrors = Array<{\n\tmessage: string;\n\tlocations?: { line: number; column: number }[];\n\tpath?: (string | number)[];\n}>;\n\nexport interface SuiGraphQLClientOptions<Queries extends Record<string, GraphQLDocument>> {\n\turl: string;\n\tfetch?: typeof fetch;\n\theaders?: Record<string, string>;\n\tqueries?: Queries;\n\tnetwork: SuiClientTypes.Network;\n\tmvr?: SuiClientTypes.MvrOptions;\n}\n\nexport class SuiGraphQLRequestError extends Error {}\n\nconst SUI_CLIENT_BRAND = Symbol.for('@mysten/SuiGraphQLClient') as never;\n\nexport function isSuiGraphQLClient(client: unknown): client is SuiGraphQLClient {\n\treturn (\n\t\ttypeof client === 'object' && client !== null && (client as any)[SUI_CLIENT_BRAND] === true\n\t);\n}\n\nexport interface DynamicFieldInclude {\n\tvalue?: boolean;\n}\n\nexport type DynamicFieldEntryWithValue<Include extends DynamicFieldInclude = {}> =\n\tSuiClientTypes.DynamicFieldEntry & {\n\t\tvalue: Include extends { value: true } ? SuiClientTypes.DynamicFieldValue : undefined;\n\t};\n\nexport interface ListDynamicFieldsWithValueResponse<Include extends DynamicFieldInclude = {}> {\n\thasNextPage: boolean;\n\tcursor: string | null;\n\tdynamicFields: DynamicFieldEntryWithValue<Include>[];\n}\n\nexport class SuiGraphQLClient<Queries extends Record<string, GraphQLDocument> = {}>\n\textends BaseClient\n\timplements SuiClientTypes.TransportMethods\n{\n\t#url: string;\n\t#queries: Queries;\n\t#headers: Record<string, string>;\n\t#fetch: typeof fetch;\n\tcore: GraphQLCoreClient;\n\tget mvr(): SuiClientTypes.MvrMethods {\n\t\treturn this.core.mvr;\n\t}\n\n\tget [SUI_CLIENT_BRAND]() {\n\t\treturn true;\n\t}\n\n\tconstructor({\n\t\turl,\n\t\tfetch: fetchFn = fetch,\n\t\theaders = {},\n\t\tqueries = {} as Queries,\n\t\tnetwork,\n\t\tmvr,\n\t}: SuiGraphQLClientOptions<Queries>) {\n\t\tsuper({\n\t\t\tnetwork,\n\t\t});\n\t\tthis.#url = url;\n\t\tthis.#queries = queries;\n\t\tthis.#headers = headers;\n\t\tthis.#fetch = (...args) => fetchFn(...args);\n\t\tthis.core = new GraphQLCoreClient({\n\t\t\tgraphqlClient: this,\n\t\t\tmvr,\n\t\t});\n\t}\n\n\tasync query<Result = Record<string, unknown>, Variables = Record<string, unknown>>(\n\t\toptions: GraphQLQueryOptions<Result, Variables>,\n\t): Promise<GraphQLQueryResult<Result>> {\n\t\tconst res = await this.#fetch(this.#url, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t...this.#headers,\n\t\t\t},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tquery:\n\t\t\t\t\ttypeof options.query === 'string' || options.query instanceof String\n\t\t\t\t\t\t? String(options.query)\n\t\t\t\t\t\t: print(options.query),\n\t\t\t\tvariables: options.variables,\n\t\t\t\textensions: options.extensions,\n\t\t\t\toperationName: options.operationName,\n\t\t\t}),\n\t\t\tsignal: options.signal,\n\t\t});\n\n\t\tif (!res.ok) {\n\t\t\tthrow new SuiGraphQLRequestError(`GraphQL request failed: ${res.statusText} (${res.status})`);\n\t\t}\n\n\t\treturn await res.json();\n\t}\n\n\tasync execute<\n\t\tconst Query extends Extract<keyof Queries, string>,\n\t\tResult = Queries[Query] extends GraphQLDocument<infer R, unknown> ? R : Record<string, unknown>,\n\t\tVariables = Queries[Query] extends GraphQLDocument<unknown, infer V>\n\t\t\t? V\n\t\t\t: Record<string, unknown>,\n\t>(\n\t\tquery: Query,\n\t\toptions: Omit<GraphQLQueryOptions<Result, Variables>, 'query'>,\n\t): Promise<GraphQLQueryResult<Result>> {\n\t\treturn this.query({\n\t\t\t...(options as { variables: Record<string, unknown> }),\n\t\t\tquery: this.#queries[query]!,\n\t\t}) as Promise<GraphQLQueryResult<Result>>;\n\t}\n\n\tgetObjects<Include extends SuiClientTypes.ObjectInclude = {}>(\n\t\tinput: SuiClientTypes.GetObjectsOptions<Include>,\n\t): Promise<SuiClientTypes.GetObjectsResponse<Include>> {\n\t\treturn this.core.getObjects(input);\n\t}\n\n\tgetObject<Include extends SuiClientTypes.ObjectInclude = {}>(\n\t\tinput: SuiClientTypes.GetObjectOptions<Include>,\n\t): Promise<SuiClientTypes.GetObjectResponse<Include>> {\n\t\treturn this.core.getObject(input);\n\t}\n\n\tlistCoins(input: SuiClientTypes.ListCoinsOptions): Promise<SuiClientTypes.ListCoinsResponse> {\n\t\treturn this.core.listCoins(input);\n\t}\n\n\tlistOwnedObjects<Include extends SuiClientTypes.ObjectInclude = {}>(\n\t\tinput: SuiClientTypes.ListOwnedObjectsOptions<Include>,\n\t): Promise<SuiClientTypes.ListOwnedObjectsResponse<Include>> {\n\t\treturn this.core.listOwnedObjects(input);\n\t}\n\n\tgetBalance(input: SuiClientTypes.GetBalanceOptions): Promise<SuiClientTypes.GetBalanceResponse> {\n\t\treturn this.core.getBalance(input);\n\t}\n\n\tlistBalances(\n\t\tinput: SuiClientTypes.ListBalancesOptions,\n\t): Promise<SuiClientTypes.ListBalancesResponse> {\n\t\treturn this.core.listBalances(input);\n\t}\n\n\tgetCoinMetadata(\n\t\tinput: SuiClientTypes.GetCoinMetadataOptions,\n\t): Promise<SuiClientTypes.GetCoinMetadataResponse> {\n\t\treturn this.core.getCoinMetadata(input);\n\t}\n\n\tgetTransaction<Include extends SuiClientTypes.TransactionInclude = {}>(\n\t\tinput: SuiClientTypes.GetTransactionOptions<Include>,\n\t): Promise<SuiClientTypes.TransactionResult<Include>> {\n\t\treturn this.core.getTransaction(input);\n\t}\n\n\texecuteTransaction<Include extends SuiClientTypes.TransactionInclude = {}>(\n\t\tinput: SuiClientTypes.ExecuteTransactionOptions<Include>,\n\t): Promise<SuiClientTypes.TransactionResult<Include>> {\n\t\treturn this.core.executeTransaction(input);\n\t}\n\n\tsignAndExecuteTransaction<Include extends SuiClientTypes.TransactionInclude = {}>(\n\t\tinput: SuiClientTypes.SignAndExecuteTransactionOptions<Include>,\n\t): Promise<SuiClientTypes.TransactionResult<Include>> {\n\t\treturn this.core.signAndExecuteTransaction(input);\n\t}\n\n\twaitForTransaction<Include extends SuiClientTypes.TransactionInclude = {}>(\n\t\tinput: SuiClientTypes.WaitForTransactionOptions<Include>,\n\t): Promise<SuiClientTypes.TransactionResult<Include>> {\n\t\treturn this.core.waitForTransaction(input);\n\t}\n\n\tsimulateTransaction<Include extends SuiClientTypes.SimulateTransactionInclude = {}>(\n\t\tinput: SuiClientTypes.SimulateTransactionOptions<Include>,\n\t): Promise<SuiClientTypes.SimulateTransactionResult<Include>> {\n\t\treturn this.core.simulateTransaction(input);\n\t}\n\n\tgetReferenceGasPrice(): Promise<SuiClientTypes.GetReferenceGasPriceResponse> {\n\t\treturn this.core.getReferenceGasPrice();\n\t}\n\n\tasync listDynamicFields<Include extends DynamicFieldInclude = {}>(\n\t\tinput: SuiClientTypes.ListDynamicFieldsOptions & { include?: Include & DynamicFieldInclude },\n\t): Promise<ListDynamicFieldsWithValueResponse<Include>> {\n\t\tconst includeValue = input.include?.value ?? false;\n\n\t\tconst { data, errors } = await this.query({\n\t\t\tquery: GetDynamicFieldsDocument,\n\t\t\tvariables: {\n\t\t\t\tparentId: input.parentId,\n\t\t\t\tfirst: input.limit,\n\t\t\t\tcursor: input.cursor,\n\t\t\t\tincludeValue,\n\t\t\t},\n\t\t});\n\n\t\tif (errors?.length) {\n\t\t\tthrow errors.length === 1\n\t\t\t\t? new Error(errors[0].message)\n\t\t\t\t: new AggregateError(errors.map((e) => new Error(e.message)));\n\t\t}\n\n\t\tconst result = data?.address?.dynamicFields;\n\t\tif (!result) {\n\t\t\tthrow new Error('Missing response data');\n\t\t}\n\n\t\treturn {\n\t\t\tdynamicFields: result.nodes.map((dynamicField): DynamicFieldEntryWithValue<Include> => {\n\t\t\t\tconst valueType =\n\t\t\t\t\tdynamicField.value?.__typename === 'MoveObject'\n\t\t\t\t\t\t? dynamicField.value.contents?.type?.repr!\n\t\t\t\t\t\t: dynamicField.value?.type?.repr!;\n\t\t\t\tconst isDynamicObject = dynamicField.value?.__typename === 'MoveObject';\n\t\t\t\tconst derivedNameType = isDynamicObject\n\t\t\t\t\t? `0x2::dynamic_object_field::Wrapper<${dynamicField.name?.type?.repr}>`\n\t\t\t\t\t: dynamicField.name?.type?.repr!;\n\n\t\t\t\tlet value: SuiClientTypes.DynamicFieldValue | undefined;\n\t\t\t\tif (includeValue) {\n\t\t\t\t\tlet valueBcs: Uint8Array;\n\t\t\t\t\tif (dynamicField.value?.__typename === 'MoveValue') {\n\t\t\t\t\t\tvalueBcs = fromBase64(dynamicField.value.bcs ?? '');\n\t\t\t\t\t} else if (dynamicField.value?.__typename === 'MoveObject') {\n\t\t\t\t\t\tvalueBcs = fromBase64(dynamicField.value.contents?.bcs ?? '');\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvalueBcs = new Uint8Array();\n\t\t\t\t\t}\n\t\t\t\t\tvalue = { type: valueType, bcs: valueBcs };\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\t$kind: isDynamicObject ? 'DynamicObject' : 'DynamicField',\n\t\t\t\t\tfieldId: deriveDynamicFieldID(\n\t\t\t\t\t\tinput.parentId,\n\t\t\t\t\t\tderivedNameType,\n\t\t\t\t\t\tfromBase64(dynamicField.name?.bcs!),\n\t\t\t\t\t),\n\t\t\t\t\ttype: normalizeStructTag(\n\t\t\t\t\t\tisDynamicObject\n\t\t\t\t\t\t\t? `0x2::dynamic_field::Field<0x2::dynamic_object_field::Wrapper<${dynamicField.name?.type?.repr}>,0x2::object::ID>`\n\t\t\t\t\t\t\t: `0x2::dynamic_field::Field<${dynamicField.name?.type?.repr},${valueType}>`,\n\t\t\t\t\t),\n\t\t\t\t\tname: {\n\t\t\t\t\t\ttype: dynamicField.name?.type?.repr!,\n\t\t\t\t\t\tbcs: fromBase64(dynamicField.name?.bcs!),\n\t\t\t\t\t},\n\t\t\t\t\tvalueType,\n\t\t\t\t\tchildId:\n\t\t\t\t\t\tisDynamicObject && dynamicField.value?.__typename === 'MoveObject'\n\t\t\t\t\t\t\t? dynamicField.value.address\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\tvalue: (includeValue ? value : undefined) as DynamicFieldEntryWithValue<Include>['value'],\n\t\t\t\t} as DynamicFieldEntryWithValue<Include>;\n\t\t\t}),\n\t\t\tcursor: result.pageInfo.endCursor ?? null,\n\t\t\thasNextPage: result.pageInfo.hasNextPage,\n\t\t};\n\t}\n\n\tgetDynamicField(\n\t\tinput: SuiClientTypes.GetDynamicFieldOptions,\n\t): Promise<SuiClientTypes.GetDynamicFieldResponse> {\n\t\treturn this.core.getDynamicField(input);\n\t}\n\n\tgetMoveFunction(\n\t\tinput: SuiClientTypes.GetMoveFunctionOptions,\n\t): Promise<SuiClientTypes.GetMoveFunctionResponse> {\n\t\treturn this.core.getMoveFunction(input);\n\t}\n\n\tresolveTransactionPlugin(): TransactionPlugin {\n\t\treturn this.core.resolveTransactionPlugin();\n\t}\n\n\tverifyZkLoginSignature(\n\t\tinput: SuiClientTypes.VerifyZkLoginSignatureOptions,\n\t): Promise<SuiClientTypes.ZkLoginVerifyResponse> {\n\t\treturn this.core.verifyZkLoginSignature(input);\n\t}\n\n\tdefaultNameServiceName(\n\t\tinput: SuiClientTypes.DefaultNameServiceNameOptions,\n\t): Promise<SuiClientTypes.DefaultNameServiceNameResponse> {\n\t\treturn this.core.defaultNameServiceName(input);\n\t}\n}\n","// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { bcs } from '../bcs/index.js';\n\nexport type IntentScope = Exclude<keyof typeof bcs.IntentScope.$inferType, '$kind'>;\n/**\n * Inserts a domain separator for a message that is being signed\n */\nexport function messageWithIntent(scope: IntentScope, message: Uint8Array) {\n\treturn bcs\n\t\t.IntentMessage(bcs.bytes(message.length))\n\t\t.serialize({\n\t\t\tintent: {\n\t\t\t\tscope: { [scope as 'PersonalMessage']: true },\n\t\t\t\tversion: { V0: true },\n\t\t\t\tappId: { Sui: true },\n\t\t\t},\n\t\t\tvalue: message,\n\t\t})\n\t\t.toBytes();\n}\n","// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fromBase64, toBase64 } from '@mysten/bcs';\nimport { blake2b } from '@noble/hashes/blake2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\n\nimport { bcs } from '../bcs/index.js';\nimport { normalizeSuiAddress, SUI_ADDRESS_LENGTH } from '../utils/sui-types.js';\nimport type { IntentScope } from './intent.js';\nimport { messageWithIntent } from './intent.js';\nimport { SIGNATURE_FLAG_TO_SCHEME, SIGNATURE_SCHEME_TO_SIZE } from './signature-scheme.js';\n\n/**\n * Value to be converted into public key.\n */\nexport type PublicKeyInitData = string | Uint8Array | Iterable<number>;\n\nexport function bytesEqual(a: Uint8Array, b: Uint8Array) {\n\tif (a === b) return true;\n\n\tif (a.length !== b.length) {\n\t\treturn false;\n\t}\n\n\tfor (let i = 0; i < a.length; i++) {\n\t\tif (a[i] !== b[i]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/**\n * A public key\n */\nexport abstract class PublicKey {\n\t/**\n\t * Checks if two public keys are equal\n\t */\n\tequals(publicKey: PublicKey) {\n\t\treturn bytesEqual(this.toRawBytes(), publicKey.toRawBytes());\n\t}\n\n\t/**\n\t * Return the base-64 representation of the public key\n\t */\n\ttoBase64() {\n\t\treturn toBase64(this.toRawBytes());\n\t}\n\n\ttoString(): never {\n\t\tthrow new Error(\n\t\t\t'`toString` is not implemented on public keys. Use `toBase64()` or `toRawBytes()` instead.',\n\t\t);\n\t}\n\n\t/**\n\t * Return the Sui representation of the public key encoded in\n\t * base-64. A Sui public key is formed by the concatenation\n\t * of the scheme flag with the raw bytes of the public key\n\t */\n\ttoSuiPublicKey(): string {\n\t\tconst bytes = this.toSuiBytes();\n\t\treturn toBase64(bytes);\n\t}\n\n\tverifyWithIntent(\n\t\tbytes: Uint8Array,\n\t\tsignature: Uint8Array | string,\n\t\tintent: IntentScope,\n\t): Promise<boolean> {\n\t\tconst intentMessage = messageWithIntent(intent, bytes);\n\t\tconst digest = blake2b(intentMessage, { dkLen: 32 });\n\n\t\treturn this.verify(digest, signature);\n\t}\n\n\t/**\n\t * Verifies that the signature is valid for for the provided PersonalMessage\n\t */\n\tverifyPersonalMessage(message: Uint8Array, signature: Uint8Array | string): Promise<boolean> {\n\t\treturn this.verifyWithIntent(\n\t\t\tbcs.byteVector().serialize(message).toBytes(),\n\t\t\tsignature,\n\t\t\t'PersonalMessage',\n\t\t);\n\t}\n\n\t/**\n\t * Verifies that the signature is valid for for the provided Transaction\n\t */\n\tverifyTransaction(transaction: Uint8Array, signature: Uint8Array | string): Promise<boolean> {\n\t\treturn this.verifyWithIntent(transaction, signature, 'TransactionData');\n\t}\n\n\t/**\n\t * Verifies that the public key is associated with the provided address\n\t */\n\tverifyAddress(address: string): boolean {\n\t\treturn this.toSuiAddress() === address;\n\t}\n\n\t/**\n\t * Returns the bytes representation of the public key\n\t * prefixed with the signature scheme flag\n\t */\n\ttoSuiBytes(): Uint8Array<ArrayBuffer> {\n\t\tconst rawBytes = this.toRawBytes();\n\t\tconst suiBytes = new Uint8Array(rawBytes.length + 1);\n\t\tsuiBytes.set([this.flag()]);\n\t\tsuiBytes.set(rawBytes, 1);\n\n\t\treturn suiBytes;\n\t}\n\n\t/**\n\t * Return the Sui address associated with this Ed25519 public key\n\t */\n\ttoSuiAddress(): string {\n\t\t// Each hex char represents half a byte, hence hex address doubles the length\n\t\treturn normalizeSuiAddress(\n\t\t\tbytesToHex(blake2b(this.toSuiBytes(), { dkLen: 32 })).slice(0, SUI_ADDRESS_LENGTH * 2),\n\t\t);\n\t}\n\n\t/**\n\t * Return the byte array representation of the public key\n\t */\n\tabstract toRawBytes(): Uint8Array<ArrayBuffer>;\n\n\t/**\n\t * Return signature scheme flag of the public key\n\t */\n\tabstract flag(): number;\n\n\t/**\n\t * Verifies that the signature is valid for for the provided message\n\t */\n\tabstract verify(data: Uint8Array, signature: Uint8Array | string): Promise<boolean>;\n}\n\nexport function parseSerializedKeypairSignature(serializedSignature: string) {\n\tconst bytes = fromBase64(serializedSignature);\n\n\tconst signatureScheme =\n\t\tSIGNATURE_FLAG_TO_SCHEME[bytes[0] as keyof typeof SIGNATURE_FLAG_TO_SCHEME];\n\n\tswitch (signatureScheme) {\n\t\tcase 'ED25519':\n\t\tcase 'Secp256k1':\n\t\tcase 'Secp256r1':\n\t\t\tconst size =\n\t\t\t\tSIGNATURE_SCHEME_TO_SIZE[signatureScheme as keyof typeof SIGNATURE_SCHEME_TO_SIZE];\n\t\t\tconst signature = bytes.slice(1, bytes.length - size);\n\t\t\tconst publicKey = bytes.slice(1 + signature.length);\n\n\t\t\treturn {\n\t\t\t\tserializedSignature,\n\t\t\t\tsignatureScheme,\n\t\t\t\tsignature,\n\t\t\t\tpublicKey,\n\t\t\t\tbytes,\n\t\t\t};\n\t\tdefault:\n\t\t\tthrow new Error('Unsupported signature scheme');\n\t}\n}\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://www.rfc-editor.org/rfc/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal 32-byte base SHA2 hash class. */\nabstract class SHA2_32B<T extends SHA2_32B<T>> extends HashMD<T> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA2-256 hash class. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA2-224 hash class. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal 64-byte base SHA2 hash class. */\nabstract class SHA2_64B<T extends SHA2_64B<T>> extends HashMD<T> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/** Internal SHA2-512 hash class. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA2-384 hash class. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA2-512/224 hash class. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\n/** Internal SHA2-512/256 hash class. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n */\nexport const sha256: CHash<_SHA256> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash<_SHA224> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash<_SHA512> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash<_SHA384> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash<_SHA512_256> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash<_SHA512_224> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n anumber,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n} from '@noble/hashes/utils.js';\nexport {\n abytes,\n anumber,\n bytesToHex,\n concatBytes,\n hexToBytes,\n isBytes,\n randomBytes,\n} from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\nexport type CHash = {\n (message: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array) => Uint8Array;\nexport function abool(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n// Used in weierstrass, der\nfunction abignumber(n: number | bigint) {\n if (typeof n === 'bigint') {\n if (!isPosBig(n)) throw new Error('positive bigint expected, got ' + n);\n } else anumber(n);\n return n;\n}\n\nexport function asafenumber(value: number, title: string = ''): void {\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected safe integer, got type=' + typeof value);\n }\n}\n\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex_(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n anumber(len);\n n = abignumber(n);\n const res = hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n if (res.length !== len) throw new Error('number too large');\n return res;\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes_(numberToHexUnpadded(abignumber(n)));\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return Uint8Array.from(bytes);\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n */\nexport function asciiToBytes(ascii: string): Uint8Array {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n });\n}\n\n// Is positive bigint\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\ntype Pred<T> = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, message: Uint8Array) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n anumber(hashLen, 'hashLen');\n anumber(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n const u8n = (len: number): Uint8Array => new Uint8Array(len); // creates Uint8Array\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...msgs: Uint8Array[]) => hmacFn(k, concatBytes_(v, ...msgs)); // hmac(k)(v, ...values)\n const reseed = (seed: Uint8Array = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= _maxDrbgIters) throw new Error('drbg: tried max amount of iterations');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes_(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\nexport function validateObject(\n object: Record<string, any>,\n fields: Record<string, string> = {},\n optFields: Record<string, string> = {}\n): void {\n if (!object || typeof object !== 'object') throw new Error('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f: typeof fields, isOpt: boolean) =>\n Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized<T extends object, R, O extends any[]>(\n fn: (arg: T, ...args: O) => R\n): (arg: T, ...args: O) => R {\n const map = new WeakMap<T, R>();\n return (arg: T, ...args: O): R => {\n const val = map.get(arg);\n if (val !== undefined) return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n\nexport interface CryptoKeys {\n lengths: { seed?: number; public?: number; secret?: number };\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Uint8Array) => Uint8Array;\n}\n\n/** Generic interface for signatures. Has keygen, sign and verify. */\nexport interface Signer extends CryptoKeys {\n // Interfaces are fun. We cannot just add new fields without copying old ones.\n lengths: {\n seed?: number;\n public?: number;\n secret?: number;\n signRand?: number;\n signature?: number;\n };\n sign: (msg: Uint8Array, secretKey: Uint8Array) => Uint8Array;\n verify: (sig: Uint8Array, msg: Uint8Array, publicKey: Uint8Array) => boolean;\n}\n","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes,\n anumber,\n bytesToNumberBE,\n bytesToNumberLE,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from '../utils.ts';\n\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _16n = /* @__PURE__ */ BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\n}\n\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n) throw new Error('invert: expected non-zero number');\n if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\nfunction assertIsSquare<T>(Fp: IField<T>, root: T, n: T): void {\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4<T>(Fp: IField<T>, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\n\nfunction sqrt5mod8<T>(Fp: IField<T>, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n assertIsSquare(Fp, root, n);\n return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));// 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return <T>(Fp: IField<T>, n: T) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3);// 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: IField<T>, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n) return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint): boolean =>\n (mod(num, modulo) & _1n) === _1n;\n\n/** Field is not always over prime: for example, Fp2 has ORDER(q)=p^m. */\nexport interface IField<T> {\n ORDER: bigint;\n BYTES: number;\n BITS: number;\n isLE: boolean;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n isValidNot0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n // legendre?(num: T): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array, skipValidation?: boolean): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField<T>(field: IField<T>): IField<T> {\n const initial = {\n ORDER: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow<T>(Fp: IField<T>, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch<T>(Fp: IField<T>, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv<T>(Fp: IField<T>, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n */\nexport function FpLegendre<T>(Fp: IField<T>, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare<T>(Fp: IField<T>, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\nexport type NLength = { nByteLength: number; nBitLength: number };\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number): NLength {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n isLE: boolean;\n BITS: number;\n sqrt: SqrtFn;\n allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes)\n modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n}>;\nclass _Field implements IField<bigint> {\n readonly ORDER: bigint;\n readonly BITS: number;\n readonly BYTES: number;\n readonly isLE: boolean;\n readonly ZERO = _0n;\n readonly ONE = _1n;\n readonly _lengths?: number[];\n private _sqrt: ReturnType<typeof FpSqrt> | undefined; // cached sqrt\n private readonly _mod?: boolean;\n constructor(ORDER: bigint, opts: FieldOpts = {}) {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength: number | undefined = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n if (typeof opts.BITS === 'number') _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function') this.sqrt = opts.sqrt;\n if (typeof opts.isLE === 'boolean') this.isLE = opts.isLE;\n if (opts.allowedLengths) this._lengths = opts.allowedLengths?.slice();\n if (typeof opts.modFromBytes === 'boolean') this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n this._sqrt = undefined;\n Object.preventExtensions(this);\n }\n\n create(num: bigint) {\n return mod(num, this.ORDER);\n }\n isValid(num: bigint) {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num: bigint) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num: bigint) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num: bigint) {\n return (num & _1n) === _1n;\n }\n neg(num: bigint) {\n return mod(-num, this.ORDER);\n }\n eql(lhs: bigint, rhs: bigint) {\n return lhs === rhs;\n }\n\n sqr(num: bigint) {\n return mod(num * num, this.ORDER);\n }\n add(lhs: bigint, rhs: bigint) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs: bigint, rhs: bigint) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs: bigint, rhs: bigint) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num: bigint, power: bigint): bigint {\n return FpPow(this, num, power);\n }\n div(lhs: bigint, rhs: bigint) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n\n // Same as above, but doesn't normalize\n sqrN(num: bigint) {\n return num * num;\n }\n addN(lhs: bigint, rhs: bigint) {\n return lhs + rhs;\n }\n subN(lhs: bigint, rhs: bigint) {\n return lhs - rhs;\n }\n mulN(lhs: bigint, rhs: bigint) {\n return lhs * rhs;\n }\n\n inv(num: bigint) {\n return invert(num, this.ORDER);\n }\n sqrt(num: bigint): bigint {\n // Caching _sqrt speeds up sqrt9mod16 by 5x and tonneli-shanks by 10%\n if (!this._sqrt) this._sqrt = FpSqrt(this.ORDER);\n return this._sqrt(this, num);\n }\n toBytes(num: bigint) {\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes: Uint8Array, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error(\n 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n );\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes) scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst: bigint[]): bigint[] {\n return FpInvertBatch(this, lst);\n }\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov(a: bigint, b: bigint, condition: boolean) {\n return condition ? b : a;\n }\n}\n\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER: bigint, opts: FieldOpts = {}): Readonly<FpField> {\n return new _Field(ORDER, opts);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\n\nexport function FpSqrtOdd<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.Point.Fn.ORDER)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n abytes(key);\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, type Signer } from '../utils.ts';\nimport { Field, FpInvertBatch, validateField, type IField } from './modular.ts';\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\nexport type AffinePoint<T> = {\n x: T;\n y: T;\n} & { Z?: never };\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic curve Points. */\nexport interface CurvePoint<F, P extends CurvePoint<F, P>> {\n /** Affine x coordinate. Different from projective / extended X coordinate. */\n x: F;\n /** Affine y coordinate. Different from projective / extended Y coordinate. */\n y: F;\n Z?: F;\n double(): P;\n negate(): P;\n add(other: P): P;\n subtract(other: P): P;\n equals(other: P): boolean;\n multiply(scalar: bigint): P;\n assertValidity(): void;\n clearCofactor(): P;\n is0(): boolean;\n isTorsionFree(): boolean;\n isSmallOrder(): boolean;\n multiplyUnsafe(scalar: bigint): P;\n /**\n * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n * @param isLazy calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n */\n precompute(windowSize?: number, isLazy?: boolean): P;\n /** Converts point to 2D xy affine coordinates */\n toAffine(invertedZ?: F): AffinePoint<F>;\n toBytes(): Uint8Array;\n toHex(): string;\n}\n\n/** Base interface for all elliptic curve Point constructors. */\nexport interface CurvePointCons<P extends CurvePoint<any, P>> {\n [Symbol.hasInstance]: (item: unknown) => boolean;\n BASE: P;\n ZERO: P;\n /** Field for basic curve math */\n Fp: IField<P_F<P>>;\n /** Scalar field, for scalars in multiply and others */\n Fn: IField<bigint>;\n /** Creates point from x, y. Does NOT validate if the point is valid. Use `.assertValidity()`. */\n fromAffine(p: AffinePoint<P_F<P>>): P;\n fromBytes(bytes: Uint8Array): P;\n fromHex(hex: string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint<PC>': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint<PC>': it won't be accesible for arguments/return types\n// * `CurvePointCons<P extends CurvePoint<any, P>>` constraints from interface definition\n// won't propagate, if `PC extends CurvePointCons<any>`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint<any, P>.\n// this means we need to do stuff like\n// `function test<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(`\n// if we want type safety around P, otherwise PC_P<PC> will be any\n\n/** Returns Fp type from Point (P_F<P> == P.F) */\nexport type P_F<P extends CurvePoint<any, P>> = P extends CurvePoint<infer F, P> ? F : never;\n/** Returns Fp type from PointCons (PC_F<PC> == PC.P.F) */\nexport type PC_F<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['Fp']['ZERO'];\n/** Returns Point type from PointCons (PC_P<PC> == PC.P) */\nexport type PC_P<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons<CurvePoint<any, any>>`, will return `any` after 1 operation\n// * `CurvePointCons<any>: WeierstrassPointCons<bigint> extends CurvePointCons<any> = false`\n// * `P extends CurvePoint, PC extends CurvePointCons<P>`\n// * It can't infer P from PC alone\n// * Too many relations between F, P & PC\n// * It will infer P/F if `arg: CurvePointCons<F, P>`, but will fail if PC is generic\n// * It will work correctly if there is an additional argument of type P\n// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n// types, making them un-inferable\n// prettier-ignore\nexport type PC_ANY = CurvePointCons<\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any, any>\n >>>>>>>>>\n>;\n\nexport interface CurveLengths {\n secretKey?: number;\n publicKey?: number;\n publicKeyUncompressed?: number;\n publicKeyHasPrefix?: boolean;\n signature?: number;\n seed?: number;\n}\n\nexport type Mapper<T> = (i: T[]) => T[];\n\nexport function negateCt<T extends { negate: () => T }>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\n}\n\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\nexport function normalizeZ<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[]\n): P[] {\n const invertedZs = FpInvertBatch(\n c.Fp,\n points.map((p) => p.Z!)\n );\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\n\nfunction validateW(W: number, bits: number) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\n/** Internal wNAF opts for specific W and scalarBits */\ntype WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n if (!Array.isArray(points)) throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap<any, any[]>();\nconst pointWindowSizes = new WeakMap<any, number>();\n\nfunction getW(P: any): number {\n // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF<PC extends PC_ANY> {\n private readonly BASE: PC_P<PC>;\n private readonly ZERO: PC_P<PC>;\n private readonly Fn: PC['Fn'];\n readonly bits: number;\n\n // Parametrized with a given Point class (not individual point)\n constructor(Point: PC, bits: number) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n\n // non-const time multiplication ladder\n _unsafeLadder(elm: PC_P<PC>, n: bigint, p: PC_P<PC> = this.ZERO): PC_P<PC> {\n let d: PC_P<PC> = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n private precomputeWindow(point: PC_P<PC>, W: number): PC_P<PC>[] {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points: PC_P<PC>[] = [];\n let p: PC_P<PC> = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n private wNAF(W: number, precomputes: PC_P<PC>[], n: bigint): { p: PC_P<PC>; f: PC_P<PC> } {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points: JIT won't eliminate f.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n }\n\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n private wNAFUnsafe(\n W: number,\n precomputes: PC_P<PC>[],\n n: bigint,\n acc: PC_P<PC> = this.ZERO\n ): PC_P<PC> {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n\n private getPrecomputes(W: number, point: PC_P<PC>, transform?: Mapper<PC_P<PC>>): PC_P<PC>[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W) as PC_P<PC>[];\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function') comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n\n cached(\n point: PC_P<PC>,\n scalar: bigint,\n transform?: Mapper<PC_P<PC>>\n ): { p: PC_P<PC>; f: PC_P<PC> } {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n\n unsafe(point: PC_P<PC>, scalar: bigint, transform?: Mapper<PC_P<PC>>, prev?: PC_P<PC>): PC_P<PC> {\n const W = getW(point);\n if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P: PC_P<PC>, W: number): void {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n\n hasCache(elm: PC_P<PC>): boolean {\n return getW(elm) !== 1;\n }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n Point: PC,\n point: P,\n k1: bigint,\n k2: bigint\n): { p1: P; p2: P } {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) p1 = p1.add(acc);\n if (k2 & _1n) p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka secret keys / bigints)\n */\nexport function pippenger<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[],\n scalars: bigint[]\n): P {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as P;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[],\n windowSize: number\n): (scalars: bigint[]) => P {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n const fieldN = c.Fn;\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p: P) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars: bigint[]): P => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr) continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n\nexport type ValidCurveParams<T> = {\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b?: T;\n d?: T;\n Gx: T;\n Gy: T;\n};\n\nfunction createField<T>(order: bigint, field?: IField<T>, isLE?: boolean): IField<T> {\n if (field) {\n if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n } else {\n return Field(order, { isLE }) as unknown as IField<T>;\n }\n}\nexport type FpFn<T> = { Fp: IField<T>; Fn: IField<bigint> };\n\n/** Validates CURVE opts and creates fields */\nexport function createCurveFields<T>(\n type: 'weierstrass' | 'edwards',\n CURVE: ValidCurveParams<T>,\n curveOpts: Partial<FpFn<T>> = {},\n FpFnLE?: boolean\n): FpFn<T> & { CURVE: ValidCurveParams<T> } {\n if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h'] as const) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b] as const;\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n\ntype KeygenFn = (\n seed?: Uint8Array,\n isCompressed?: boolean\n) => { secretKey: Uint8Array; publicKey: Uint8Array };\nexport function createKeygen(\n randomSecretKey: Function,\n getPublicKey: Signer['getPublicKey']\n): KeygenFn {\n return function keygen(seed?: Uint8Array) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n };\n}\n","/**\n * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².\n * For design rationale of types / exports, see weierstrass module documentation.\n * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abool,\n abytes,\n aInRange,\n bytesToHex,\n bytesToNumberLE,\n concatBytes,\n copyBytes,\n hexToBytes,\n isBytes,\n memoized,\n notImplemented,\n validateObject,\n randomBytes as wcRandomBytes,\n type FHash,\n type Signer,\n} from '../utils.ts';\nimport {\n createCurveFields,\n createKeygen,\n normalizeZ,\n wNAF,\n type AffinePoint,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport { type IField } from './modular.ts';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n\n/** Instance of Extended Point with coordinates in X, Y, Z, T. */\nexport interface EdwardsPoint extends CurvePoint<bigint, EdwardsPoint> {\n /** extended X coordinate. Different from affine x. */\n readonly X: bigint;\n /** extended Y coordinate. Different from affine y. */\n readonly Y: bigint;\n /** extended Z coordinate */\n readonly Z: bigint;\n /** extended T coordinate */\n readonly T: bigint;\n}\n/** Static methods of Extended Point with coordinates in X, Y, Z, T. */\nexport interface EdwardsPointCons extends CurvePointCons<EdwardsPoint> {\n new (X: bigint, Y: bigint, Z: bigint, T: bigint): EdwardsPoint;\n CURVE(): EdwardsOpts;\n fromBytes(bytes: Uint8Array, zip215?: boolean): EdwardsPoint;\n fromHex(hex: string, zip215?: boolean): EdwardsPoint;\n}\n\n/**\n * Twisted Edwards curve options.\n *\n * * a: formula param\n * * d: formula param\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor. h*n is group order; n is subgroup order\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type EdwardsOpts = Readonly<{\n p: bigint;\n n: bigint;\n h: bigint;\n a: bigint;\n d: bigint;\n Gx: bigint;\n Gy: bigint;\n}>;\n\n/**\n * Extra curve options for Twisted Edwards.\n *\n * * Fp: redefined Field over curve.p\n * * Fn: redefined Field over curve.n\n * * uvRatio: helper function for decompression, calculating √(u/v)\n */\nexport type EdwardsExtraOpts = Partial<{\n Fp: IField<bigint>;\n Fn: IField<bigint>;\n FpFnLE: boolean;\n uvRatio: (u: bigint, v: bigint) => { isValid: boolean; value: bigint };\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) options.\n *\n * * hash: hash function used to hash secret keys and messages\n * * adjustScalarBytes: clears bits to get valid field element\n * * domain: Used for hashing\n * * mapToCurve: for hash-to-curve standard\n * * prehash: RFC 8032 pre-hashing of messages to sign() / verify()\n * * randomBytes: function generating random bytes, used for randomSecretKey\n */\nexport type EdDSAOpts = Partial<{\n adjustScalarBytes: (bytes: Uint8Array) => Uint8Array;\n domain: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;\n mapToCurve: (scalar: bigint[]) => AffinePoint<bigint>;\n prehash: FHash;\n randomBytes: (bytesLength?: number) => Uint8Array;\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) interface.\n *\n * Allows to create and verify signatures, create public and secret keys.\n */\nexport interface EdDSA {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Uint8Array) => Uint8Array;\n sign: (\n message: Uint8Array,\n secretKey: Uint8Array,\n options?: { context?: Uint8Array }\n ) => Uint8Array;\n verify: (\n sig: Uint8Array,\n message: Uint8Array,\n publicKey: Uint8Array,\n options?: { context?: Uint8Array; zip215: boolean }\n ) => boolean;\n Point: EdwardsPointCons;\n utils: {\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n isValidSecretKey: (secretKey: Uint8Array) => boolean;\n isValidPublicKey: (publicKey: Uint8Array, zip215?: boolean) => boolean;\n\n /**\n * Converts ed public key to x public key.\n *\n * There is NO `fromMontgomery`:\n * - There are 2 valid ed25519 points for every x25519, with flipped coordinate\n * - Sometimes there are 0 valid ed25519 points, because x25519 *additionally*\n * accepts inputs on the quadratic twist, which can't be moved to ed25519\n *\n * @example\n * ```js\n * const someonesPub_ed = ed25519.getPublicKey(ed25519.utils.randomSecretKey());\n * const someonesPub = ed25519.utils.toMontgomery(someonesPub);\n * const aPriv = x25519.utils.randomSecretKey();\n * const shared = x25519.getSharedSecret(aPriv, someonesPub)\n * ```\n */\n toMontgomery: (publicKey: Uint8Array) => Uint8Array;\n /**\n * Converts ed secret key to x secret key.\n * @example\n * ```js\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomSecretKey());\n * const aPriv_ed = ed25519.utils.randomSecretKey();\n * const aPriv = ed25519.utils.toMontgomerySecret(aPriv_ed);\n * const shared = x25519.getSharedSecret(aPriv, someonesPub)\n * ```\n */\n toMontgomerySecret: (secretKey: Uint8Array) => Uint8Array;\n getExtendedPublicKey: (key: Uint8Array) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: EdwardsPoint;\n pointBytes: Uint8Array;\n };\n };\n lengths: CurveLengths;\n}\n\nfunction isEdValidXY(Fp: IField<bigint>, CURVE: EdwardsOpts, x: bigint, y: bigint): boolean {\n const x2 = Fp.sqr(x);\n const y2 = Fp.sqr(y);\n const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n return Fp.eql(left, right);\n}\n\nexport function edwards(params: EdwardsOpts, extraOpts: EdwardsExtraOpts = {}): EdwardsPointCons {\n const validated = createCurveFields('edwards', params, extraOpts, extraOpts.FpFnLE);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE as EdwardsOpts;\n const { h: cofactor } = CURVE;\n validateObject(extraOpts, {}, { uvRatio: 'function' });\n\n // Important:\n // There are some places where Fp.BYTES is used instead of nByteLength.\n // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n // TODO: test and find curves which behave otherwise.\n const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n);\n const modP = (n: bigint) => Fp.create(n); // Function overrides\n\n // sqrt(u/v)\n const uvRatio =\n extraOpts.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n\n // Validate whether the passed curve params are valid.\n // equation ax² + y² = 1 + dx²y² should work for generator point.\n if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n\n /**\n * Asserts coordinate is valid: 0 <= n < MASK.\n * Coordinates >= Fp.ORDER are allowed for zip215.\n */\n function acoord(title: string, n: bigint, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n return n;\n }\n\n function aedpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('EdwardsPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p: Point, iz?: bigint): AffinePoint<bigint> => {\n const { X, Y, Z } = p;\n const is0 = p.is0();\n if (iz == null) iz = is0 ? _8n : (Fp.inv(Z) as bigint); // 8 was chosen arbitrarily\n const x = modP(X * iz);\n const y = modP(Y * iz);\n const zz = Fp.mul(Z, iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x, y };\n });\n const assertValidMemo = memoized((p: Point) => {\n const { a, d } = CURVE;\n if (p.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { X, Y, Z, T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right) throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n return true;\n });\n\n // Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point implements EdwardsPoint {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n // zero / infinity / identity point\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: bigint;\n readonly Y: bigint;\n readonly Z: bigint;\n readonly T: bigint;\n\n constructor(X: bigint, Y: bigint, Z: bigint, T: bigint) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y);\n this.Z = acoord('z', Z, true);\n this.T = acoord('t', T);\n Object.freeze(this);\n }\n\n static CURVE(): EdwardsOpts {\n return CURVE;\n }\n\n static fromAffine(p: AffinePoint<bigint>): Point {\n if (p instanceof Point) throw new Error('extended point not allowed');\n const { x, y } = p || {};\n acoord('x', x);\n acoord('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n\n // Uses algo from RFC8032 5.1.3.\n static fromBytes(bytes: Uint8Array, zip215 = false): Point {\n const len = Fp.BYTES;\n const { a, d } = CURVE;\n bytes = copyBytes(abytes(bytes, len, 'point'));\n abool(zip215, 'zip215');\n const normed = copyBytes(bytes); // copy again, we'll manipulate it\n const lastByte = bytes[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = bytesToNumberLE(normed);\n\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n aInRange('point.y', y, _0n, max);\n\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid) throw new Error('bad point: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('bad point: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n\n static fromHex(hex: string, zip215 = false): Point {\n return Point.fromBytes(hexToBytes(hex), zip215);\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n precompute(windowSize: number = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_2n); // random number\n return this;\n }\n\n // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n aedpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n negate(): Point {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));\n }\n\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double(): Point {\n const { a } = CURVE;\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other: Point) {\n aedpoint(other);\n const { a, d } = CURVE;\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n subtract(other: Point): Point {\n return this.add(other.negate());\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n // 1 <= scalar < L\n if (!Fn.isValidNot0(scalar)) throw new Error('invalid scalar: expected 1 <= sc < curve.n');\n const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));\n return normalizeZ(Point, [p, f])[0];\n }\n\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n // Accepts optional accumulator to merge with multiply (important for sparse scalars)\n multiplyUnsafe(scalar: bigint, acc = Point.ZERO): Point {\n // 0 <= scalar < L\n if (!Fn.isValid(scalar)) throw new Error('invalid scalar: expected 0 <= sc < curve.n');\n if (scalar === _0n) return Point.ZERO;\n if (this.is0() || scalar === _1n) return this;\n return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);\n }\n\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree(): boolean {\n return wnaf.unsafe(this, CURVE.n).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n return toAffineMemo(this, invertedZ);\n }\n\n clearCofactor(): Point {\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n toBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n // Fp.toBytes() allows non-canonical encoding of y (>= p).\n const bytes = Fp.toBytes(y);\n // Each y has 2 valid points: (x, y), (x,-y).\n // When compressing, it's enough to store y and use the last byte to encode sign of x\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;\n return bytes;\n }\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const wnaf = new wNAF(Point, Fn.BITS);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points.\n */\nexport abstract class PrimeEdwardsPoint<T extends PrimeEdwardsPoint<T>>\n implements CurvePoint<bigint, T>\n{\n static BASE: PrimeEdwardsPoint<any>;\n static ZERO: PrimeEdwardsPoint<any>;\n static Fp: IField<bigint>;\n static Fn: IField<bigint>;\n\n protected readonly ep: EdwardsPoint;\n\n constructor(ep: EdwardsPoint) {\n this.ep = ep;\n }\n\n // Abstract methods that must be implemented by subclasses\n abstract toBytes(): Uint8Array;\n abstract equals(other: T): boolean;\n\n // Static methods that must be implemented by subclasses\n static fromBytes(_bytes: Uint8Array): any {\n notImplemented();\n }\n\n static fromHex(_hex: string): any {\n notImplemented();\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n // Common implementations\n clearCofactor(): T {\n // no-op for prime-order groups\n return this as any;\n }\n\n assertValidity(): void {\n this.ep.assertValidity();\n }\n\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n return this.ep.toAffine(invertedZ);\n }\n\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n isTorsionFree(): boolean {\n return true;\n }\n\n isSmallOrder(): boolean {\n return false;\n }\n\n add(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.add(other.ep));\n }\n\n subtract(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): T {\n return this.init(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): T {\n return this.init(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): T {\n return this.init(this.ep.double());\n }\n\n negate(): T {\n return this.init(this.ep.negate());\n }\n\n precompute(windowSize?: number, isLazy?: boolean): T {\n return this.init(this.ep.precompute(windowSize, isLazy));\n }\n\n // Helper methods\n abstract is0(): boolean;\n protected abstract assertSame(other: T): void;\n protected abstract init(ep: EdwardsPoint): T;\n}\n\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n */\nexport function eddsa(Point: EdwardsPointCons, cHash: FHash, eddsaOpts: EdDSAOpts = {}): EdDSA {\n if (typeof cHash !== 'function') throw new Error('\"hash\" function param is required');\n validateObject(\n eddsaOpts,\n {},\n {\n adjustScalarBytes: 'function',\n randomBytes: 'function',\n domain: 'function',\n prehash: 'function',\n mapToCurve: 'function',\n }\n );\n\n const { prehash } = eddsaOpts;\n const { BASE, Fp, Fn } = Point;\n\n const randomBytes = eddsaOpts.randomBytes || wcRandomBytes;\n const adjustScalarBytes = eddsaOpts.adjustScalarBytes || ((bytes: Uint8Array) => bytes);\n const domain =\n eddsaOpts.domain ||\n ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => {\n abool(phflag, 'phflag');\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n }\n\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key: Uint8Array) {\n const len = lengths.secretKey;\n abytes(key, lengths.secretKey, 'secretKey');\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = abytes(cHash(key), 2 * len, 'hashedSecretKey');\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n return { head, prefix, scalar };\n }\n\n /** Convenience method that creates public key from scalar. RFC8032 5.1.5 */\n function getExtendedPublicKey(secretKey: Uint8Array) {\n const { head, prefix, scalar } = getPrivateScalar(secretKey);\n const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toBytes();\n return { head, prefix, scalar, point, pointBytes };\n }\n\n /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n function getPublicKey(secretKey: Uint8Array): Uint8Array {\n return getExtendedPublicKey(secretKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Uint8Array = Uint8Array.of(), ...msgs: Uint8Array[]) {\n const msg = concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, abytes(context, undefined, 'context'), !!prehash)));\n }\n\n /** Signs message with secret key. RFC8032 5.1.6 */\n function sign(\n msg: Uint8Array,\n secretKey: Uint8Array,\n options: { context?: Uint8Array } = {}\n ): Uint8Array {\n msg = abytes(msg, undefined, 'message');\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = BASE.multiply(r).toBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n if (!Fn.isValid(s)) throw new Error('sign failed: invalid s'); // 0 <= s < L\n const rs = concatBytes(R, Fn.toBytes(s));\n return abytes(rs, lengths.signature, 'result');\n }\n\n // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\n const verifyOpts: { context?: Uint8Array; zip215?: boolean } = { zip215: true };\n\n /**\n * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n * An extended group equation is checked.\n */\n function verify(\n sig: Uint8Array,\n msg: Uint8Array,\n publicKey: Uint8Array,\n options = verifyOpts\n ): boolean {\n const { context, zip215 } = options;\n const len = lengths.signature;\n sig = abytes(sig, len, 'signature');\n msg = abytes(msg, undefined, 'message');\n publicKey = abytes(publicKey, lengths.publicKey, 'publicKey');\n if (zip215 !== undefined) abool(zip215, 'zip215');\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const mid = len / 2;\n const r = sig.subarray(0, mid);\n const s = bytesToNumberLE(sig.subarray(mid, len));\n let A, R, SB;\n try {\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false; // zip215 allows public keys of small order\n\n const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Extended group equation\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n }\n\n const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n const lengths = {\n secretKey: _size,\n publicKey: _size,\n signature: 2 * _size,\n seed: _size,\n };\n function randomSecretKey(seed = randomBytes(lengths.seed)): Uint8Array {\n return abytes(seed, lengths.seed, 'seed');\n }\n\n function isValidSecretKey(key: Uint8Array): boolean {\n return isBytes(key) && key.length === Fn.BYTES;\n }\n\n function isValidPublicKey(key: Uint8Array, zip215?: boolean): boolean {\n try {\n return !!Point.fromBytes(key, zip215);\n } catch (error) {\n return false;\n }\n }\n\n const utils = {\n getExtendedPublicKey,\n randomSecretKey,\n isValidSecretKey,\n isValidPublicKey,\n /**\n * Converts ed public key to x public key. Uses formula:\n * - ed25519:\n * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * - ed448:\n * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n */\n toMontgomery(publicKey: Uint8Array): Uint8Array {\n const { y } = Point.fromBytes(publicKey);\n const size = lengths.publicKey;\n const is25519 = size === 32;\n if (!is25519 && size !== 57) throw new Error('only defined for 25519 and 448');\n const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);\n return Fp.toBytes(u);\n },\n toMontgomerySecret(secretKey: Uint8Array): Uint8Array {\n const size = lengths.secretKey;\n abytes(secretKey, size);\n const hashed = cHash(secretKey.subarray(0, size));\n return adjustScalarBytes(hashed).subarray(0, size);\n },\n };\n\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getPublicKey,\n sign,\n verify,\n utils,\n Point,\n lengths,\n }) satisfies Signer;\n}\n","/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, hexToBytes } from '@noble/hashes/utils.js';\nimport { type AffinePoint } from './abstract/curve.ts';\nimport {\n eddsa,\n edwards,\n PrimeEdwardsPoint,\n type EdDSA,\n type EdDSAOpts,\n type EdwardsOpts,\n type EdwardsPoint,\n type EdwardsPointCons,\n} from './abstract/edwards.ts';\nimport {\n _DST_scalar,\n createHasher,\n expand_message_xmd,\n type H2CDSTOpts,\n type H2CHasher,\n type H2CHasherBase,\n} from './abstract/hash-to-curve.ts';\nimport {\n FpInvertBatch,\n FpSqrtEven,\n isNegativeLE,\n mod,\n pow2,\n type IField,\n} from './abstract/modular.ts';\nimport { montgomery, type MontgomeryECDH } from './abstract/montgomery.ts';\nimport { createORPF, type OPRF } from './abstract/oprf.ts';\nimport { asciiToBytes, bytesToNumberLE, equalBytes } from './utils.ts';\n\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\n\n// P = 2n**255n - 19n\nconst ed25519_CURVE_p = BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed'\n);\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE: EdwardsOpts = /* @__PURE__ */ (() => ({\n p: ed25519_CURVE_p,\n n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n h: _8n,\n a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ed25519_CURVE_p;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\n\nfunction adjustScalarBytes(bytes: Uint8Array): Uint8Array {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n\n// √(-1) aka √(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt(\n '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ed25519_CURVE_p;\n const v3 = mod(v * v * v, P); // v³\n const v7 = mod(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P)) x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n\nconst ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });\nconst Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();\nconst Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();\n\nfunction ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n asciiToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\nfunction ed(opts: EdDSAOpts) {\n return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes }, opts));\n}\n\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * ```js\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * const { secretKey, publicKey } = ed25519.keygen();\n * // const publicKey = ed25519.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519.sign(msg, secretKey);\n * const isValid = ed25519.verify(sig, msg, pub); // ZIP215\n * // RFC8032 / FIPS 186-5\n * const isValid2 = ed25519.verify(sig, msg, pub, { zip215: false });\n * ```\n */\nexport const ed25519: EdDSA = /* @__PURE__ */ ed({});\n/** Context version of ed25519 (ctx for domain separation). See {@link ed25519} */\nexport const ed25519ctx: EdDSA = /* @__PURE__ */ ed({ domain: ed25519_domain });\n/** Prehashed version of ed25519. See {@link ed25519} */\nexport const ed25519ph: EdDSA = /* @__PURE__ */ ed({ domain: ed25519_domain, prehash: sha512 });\n\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * ```js\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const alice = x25519.keygen();\n * const bob = x25519.keygen();\n * const shared = x25519.getSharedSecret(alice.secretKey, bob.publicKey);\n * ```\n */\nexport const x25519: MontgomeryECDH = /* @__PURE__ */ (() => {\n const P = ed25519_CURVE_p;\n return montgomery({\n P,\n type: 'x25519',\n powPminus2: (x: bigint): bigint => {\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n });\n})();\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n\n/**\n * RFC 9380 method `map_to_curve_elligator2_curve25519`. Experimental name: may be renamed later.\n * @private\n */\n// prettier-ignore\nexport function _map_to_curve_elligator2_curve25519(u: bigint): {\n xMn: bigint, xMd: bigint, yMn: bigint, yMd: bigint\n} {\n const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J);// 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd!(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n const { xMn, xMd, yMn, yMd } = _map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n\n/** Hashing to ed25519 points / field. RFC 9380 methods. */\nexport const ed25519_hasher: H2CHasher<EdwardsPointCons> = /* @__PURE__ */ (() =>\n createHasher(\n ed25519_Point,\n (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: ed25519_CURVE_p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\n\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d²\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)²\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/√(number)\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = /* @__PURE__ */ BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n);\nconst bytes255ToNumberLE = (bytes: Uint8Array) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\n/**\n * Computes Elligator map for Ristretto255.\n * Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-B) and on\n * the [website](https://ristretto.group/formulas/elligator.html).\n */\nfunction calcElligatorRistrettoMap(r0: bigint): EdwardsPoint {\n const { d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n if (!Ns_D_is_sq) s = s_; // 7\n if (!Ns_D_is_sq) c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519_Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/EdwardsPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like EdwardsPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint<_RistrettoPoint> {\n // Do NOT change syntax: the following gymnastics is done,\n // because typescript strips comments, which makes bundlers disable tree-shaking.\n // prettier-ignore\n static BASE: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.BASE))();\n // prettier-ignore\n static ZERO: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.ZERO))();\n // prettier-ignore\n static Fp: IField<bigint> =\n /* @__PURE__ */ (() => Fp)();\n // prettier-ignore\n static Fn: IField<bigint> =\n /* @__PURE__ */ (() => Fn)();\n\n constructor(ep: EdwardsPoint) {\n super(ep);\n }\n\n static fromAffine(ap: AffinePoint<bigint>): _RistrettoPoint {\n return new _RistrettoPoint(ed25519_Point.fromAffine(ap));\n }\n\n protected assertSame(other: _RistrettoPoint): void {\n if (!(other instanceof _RistrettoPoint)) throw new Error('RistrettoPoint expected');\n }\n\n protected init(ep: EdwardsPoint): _RistrettoPoint {\n return new _RistrettoPoint(ep);\n }\n\n static fromBytes(bytes: Uint8Array): _RistrettoPoint {\n abytes(bytes, 32);\n const { a, d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const s = bytes255ToNumberLE(bytes);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))\n throw new Error('invalid ristretto255 encoding 1');\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P)) x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n)\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519_Point(x, y, _1n, t));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: string): _RistrettoPoint {\n return _RistrettoPoint.fromBytes(hexToBytes(hex));\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toBytes(): Uint8Array {\n let { X, Y, Z, T } = this.ep;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const u1 = mod(mod(Z + Y) * mod(Z - Y)); // 1\n const u2 = mod(X * Y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * T); // 6\n let D: bigint; // 7\n if (isNegativeLE(T * zInv, P)) {\n let _x = mod(Y * SQRT_M1);\n let _y = mod(X * SQRT_M1);\n X = _x;\n Y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n } else {\n D = D2; // 8\n }\n if (isNegativeLE(X * zInv, P)) Y = mod(-Y); // 9\n let s = mod((Z - Y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P)) s = mod(-s);\n return Fp.toBytes(s); // 11\n }\n\n /**\n * Compares two Ristretto points.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n */\n equals(other: _RistrettoPoint): boolean {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n const mod = (n: bigint) => Fp.create(n);\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n\n is0(): boolean {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\n\nexport const ristretto255: {\n Point: typeof _RistrettoPoint;\n} = { Point: _RistrettoPoint };\n\n/** Hashing to ristretto255 points / field. RFC 9380 methods. */\nexport const ristretto255_hasher: H2CHasherBase<typeof _RistrettoPoint> = {\n Point: _RistrettoPoint,\n /**\n * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:\n * * There are no test vectors\n * * encodeToCurve / mapToCurve is undefined\n * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!\n * * hashToScalar is undefined too, so we just use OPRF implementation\n * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC\n (os2ip -> bytes255ToNumberLE)\n * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map\n * * hashToScalar is undefined in RFC9380 for ristretto, we are using version from OPRF here, using bytes255ToNumblerLE will create different result if we use bytes255ToNumberLE as os2ip\n * * current version is closest to spec.\n */\n hashToCurve(msg: Uint8Array, options?: H2CDSTOpts): _RistrettoPoint {\n // == 'hash_to_ristretto255'\n const DST = options?.DST || 'ristretto255_XMD:SHA-512_R255MAP_RO_';\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n // NOTE: RFC 9380 incorrectly calls this function 'ristretto255_map', in RFC 9496 map was function inside (per point)\n // That also lead to confustion that ristretto255_map is mapToCurve (it is not! it is old hashToCurve)\n return ristretto255_hasher.deriveToCurve!(xmd);\n },\n hashToScalar(msg: Uint8Array, options: H2CDSTOpts = { DST: _DST_scalar }) {\n const xmd = expand_message_xmd(msg, options.DST, 64, sha512);\n return Fn.create(bytesToNumberLE(xmd));\n },\n /**\n * HashToCurve-like construction based on RFC 9496 (Element Derivation).\n * Converts 64 uniform random bytes into a curve point.\n *\n * WARNING: This represents an older hash-to-curve construction, preceding the finalization of RFC 9380.\n * It was later reused as a component in the newer `hash_to_ristretto255` function defined in RFC 9380.\n */\n deriveToCurve(bytes: Uint8Array): _RistrettoPoint {\n // https://www.rfc-editor.org/rfc/rfc9496.html#name-element-derivation\n abytes(bytes, 64);\n const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new _RistrettoPoint(R1.add(R2));\n },\n};\n\n/** ristretto255 OPRF, defined in RFC 9497. */\nexport const ristretto255_oprf: OPRF = /* @__PURE__ */ (() =>\n createORPF({\n name: 'ristretto255-SHA512',\n Point: _RistrettoPoint,\n hash: sha512,\n hashToGroup: ristretto255_hasher.hashToCurve,\n hashToScalar: ristretto255_hasher.hashToScalar,\n }))();\n\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * ⟨T⟩ = { O, T, 2T, 3T, 4T, 5T, 6T, 7T }\n */\nexport const ED25519_TORSION_SUBGROUP: string[] = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n","// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fromBase64 } from '@mysten/bcs';\nimport { ed25519 } from '@noble/curves/ed25519.js';\n\nimport {\n\tbytesEqual,\n\tparseSerializedKeypairSignature,\n\tPublicKey,\n} from '../../cryptography/publickey.js';\nimport type { PublicKeyInitData } from '../../cryptography/publickey.js';\nimport { SIGNATURE_SCHEME_TO_FLAG } from '../../cryptography/signature-scheme.js';\n\nconst PUBLIC_KEY_SIZE = 32;\n\n/**\n * An Ed25519 public key\n */\nexport class Ed25519PublicKey extends PublicKey {\n\tstatic SIZE = PUBLIC_KEY_SIZE;\n\tprivate data: Uint8Array<ArrayBuffer>;\n\n\t/**\n\t * Create a new Ed25519PublicKey object\n\t * @param value ed25519 public key as buffer or base-64 encoded string\n\t */\n\tconstructor(value: PublicKeyInitData) {\n\t\tsuper();\n\n\t\tif (typeof value === 'string') {\n\t\t\tthis.data = fromBase64(value);\n\t\t} else if (value instanceof Uint8Array) {\n\t\t\tthis.data = value as Uint8Array<ArrayBuffer>;\n\t\t} else {\n\t\t\tthis.data = Uint8Array.from(value);\n\t\t}\n\n\t\tif (this.data.length !== PUBLIC_KEY_SIZE) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid public key input. Expected ${PUBLIC_KEY_SIZE} bytes, got ${this.data.length}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Checks if two Ed25519 public keys are equal\n\t */\n\toverride equals(publicKey: Ed25519PublicKey): boolean {\n\t\treturn super.equals(publicKey);\n\t}\n\n\t/**\n\t * Return the byte array representation of the Ed25519 public key\n\t */\n\ttoRawBytes(): Uint8Array<ArrayBuffer> {\n\t\treturn this.data;\n\t}\n\n\t/**\n\t * Return the Sui address associated with this Ed25519 public key\n\t */\n\tflag(): number {\n\t\treturn SIGNATURE_SCHEME_TO_FLAG['ED25519'];\n\t}\n\n\t/**\n\t * Verifies that the signature is valid for for the provided message\n\t */\n\tasync verify(message: Uint8Array, signature: Uint8Array | string): Promise<boolean> {\n\t\tlet bytes;\n\t\tif (typeof signature === 'string') {\n\t\t\tconst parsed = parseSerializedKeypairSignature(signature);\n\t\t\tif (parsed.signatureScheme !== 'ED25519') {\n\t\t\t\tthrow new Error('Invalid signature scheme');\n\t\t\t}\n\n\t\t\tif (!bytesEqual(this.toRawBytes(), parsed.publicKey)) {\n\t\t\t\tthrow new Error('Signature does not match public key');\n\t\t\t}\n\n\t\t\tbytes = parsed.signature;\n\t\t} else {\n\t\t\tbytes = signature;\n\t\t}\n\n\t\treturn ed25519.verify(bytes, message, this.toRawBytes());\n\t}\n}\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n ? ReturnType<typeof BigInt64Array.of>\n : T extends BigUint64Array\n ? ReturnType<typeof BigUint64Array.of>\n : T extends Float32Array\n ? ReturnType<typeof Float32Array.of>\n : T extends Float64Array\n ? ReturnType<typeof Float64Array.of>\n : T extends Int16Array\n ? ReturnType<typeof Int16Array.of>\n : T extends Int32Array\n ? ReturnType<typeof Int32Array.of>\n : T extends Int8Array\n ? ReturnType<typeof Int8Array.of>\n : T extends Uint16Array\n ? ReturnType<typeof Uint16Array.of>\n : T extends Uint32Array\n ? ReturnType<typeof Uint32Array.of>\n : T extends Uint8ClampedArray\n ? ReturnType<typeof Uint8ClampedArray.of>\n : T extends Uint8Array\n ? ReturnType<typeof Uint8Array.of>\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n | T\n | ([TypedArg<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends (infer A)[]\n ? TArg<A>[]\n : T extends readonly (infer A)[]\n ? readonly TArg<A>[]\n : T extends Promise<infer A>\n ? Promise<TArg<A>>\n : T extends object\n ? { [K in keyof T]: TArg<T[K]> }\n : T\n : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n ? T &\n ([TypedRet<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends (infer A)[]\n ? TRet<A>[]\n : T extends readonly (infer A)[]\n ? readonly TRet<A>[]\n : T extends Promise<infer A>\n ? Promise<TRet<A>>\n : T extends object\n ? { [K in keyof T]: TRet<T[K]> }\n : T\n : TypedRet<T>)\n : never;\n/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a: unknown): a is Uint8Array {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (\n a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1)\n );\n}\n\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n: number, title: string = ''): void {\n if (typeof n !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(`${prefix}expected number, got ${typeof n}`);\n }\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(\n value: TArg<Uint8Array>,\n length?: number,\n title: string = ''\n): TRet<Uint8Array> {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes) throw new TypeError(message);\n throw new RangeError(message);\n }\n return value as TRet<Uint8Array>;\n}\n\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet<Uint8Array>;\n}\n\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h: TArg<CHash>): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1) throw new Error('\"outputLen\" must be >= 1');\n if (h.blockLen < 1) throw new Error('\"blockLen\" must be >= 1');\n}\n\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new RangeError('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte array views, but not 64-bit variants. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr: TArg<TypedArray>): TRet<Uint8Array> {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength) as TRet<Uint8Array>;\n}\n\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr: TArg<TypedArray>): TRet<Uint32Array> {\n return new Uint32Array(\n arr.buffer,\n arr.byteOffset,\n Math.floor(arr.byteLength / 4)\n ) as TRet<Uint32Array>;\n}\n\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays: TArg<TypedArray[]>): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr: TArg<TypedArray>): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Whether the current platform is little-endian. */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n) >>> 0;\n\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr: TArg<Uint32Array>): TRet<Uint32Array> {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr as TRet<Uint32Array>;\n}\n\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE: (u: TArg<Uint32Array>) => TRet<Uint32Array> = isLE\n ? (u: TArg<Uint32Array>) => u as TRet<Uint32Array>\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes: TArg<Uint8Array>): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex: string): TRet<Uint8Array> {\n if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return (Uint8Array as any).fromHex(hex);\n } catch (error) {\n if (error instanceof SyntaxError) throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError(\n 'hex string expected, got non-hex character \"' + char + '\" at index ' + hi\n );\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * This yields to the Promise/microtask scheduler queue, not to timers or the\n * full macrotask event loop.\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/**\n * Returns control to the Promise/microtask scheduler every `tick`\n * milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str: string): TRet<Uint8Array> {\n if (typeof str !== 'string') throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data: TArg<KDFInput>, errorTitle = ''): TRet<Uint8Array> {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays: TArg<Uint8Array[]>): TRet<Uint8Array> {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @returns Merged option object. The merge mutates `defaults` in place.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new TypeError('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hash instances. */\nexport interface Hash<T> {\n /** Bytes processed per compression block. */\n blockLen: number;\n /** Bytes produced by `digest()`. */\n outputLen: number;\n /** Whether the instance supports XOF-style variable-length output via `xof()` / `xofInto()`. */\n canXOF: boolean;\n /**\n * Absorbs more message bytes into the running hash state.\n * @param buf - message chunk to absorb\n * @returns The same hash instance for chaining.\n */\n update(buf: TArg<Uint8Array>): this;\n /**\n * Finalizes the hash into a caller-provided buffer.\n * @param buf - destination buffer\n * @returns Nothing. Implementations write into `buf` in place.\n */\n digestInto(buf: TArg<Uint8Array>): void;\n /**\n * Finalizes the hash and returns a freshly allocated digest.\n * @returns Digest bytes.\n */\n digest(): TRet<Uint8Array>;\n /** Wipes internal state and makes the instance unusable. */\n destroy(): void;\n /**\n * Copies the current hash state into an existing or new instance.\n * @param to - Optional destination instance to reuse.\n * @returns Cloned hash state.\n */\n _cloneInto(to?: T): T;\n /**\n * Creates an independent copy of the current hash state.\n * @returns Cloned hash instance.\n */\n clone(): T;\n}\n\n/** Pseudorandom generator interface. */\nexport interface PRG {\n /**\n * Mixes more entropy into the generator state.\n * @param seed - fresh entropy bytes\n * @returns Nothing. Implementations update internal state in place.\n */\n addEntropy(seed: TArg<Uint8Array>): void;\n /**\n * Generates pseudorandom output bytes.\n * @param length - number of bytes to generate\n * @returns Generated pseudorandom bytes.\n */\n randomBytes(length: number): TRet<Uint8Array>;\n /** Wipes generator state and makes the instance unusable. */\n clean(): void;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n /**\n * Reads more bytes from the XOF stream.\n * @param bytes - number of bytes to read\n * @returns Requested digest bytes.\n */\n xof(bytes: number): TRet<Uint8Array>;\n /**\n * Reads more bytes from the XOF stream into a caller-provided buffer.\n * @param buf - destination buffer\n * @returns Filled output buffer.\n */\n xofInto(buf: TArg<Uint8Array>): TRet<Uint8Array>;\n};\n\n/** Hash constructor or factory type. */\nexport type HasherCons<T, Opts = undefined> = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash metadata. */\nexport type HashInfo = {\n /** DER-encoded object identifier bytes for the hash algorithm. */\n oid?: TRet<Uint8Array>;\n};\n/** Callable hash function type. */\nexport type CHash<T extends Hash<T> = Hash<any>, Opts = undefined> = {\n /** Digest size in bytes. */\n outputLen: number;\n /** Input block size in bytes. */\n blockLen: number;\n /** Whether `.create()` returns a hash instance that can be used as an XOF stream. */\n canXOF: boolean;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: TArg<Uint8Array>): TRet<Uint8Array>;\n create(): T;\n }\n : {\n (msg: TArg<Uint8Array>, opts?: TArg<Opts>): TRet<Uint8Array>;\n create(opts?: Opts): T;\n });\n/** Callable extendable-output hash function type. */\nexport type CHashXOF<T extends HashXOF<T> = HashXOF<any>, Opts = undefined> = CHash<T, Opts>;\n\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher<T extends Hash<T>, Opts = undefined>(\n hashCons: HasherCons<T, Opts>,\n info: TArg<HashInfo> = {}\n): TRet<CHash<T, Opts>> {\n const hashC: any = (msg: TArg<Uint8Array>, opts?: TArg<Opts>) =>\n hashCons(opts as Opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC) as TRet<CHash<T, Opts>>;\n}\n\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32): TRet<Uint8Array> {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 §10.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix: number): TRet<Required<HashInfo>> => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport {\n abytes,\n aexists,\n ahash,\n aoutput,\n clean,\n type CHash,\n type Hash,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/**\n * Internal class for HMAC.\n * Accepts any byte key, although RFC 2104 §3 recommends keys at least\n * `HashLen` bytes long.\n */\nexport class _HMAC<T extends Hash<T>> implements Hash<_HMAC<T>> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n canXOF = false;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: TArg<CHash>, key: TArg<Uint8Array>) {\n ahash(hash);\n abytes(key, undefined, 'key');\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of the first block) of the outer hash here,\n // we can re-use it between multiple calls via clone.\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf: TArg<Uint8Array>): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: TArg<Uint8Array>): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const buf = out.subarray(0, this.outputLen);\n // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before\n // overwriting that same prefix with the final tag, leaving any oversized tail untouched.\n this.iHash.digestInto(buf);\n this.oHash.update(buf);\n this.oHash.digestInto(buf);\n this.destroy();\n }\n digest(): TRet<Uint8Array> {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out as TRet<Uint8Array>;\n }\n _cloneInto(to?: _HMAC<T>): _HMAC<T> {\n // Create new instance without calling constructor since the key\n // is already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone(): _HMAC<T> {\n return this._cloneInto();\n }\n destroy(): void {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - authentication key bytes\n * @param message - message bytes to authenticate\n * @returns Authentication tag bytes.\n * @example\n * Compute an RFC 2104 HMAC.\n * ```ts\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const mac = hmac(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));\n * ```\n */\ntype HmacFn = {\n (hash: TArg<CHash>, key: TArg<Uint8Array>, message: TArg<Uint8Array>): TRet<Uint8Array>;\n create(hash: TArg<CHash>, key: TArg<Uint8Array>): TRet<_HMAC<any>>;\n};\nexport const hmac: TRet<HmacFn> = /* @__PURE__ */ (() => {\n const hmac_ = ((\n hash: TArg<CHash>,\n key: TArg<Uint8Array>,\n message: TArg<Uint8Array>\n ): TRet<Uint8Array> => new _HMAC<any>(hash, key).update(message).digest()) as TRet<HmacFn>;\n hmac_.create = (hash: TArg<CHash>, key: TArg<Uint8Array>): TRet<_HMAC<any>> =>\n new _HMAC<any>(hash, key) as TRet<_HMAC<any>>;\n return hmac_;\n})();\n","/**\n * PBKDF (RFC 2898). Can be used to create a key from password and salt.\n * @module\n */\nimport { hmac } from './hmac.ts';\n// prettier-ignore\nimport {\n ahash, anumber,\n asyncLoop, checkOpts, clean, createView, kdfInputToBytes,\n type CHash,\n type Hash,\n type KDFInput,\n type TArg,\n type TRet\n} from './utils.ts';\n\n/**\n * PBKDF2 options:\n * * c: iterations, should probably be higher than 100_000\n * * dkLen: desired length of derived key in bytes, must be `>= 1` per RFC 8018 §5.2\n * * asyncTick: max time in ms for which async function can block execution\n */\nexport type Pbkdf2Opt = {\n /** Iteration count. Higher values increase CPU cost. */\n c: number;\n /** Desired derived key length in bytes, must be `>= 1` per RFC 8018 §5.2. */\n dkLen?: number;\n /** Max scheduler block time in milliseconds for the async variant. */\n asyncTick?: number;\n};\n// Common start and end for sync/async functions\nfunction pbkdf2Init(\n hash: TArg<CHash>,\n _password: TArg<KDFInput>,\n _salt: TArg<KDFInput>,\n _opts: TArg<Pbkdf2Opt>\n) {\n ahash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n anumber(c, 'c');\n anumber(dkLen, 'dkLen');\n anumber(asyncTick, 'asyncTick');\n if (c < 1) throw new Error('iterations (c) must be >= 1');\n // RFC 8018 §5.2 defines `dkLen` as \"a positive integer\".\n if (dkLen < 1) throw new Error('\"dkLen\" must be >= 1');\n // RFC 8018 §5.2 step 1 requires rejecting oversize `dkLen`\n // before allocating the destination buffer.\n if (dkLen > (2 ** 32 - 1) * hash.outputLen) throw new Error('derived key too long');\n const password = kdfInputToBytes(_password, 'password');\n const salt = kdfInputToBytes(_salt, 'salt');\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = hmac.create(hash, password);\n // Cache PRF(P, S || ...) prefix state so each block only appends INT_32_BE(i).\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\n\nfunction pbkdf2Output<T extends Hash<T>>(\n PRF: TArg<Hash<T>>,\n PRFSalt: TArg<Hash<T>>,\n DK: TArg<Uint8Array>,\n prfW: TArg<Hash<T> | undefined>,\n u: TArg<Uint8Array>\n): TRet<Uint8Array> {\n // Shared sync/async cleanup point: wipe transient PRF state\n // while preserving the derived key buffer.\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW) prfW.destroy();\n clean(u);\n return DK as TRet<Uint8Array>;\n}\n\n/**\n * PBKDF2-HMAC: RFC 8018 key derivation function.\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated;\n * JS string inputs are UTF-8 encoded first\n * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first\n * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,\n * must be `>= 1` per RFC 8018 §5.2. See {@link Pbkdf2Opt}.\n * @returns Derived key bytes.\n * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error}\n * @example\n * PBKDF2-HMAC: RFC 2898 key derivation function.\n * ```ts\n * import { pbkdf2 } from '@noble/hashes/pbkdf2.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });\n * ```\n */\nexport function pbkdf2(\n hash: TArg<CHash>,\n password: TArg<KDFInput>,\n salt: TArg<KDFInput>,\n opts: TArg<Pbkdf2Opt>\n): TRet<Uint8Array> {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n // The last Ti view can be shorter than hLen, which applies\n // RFC 8018 §5.2 step 4's T_l<0..r-1> truncation without extra copies.\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n\n/**\n * PBKDF2-HMAC: RFC 8018 key derivation function. Async version.\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated;\n * JS string inputs are UTF-8 encoded first\n * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first\n * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,\n * must be `>= 1` per RFC 8018 §5.2. `asyncTick` is only a local\n * scheduler-yield knob for this JS wrapper, not part of RFC 8018.\n * See {@link Pbkdf2Opt}.\n * @returns Promise resolving to derived key bytes.\n * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error}\n * @example\n * PBKDF2-HMAC: RFC 2898 key derivation function.\n * ```ts\n * import { pbkdf2Async } from '@noble/hashes/pbkdf2.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const key = await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });\n * ```\n */\nexport async function pbkdf2Async(\n hash: TArg<CHash>,\n password: TArg<KDFInput>,\n salt: TArg<KDFInput>,\n opts: TArg<Pbkdf2Opt>\n): Promise<TRet<Uint8Array>> {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n // The last Ti view can be shorter than hLen, which applies\n // RFC 8018 §5.2 step 4's T_l<0..r-1> truncation without extra copies.\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport {\n abytes,\n aexists,\n aoutput,\n clean,\n createView,\n type Hash,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport abstract class HashMD<T extends HashMD<T>> implements Hash<T> {\n // Subclasses must treat `buf` as read-only: `update()` may pass a direct view over caller input\n // when it can process whole blocks without buffering first.\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly canXOF = false;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: TArg<Uint8Array>): this {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: TArg<Uint8Array>): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here.\n view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen must be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): TRet<Uint8Array> {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res as TRet<Uint8Array>;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (length % blockLen) to.buffer.set(buffer);\n return to as unknown as any;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * Internal helpers for u64.\n * BigUint64Array is too slow as per 2026, so we implement it using\n * Uint32Array.\n * @privateRemarks TODO: re-check {@link https://issues.chromium.org/issues/42212588}\n * @module\n */\nimport type { TRet } from './utils.ts';\n\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst: bigint[], le = false): TRet<Uint32Array[]> {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al] as TRet<Uint32Array[]>;\n}\n\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h: number, l: number): number => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h: number, _l: number): number => h;\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// Canonical grouped namespace for callers that prefer one object.\n// Named exports stay for direct imports.\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// Default export mirrors named `u64` for compatibility with object-style imports.\nexport default u64;\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr, type TRet } from './utils.ts';\n\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */\nabstract class SHA2_32B<T extends SHA2_32B<T>> extends HashMD<T> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */\nabstract class SHA2_64B<T extends SHA2_64B<T>> extends HashMD<T> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256: TRet<CHash<_SHA256>> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224: TRet<CHash<_SHA224>> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512: TRet<CHash<_SHA512>> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384: TRet<CHash<_SHA384>> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256: TRet<CHash<_SHA512_256>> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224: TRet<CHash<_SHA512_224>> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n","/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js';\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, anumber, randomBytes } from '@noble/hashes/utils.js';\nimport { pbkdf2 as pbkdf2web, sha512 as sha512web } from '@noble/hashes/webcrypto.js';\nimport { utils as baseUtils } from '@scure/base';\n// Japanese wordlist\n// The canonical BIP-39 Japanese wordlist starts with あいこくしん.\n// Use that sentinel so generated phrases use U+3000 ideographic spaces.\nconst isJapanese = (wordlist) => wordlist[0] === '\\u3042\\u3044\\u3053\\u304f\\u3057\\u3093';\n// Normalization replaces equivalent sequences of characters\n// so that any two texts that are equivalent will be reduced\n// to the same sequence of code points, called the normal form of the original text.\n// https://tonsky.me/blog/unicode/#why-is-a----\n// BIP-39 requires UTF-8 NFKD for localized wordlists and mnemonic sentences.\n// It also applies NFKD to the \"mnemonic\" + passphrase salt.\nfunction nfkd(str) {\n if (typeof str !== 'string')\n throw new TypeError('invalid mnemonic type: ' + typeof str);\n return str.normalize('NFKD');\n}\n// BIP-39 mnemonics are consumed in NFKD form.\n// They must contain 12, 15, 18, 21, or 24 words before checksum validation.\nfunction normalize(str) {\n const norm = nfkd(str);\n const words = norm.split(' ');\n if (![12, 15, 18, 21, 24].includes(words.length))\n throw new Error('Invalid mnemonic');\n return { nfkd: norm, words };\n}\n// BIP-39 entropy payloads are 128-256 bits in 32-bit increments, i.e. 16/20/24/28/32 bytes.\nfunction aentropy(ent) {\n abytes(ent);\n if (![16, 20, 24, 28, 32].includes(ent.length))\n throw new RangeError('invalid entropy length');\n}\n/**\n * Generate x random words. Uses Cryptographically-Secure Random Number Generator.\n * @param wordlist - Imported wordlist for a specific language.\n * @param strength - Mnemonic strength, from 128 to 256 bits.\n * @returns 12-24 word mnemonic phrase.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Generate a new English mnemonic.\n * ```ts\n * import { generateMnemonic } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const mnemonic = generateMnemonic(wordlist, 128);\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n * ```\n */\nexport function generateMnemonic(wordlist, strength = 128) {\n anumber(strength);\n if (strength % 32 !== 0 || strength > 256)\n throw new RangeError('Invalid entropy');\n return entropyToMnemonic(randomBytes(strength / 8), wordlist);\n}\nconst calcChecksum = (entropy) => {\n // Checksum is ent.length/4 bits long\n const bitsLeft = 8 - entropy.length / 4;\n // Zero rightmost \"bitsLeft\" bits in byte\n // For example: bitsLeft=4 val=10111101 -> 10110000\n return new Uint8Array([(sha256(entropy)[0] >> bitsLeft) << bitsLeft]);\n};\nfunction getCoder(wordlist) {\n if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string')\n throw new TypeError('Wordlist: expected array of 2048 strings');\n wordlist.forEach((i) => {\n if (typeof i !== 'string')\n throw new TypeError('wordlist: non-string element: ' + i);\n });\n // BIP-39 appends checksum bits to entropy.\n // It then splits the bitstream into 11-bit indexes for a 2048-word list.\n return baseUtils.chain(baseUtils.checksum(1, calcChecksum), baseUtils.radix2(11, true), baseUtils.alphabet(wordlist));\n}\n/**\n * Reversible: Converts mnemonic string to raw entropy in form of byte array.\n * @param mnemonic - 12-24 words.\n * @param wordlist - Imported wordlist for a specific language.\n * @returns Raw entropy bytes.\n * @throws If the mnemonic shape or checksum is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode a mnemonic back into its original entropy bytes.\n * ```ts\n * import { mnemonicToEntropy } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const entropy = mnemonicToEntropy(mnem, wordlist);\n * // Produces the original 16-byte entropy payload.\n * new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ])\n * ```\n */\nexport function mnemonicToEntropy(mnemonic, wordlist) {\n const { words } = normalize(mnemonic);\n const entropy = getCoder(wordlist).decode(words);\n aentropy(entropy);\n return entropy;\n}\n/**\n * Reversible: Converts raw entropy in form of byte array to mnemonic string.\n * @param entropy - Byte array.\n * @param wordlist - Imported wordlist for a specific language.\n * @returns 12-24 words.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Convert raw entropy into an English mnemonic.\n * ```ts\n * import { entropyToMnemonic } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const ent = new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ]);\n * const mnemonic = entropyToMnemonic(ent, wordlist);\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n * ```\n */\nexport function entropyToMnemonic(entropy, wordlist) {\n aentropy(entropy);\n const words = getCoder(wordlist).encode(entropy);\n return words.join(isJapanese(wordlist) ? '\\u3000' : ' ');\n}\n/**\n * Validates mnemonic for being 12-24 words contained in `wordlist`.\n * @param mnemonic - 12-24 words.\n * @param wordlist - Imported wordlist for a specific language.\n * @returns `true` when mnemonic checksum and words are valid.\n * @example\n * Validate one English mnemonic.\n * ```ts\n * import { validateMnemonic } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const ok = validateMnemonic(\n * 'legal winner thank year wave sausage worth useful legal winner thank yellow',\n * wordlist\n * );\n * // => true\n * ```\n */\nexport function validateMnemonic(mnemonic, wordlist) {\n try {\n mnemonicToEntropy(mnemonic, wordlist);\n }\n catch (e) {\n return false;\n }\n return true;\n}\n// BIP-39 salts PBKDF2 with the UTF-8 NFKD string \"mnemonic\" + passphrase.\nconst psalt = (passphrase) => nfkd('mnemonic' + passphrase);\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic - 12-24 words.\n * @param passphrase - String that will additionally protect the key.\n * @returns 64 bytes of key data.\n * @throws If the mnemonic shape is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Derive a seed from a mnemonic with the async PBKDF2 helper.\n * ```ts\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const seed = await mnemonicToSeed(mnem, 'password');\n * // => new Uint8Array([...64 bytes])\n * ```\n */\n// BIP-39 seed derivation is independent from mnemonic generation.\n// These helpers normalize the phrase but do not verify checksum or wordlist membership.\nexport function mnemonicToSeed(mnemonic, passphrase = '') {\n return pbkdf2Async(sha512, normalize(mnemonic).nfkd, psalt(passphrase), {\n c: 2048,\n dkLen: 64,\n });\n}\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic - 12-24 words.\n * @param passphrase - String that will additionally protect the key.\n * @returns 64 bytes of key data.\n * @throws If the mnemonic shape is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Derive a seed from a mnemonic with the sync PBKDF2 helper.\n * ```ts\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const seed = mnemonicToSeedSync(mnem, 'password');\n * // => new Uint8Array([...64 bytes])\n * ```\n */\nexport function mnemonicToSeedSync(mnemonic, passphrase = '') {\n return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), {\n c: 2048,\n dkLen: 64,\n });\n}\n/**\n * Uses native, built-in functionality, provided by globalThis.crypto.\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic - 12-24 words.\n * @param passphrase - String that will additionally protect the key.\n * @returns 64 bytes of key data.\n * @throws If the mnemonic shape is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Derive a seed with the native WebCrypto PBKDF2 helper.\n * ```ts\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const seed = await mnemonicToSeedWebcrypto(mnem, 'password');\n * // => new Uint8Array([...64 bytes])\n * ```\n */\nexport function mnemonicToSeedWebcrypto(mnemonic, passphrase = '') {\n return pbkdf2web(sha512web, normalize(mnemonic).nfkd, psalt(passphrase), {\n c: 2048,\n dkLen: 64,\n });\n}\n//# sourceMappingURL=index.js.map","// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport { toHex } from '@mysten/bcs';\nimport { mnemonicToSeedSync as bip39MnemonicToSeedSync } from '@scure/bip39';\n\n/**\n * Parse and validate a path that is compliant to SLIP-0010 in form m/44'/784'/{account_index}'/{change_index}'/{address_index}'.\n *\n * @param path path string (e.g. `m/44'/784'/0'/0'/0'`).\n */\nexport function isValidHardenedPath(path: string): boolean {\n\tif (!new RegExp(\"^m\\\\/44'\\\\/784'\\\\/[0-9]+'\\\\/[0-9]+'\\\\/[0-9]+'+$\").test(path)) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n/**\n * Parse and validate a path that is compliant to BIP-32 in form m/54'/784'/{account_index}'/{change_index}/{address_index}\n * for Secp256k1 and m/74'/784'/{account_index}'/{change_index}/{address_index} for Secp256r1.\n *\n * Note that the purpose for Secp256k1 is registered as 54, to differentiate from Ed25519 with purpose 44.\n *\n * @param path path string (e.g. `m/54'/784'/0'/0/0`).\n */\nexport function isValidBIP32Path(path: string): boolean {\n\tif (!new RegExp(\"^m\\\\/(54|74)'\\\\/784'\\\\/[0-9]+'\\\\/[0-9]+\\\\/[0-9]+$\").test(path)) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n/**\n * Uses KDF to derive 64 bytes of key data from mnemonic with empty password.\n *\n * @param mnemonics 12 words string split by spaces.\n */\nexport function mnemonicToSeed(mnemonics: string): Uint8Array {\n\treturn bip39MnemonicToSeedSync(mnemonics, '');\n}\n\n/**\n * Derive the seed in hex format from a 12-word mnemonic string.\n *\n * @param mnemonics 12 words string split by spaces.\n */\nexport function mnemonicToSeedHex(mnemonics: string): string {\n\treturn toHex(mnemonicToSeed(mnemonics));\n}\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, type CHash, type Hash } from './utils.ts';\n\n/** Internal class for HMAC. */\nexport class _HMAC<T extends Hash<T>> implements Hash<_HMAC<T>> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, key: Uint8Array) {\n ahash(hash);\n abytes(key, undefined, 'key');\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf: Uint8Array): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n abytes(out, this.outputLen, 'output');\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest(): Uint8Array {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: _HMAC<T>): _HMAC<T> {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone(): _HMAC<T> {\n return this._cloneInto();\n }\n destroy(): void {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac: {\n (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array;\n create(hash: CHash, key: Uint8Array): _HMAC<any>;\n} = (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array =>\n new _HMAC<any>(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Uint8Array) => new _HMAC<any>(hash, key);\n","// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fromBase64, toBase64 } from '@mysten/bcs';\n\nimport { bcs } from '../bcs/index.js';\nimport { parseSerializedPasskeySignature } from '../keypairs/passkey/publickey.js';\nimport type { MultiSigStruct } from '../multisig/publickey.js';\nimport { parseSerializedZkLoginSignature } from '../zklogin/publickey.js';\nimport { parseSerializedKeypairSignature } from './publickey.js';\nimport type { PublicKey } from './publickey.js';\nimport type { SignatureScheme } from './signature-scheme.js';\nimport { SIGNATURE_FLAG_TO_SCHEME, SIGNATURE_SCHEME_TO_FLAG } from './signature-scheme.js';\n\n/**\n * Pair of signature and corresponding public key\n */\nexport type SerializeSignatureInput = {\n\tsignatureScheme: SignatureScheme;\n\t/** Base64-encoded signature */\n\tsignature: Uint8Array;\n\t/** Base64-encoded public key */\n\tpublicKey?: PublicKey;\n};\n\n/**\n * Takes in a signature, its associated signing scheme and a public key, then serializes this data\n */\nexport function toSerializedSignature({\n\tsignature,\n\tsignatureScheme,\n\tpublicKey,\n}: SerializeSignatureInput): string {\n\tif (!publicKey) {\n\t\tthrow new Error('`publicKey` is required');\n\t}\n\n\tconst pubKeyBytes = publicKey.toRawBytes();\n\tconst serializedSignature = new Uint8Array(1 + signature.length + pubKeyBytes.length);\n\tserializedSignature.set([SIGNATURE_SCHEME_TO_FLAG[signatureScheme]]);\n\tserializedSignature.set(signature, 1);\n\tserializedSignature.set(pubKeyBytes, 1 + signature.length);\n\treturn toBase64(serializedSignature);\n}\n\n/**\n * Decodes a serialized signature into its constituent components: the signature scheme, the actual signature, and the public key\n */\nexport function parseSerializedSignature(serializedSignature: string) {\n\tconst bytes = fromBase64(serializedSignature);\n\n\tconst signatureScheme =\n\t\tSIGNATURE_FLAG_TO_SCHEME[bytes[0] as keyof typeof SIGNATURE_FLAG_TO_SCHEME];\n\n\tswitch (signatureScheme) {\n\t\tcase 'Passkey':\n\t\t\treturn parseSerializedPasskeySignature(serializedSignature);\n\t\tcase 'MultiSig':\n\t\t\tconst multisig: MultiSigStruct = bcs.MultiSig.parse(bytes.slice(1));\n\t\t\treturn {\n\t\t\t\tserializedSignature,\n\t\t\t\tsignatureScheme,\n\t\t\t\tmultisig,\n\t\t\t\tbytes,\n\t\t\t\tsignature: undefined,\n\t\t\t};\n\t\tcase 'ZkLogin':\n\t\t\treturn parseSerializedZkLoginSignature(serializedSignature);\n\t\tcase 'ED25519':\n\t\tcase 'Secp256k1':\n\t\tcase 'Secp256r1':\n\t\t\treturn parseSerializedKeypairSignature(serializedSignature);\n\t\tdefault:\n\t\t\tthrow new Error('Unsupported signature scheme');\n\t}\n}\n","// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { bcs, toBase64 } from '@mysten/bcs';\nimport { blake2b } from '@noble/hashes/blake2.js';\nimport { bech32 } from '@scure/base';\n\nimport type { IntentScope } from './intent.js';\nimport { messageWithIntent } from './intent.js';\nimport type { PublicKey } from './publickey.js';\nimport { SIGNATURE_FLAG_TO_SCHEME, SIGNATURE_SCHEME_TO_FLAG } from './signature-scheme.js';\nimport type { SignatureScheme } from './signature-scheme.js';\nimport { toSerializedSignature } from './signature.js';\nimport type { Transaction } from '../transactions/Transaction.js';\nimport type { ClientWithCoreApi, SuiClientTypes } from '../client/index.js';\n\nexport const PRIVATE_KEY_SIZE = 32;\nexport const LEGACY_PRIVATE_KEY_SIZE = 64;\nexport const SUI_PRIVATE_KEY_PREFIX = 'suiprivkey';\n\nexport type ParsedKeypair = {\n\tscheme: SignatureScheme;\n\tsecretKey: Uint8Array;\n};\n\nexport interface SignatureWithBytes {\n\tbytes: string;\n\tsignature: string;\n}\n\nexport interface SignAndExecuteOptions {\n\ttransaction: Transaction;\n\tclient: ClientWithCoreApi;\n}\n\n/**\n * TODO: Document\n */\nexport abstract class Signer {\n\tabstract sign(bytes: Uint8Array): Promise<Uint8Array<ArrayBuffer>>;\n\t/**\n\t * Sign messages with a specific intent. By combining the message bytes with the intent before hashing and signing,\n\t * it ensures that a signed message is tied to a specific purpose and domain separator is provided\n\t */\n\tasync signWithIntent(bytes: Uint8Array, intent: IntentScope): Promise<SignatureWithBytes> {\n\t\tconst intentMessage = messageWithIntent(intent, bytes);\n\t\tconst digest = blake2b(intentMessage, { dkLen: 32 });\n\n\t\tconst signature = toSerializedSignature({\n\t\t\tsignature: await this.sign(digest),\n\t\t\tsignatureScheme: this.getKeyScheme(),\n\t\t\tpublicKey: this.getPublicKey(),\n\t\t});\n\n\t\treturn {\n\t\t\tsignature,\n\t\t\tbytes: toBase64(bytes),\n\t\t};\n\t}\n\t/**\n\t * Signs provided transaction by calling `signWithIntent()` with a `TransactionData` provided as intent scope\n\t */\n\tasync signTransaction(bytes: Uint8Array) {\n\t\treturn this.signWithIntent(bytes, 'TransactionData');\n\t}\n\t/**\n\t * Signs provided personal message by calling `signWithIntent()` with a `PersonalMessage` provided as intent scope\n\t */\n\tasync signPersonalMessage(bytes: Uint8Array) {\n\t\tconst { signature } = await this.signWithIntent(\n\t\t\tbcs.byteVector().serialize(bytes).toBytes(),\n\t\t\t'PersonalMessage',\n\t\t);\n\n\t\treturn {\n\t\t\tbytes: toBase64(bytes),\n\t\t\tsignature,\n\t\t};\n\t}\n\n\tasync signAndExecuteTransaction({\n\t\ttransaction,\n\t\tclient,\n\t}: SignAndExecuteOptions): Promise<\n\t\tSuiClientTypes.TransactionResult<{ transaction: true; effects: true }>\n\t> {\n\t\ttransaction.setSenderIfNotSet(this.toSuiAddress());\n\t\tconst bytes = await transaction.build({ client });\n\t\tconst { signature } = await this.signTransaction(bytes);\n\n\t\treturn client.core.executeTransaction({\n\t\t\ttransaction: bytes,\n\t\t\tsignatures: [signature],\n\t\t\tinclude: { transaction: true, effects: true },\n\t\t});\n\t}\n\n\ttoSuiAddress(): string {\n\t\treturn this.getPublicKey().toSuiAddress();\n\t}\n\n\t/**\n\t * Get the key scheme of the keypair: Secp256k1 or ED25519\n\t */\n\tabstract getKeyScheme(): SignatureScheme;\n\n\t/**\n\t * The public key for this keypair\n\t */\n\tabstract getPublicKey(): PublicKey;\n}\n\nexport abstract class Keypair extends Signer {\n\t/**\n\t * This returns the Bech32 secret key string for this keypair.\n\t */\n\tabstract getSecretKey(): string;\n}\n\n/**\n * This returns an ParsedKeypair object based by validating the\n * 33-byte Bech32 encoded string starting with `suiprivkey`, and\n * parse out the signature scheme and the private key in bytes.\n */\nexport function decodeSuiPrivateKey(value: string): ParsedKeypair {\n\tconst { prefix, words } = bech32.decode(value as `${string}1${string}`);\n\tif (prefix !== SUI_PRIVATE_KEY_PREFIX) {\n\t\tthrow new Error('invalid private key prefix');\n\t}\n\tconst extendedSecretKey = new Uint8Array(bech32.fromWords(words));\n\tconst secretKey = extendedSecretKey.slice(1);\n\tconst signatureScheme =\n\t\tSIGNATURE_FLAG_TO_SCHEME[extendedSecretKey[0] as keyof typeof SIGNATURE_FLAG_TO_SCHEME];\n\n\treturn {\n\t\tscheme: signatureScheme,\n\t\tsecretKey: secretKey,\n\t};\n}\n\n/**\n * This returns a Bech32 encoded string starting with `suiprivkey`,\n * encoding 33-byte `flag || bytes` for the given the 32-byte private\n * key and its signature scheme.\n */\nexport function encodeSuiPrivateKey(bytes: Uint8Array, scheme: SignatureScheme): string {\n\tif (bytes.length !== PRIVATE_KEY_SIZE) {\n\t\tthrow new Error('Invalid bytes length');\n\t}\n\tconst flag = SIGNATURE_SCHEME_TO_FLAG[scheme];\n\tconst privKeyBytes = new Uint8Array(bytes.length + 1);\n\tprivKeyBytes.set([flag]);\n\tprivKeyBytes.set(bytes, 1);\n\treturn bech32.encode(SUI_PRIVATE_KEY_PREFIX, bech32.toWords(privKeyBytes));\n}\n","// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\n// This is adapted from https://github.com/alepop/ed25519-hd-key replacing create-hmac\n// with @noble/hashes to be browser compatible.\n\nimport { fromHex } from '@mysten/bcs';\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { sha512 } from '@noble/hashes/sha2.js';\n\ntype Hex = string;\ntype Path = string;\n\ntype Keys = {\n\tkey: Uint8Array;\n\tchainCode: Uint8Array;\n};\n\nconst ED25519_CURVE = 'ed25519 seed';\nconst HARDENED_OFFSET = 0x80000000;\n\nconst pathRegex = new RegExp(\"^m(\\\\/[0-9]+')+$\");\n\nconst replaceDerive = (val: string): string => val.replace(\"'\", '');\n\nconst getMasterKeyFromSeed = (seed: Hex): Keys => {\n\tconst h = hmac.create(sha512, new TextEncoder().encode(ED25519_CURVE));\n\tconst I = h.update(fromHex(seed)).digest();\n\tconst IL = I.slice(0, 32);\n\tconst IR = I.slice(32);\n\treturn {\n\t\tkey: IL,\n\t\tchainCode: IR,\n\t};\n};\n\nconst CKDPriv = ({ key, chainCode }: Keys, index: number): Keys => {\n\tconst indexBuffer = new ArrayBuffer(4);\n\tconst cv = new DataView(indexBuffer);\n\tcv.setUint32(0, index);\n\n\tconst data = new Uint8Array(1 + key.length + indexBuffer.byteLength);\n\tdata.set(new Uint8Array(1).fill(0));\n\tdata.set(key, 1);\n\tdata.set(new Uint8Array(indexBuffer, 0, indexBuffer.byteLength), key.length + 1);\n\n\tconst I = hmac.create(sha512, chainCode).update(data).digest();\n\tconst IL = I.slice(0, 32);\n\tconst IR = I.slice(32);\n\treturn {\n\t\tkey: IL,\n\t\tchainCode: IR,\n\t};\n};\n\nconst isValidPath = (path: string): boolean => {\n\tif (!pathRegex.test(path)) {\n\t\treturn false;\n\t}\n\treturn !path\n\t\t.split('/')\n\t\t.slice(1)\n\t\t.map(replaceDerive)\n\t\t.some(isNaN as any /* ts T_T*/);\n};\n\nexport const derivePath = (path: Path, seed: Hex, offset = HARDENED_OFFSET): Keys => {\n\tif (!isValidPath(path)) {\n\t\tthrow new Error('Invalid derivation path');\n\t}\n\n\tconst { key, chainCode } = getMasterKeyFromSeed(seed);\n\tconst segments = path\n\t\t.split('/')\n\t\t.slice(1)\n\t\t.map(replaceDerive)\n\t\t.map((el) => parseInt(el, 10));\n\n\treturn segments.reduce((parentKeys, segment) => CKDPriv(parentKeys, segment + offset), {\n\t\tkey,\n\t\tchainCode,\n\t});\n};\n","// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { toHex } from '@mysten/bcs';\nimport { ed25519 } from '@noble/curves/ed25519.js';\n\nimport {\n\tdecodeSuiPrivateKey,\n\tencodeSuiPrivateKey,\n\tKeypair,\n\tPRIVATE_KEY_SIZE,\n} from '../../cryptography/keypair.js';\nimport { isValidHardenedPath, mnemonicToSeedHex } from '../../cryptography/mnemonics.js';\nimport type { SignatureScheme } from '../../cryptography/signature-scheme.js';\nimport { derivePath } from './ed25519-hd-key.js';\nimport { Ed25519PublicKey } from './publickey.js';\n\nexport const DEFAULT_ED25519_DERIVATION_PATH = \"m/44'/784'/0'/0'/0'\";\n\n/**\n * Ed25519 Keypair data. The publickey is the 32-byte public key and\n * the secretkey is 64-byte, where the first 32 bytes is the secret\n * key and the last 32 bytes is the public key.\n */\nexport interface Ed25519KeypairData {\n\tpublicKey: Uint8Array;\n\tsecretKey: Uint8Array;\n}\n\n/**\n * An Ed25519 Keypair used for signing transactions.\n */\nexport class Ed25519Keypair extends Keypair {\n\tprivate keypair: Ed25519KeypairData;\n\n\t/**\n\t * Create a new Ed25519 keypair instance.\n\t * Generate random keypair if no {@link Ed25519Keypair} is provided.\n\t *\n\t * @param keypair Ed25519 keypair\n\t */\n\tconstructor(keypair?: Ed25519KeypairData) {\n\t\tsuper();\n\t\tif (keypair) {\n\t\t\tthis.keypair = {\n\t\t\t\tpublicKey: keypair.publicKey,\n\t\t\t\tsecretKey: keypair.secretKey.slice(0, 32),\n\t\t\t};\n\t\t} else {\n\t\t\tconst privateKey = ed25519.utils.randomSecretKey();\n\t\t\tthis.keypair = {\n\t\t\t\tpublicKey: ed25519.getPublicKey(privateKey),\n\t\t\t\tsecretKey: privateKey,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Get the key scheme of the keypair ED25519\n\t */\n\tgetKeyScheme(): SignatureScheme {\n\t\treturn 'ED25519';\n\t}\n\n\t/**\n\t * Generate a new random Ed25519 keypair\n\t */\n\tstatic generate(): Ed25519Keypair {\n\t\tconst secretKey = ed25519.utils.randomSecretKey();\n\t\treturn new Ed25519Keypair({\n\t\t\tpublicKey: ed25519.getPublicKey(secretKey),\n\t\t\tsecretKey,\n\t\t});\n\t}\n\n\t/**\n\t * Create a Ed25519 keypair from a raw secret key byte array, also known as seed.\n\t * This is NOT the private scalar which is result of hashing and bit clamping of\n\t * the raw secret key.\n\t *\n\t * @throws error if the provided secret key is invalid and validation is not skipped.\n\t *\n\t * @param secretKey secret key as a byte array or Bech32 secret key string\n\t * @param options: skip secret key validation\n\t */\n\tstatic fromSecretKey(\n\t\tsecretKey: Uint8Array | string,\n\t\toptions?: { skipValidation?: boolean },\n\t): Ed25519Keypair {\n\t\tif (typeof secretKey === 'string') {\n\t\t\tconst decoded = decodeSuiPrivateKey(secretKey);\n\n\t\t\tif (decoded.scheme !== 'ED25519') {\n\t\t\t\tthrow new Error(`Expected a ED25519 keypair, got ${decoded.scheme}`);\n\t\t\t}\n\n\t\t\treturn this.fromSecretKey(decoded.secretKey, options);\n\t\t}\n\n\t\tconst secretKeyLength = secretKey.length;\n\t\tif (secretKeyLength !== PRIVATE_KEY_SIZE) {\n\t\t\tthrow new Error(\n\t\t\t\t`Wrong secretKey size. Expected ${PRIVATE_KEY_SIZE} bytes, got ${secretKeyLength}.`,\n\t\t\t);\n\t\t}\n\t\tconst keypair = {\n\t\t\tpublicKey: ed25519.getPublicKey(secretKey),\n\t\t\tsecretKey,\n\t\t};\n\n\t\tif (!options || !options.skipValidation) {\n\t\t\tconst encoder = new TextEncoder();\n\t\t\tconst signData = encoder.encode('sui validation');\n\t\t\tconst signature = ed25519.sign(signData, secretKey);\n\t\t\tif (!ed25519.verify(signature, signData, keypair.publicKey)) {\n\t\t\t\tthrow new Error('provided secretKey is invalid');\n\t\t\t}\n\t\t}\n\t\treturn new Ed25519Keypair(keypair);\n\t}\n\n\t/**\n\t * The public key for this Ed25519 keypair\n\t */\n\tgetPublicKey(): Ed25519PublicKey {\n\t\treturn new Ed25519PublicKey(this.keypair.publicKey);\n\t}\n\n\t/**\n\t * The Bech32 secret key string for this Ed25519 keypair\n\t */\n\tgetSecretKey(): string {\n\t\treturn encodeSuiPrivateKey(\n\t\t\tthis.keypair.secretKey.slice(0, PRIVATE_KEY_SIZE),\n\t\t\tthis.getKeyScheme(),\n\t\t);\n\t}\n\n\t/**\n\t * Return the signature for the provided data using Ed25519.\n\t */\n\tasync sign(data: Uint8Array) {\n\t\treturn ed25519.sign(data, this.keypair.secretKey) as Uint8Array<ArrayBuffer>;\n\t}\n\n\t/**\n\t * Derive Ed25519 keypair from mnemonics and path. The mnemonics must be normalized\n\t * and validated against the english wordlist.\n\t *\n\t * If path is none, it will default to m/44'/784'/0'/0'/0', otherwise the path must\n\t * be compliant to SLIP-0010 in form m/44'/784'/{account_index}'/{change_index}'/{address_index}'.\n\t */\n\tstatic deriveKeypair(mnemonics: string, path?: string): Ed25519Keypair {\n\t\tif (path == null) {\n\t\t\tpath = DEFAULT_ED25519_DERIVATION_PATH;\n\t\t}\n\t\tif (!isValidHardenedPath(path)) {\n\t\t\tthrow new Error('Invalid derivation path');\n\t\t}\n\t\tconst { key } = derivePath(path, mnemonicToSeedHex(mnemonics));\n\n\t\treturn Ed25519Keypair.fromSecretKey(key);\n\t}\n\n\t/**\n\t * Derive Ed25519 keypair from mnemonicSeed and path.\n\t *\n\t * If path is none, it will default to m/44'/784'/0'/0'/0', otherwise the path must\n\t * be compliant to SLIP-0010 in form m/44'/784'/{account_index}'/{change_index}'/{address_index}'.\n\t *\n\t * @param seed - The seed as a hex string or Uint8Array.\n\t */\n\tstatic deriveKeypairFromSeed(seed: string | Uint8Array, path?: string): Ed25519Keypair {\n\t\tif (path == null) {\n\t\t\tpath = DEFAULT_ED25519_DERIVATION_PATH;\n\t\t}\n\t\tif (!isValidHardenedPath(path)) {\n\t\t\tthrow new Error('Invalid derivation path');\n\t\t}\n\t\tconst seedHex = typeof seed === 'string' ? seed : toHex(seed);\n\t\tconst { key } = derivePath(path, seedHex);\n\n\t\treturn Ed25519Keypair.fromSecretKey(key);\n\t}\n}\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n isBytes as isBytes_,\n} from '@noble/hashes/utils.js';\nexport {\n abytes,\n anumber,\n bytesToHex,\n bytesToUtf8,\n concatBytes,\n hexToBytes,\n isBytes,\n randomBytes,\n utf8ToBytes,\n} from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function abool(title: string, value: boolean): void {\n if (typeof value !== 'boolean') throw new Error(title + ' boolean expected, got ' + value);\n}\n\n// tmp name until v2\nexport function _abool2(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\"`;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n// tmp name until v2\n/** Asserts something is Uint8Array. */\nexport function _abytes2(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n const bytes = isBytes_(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n\n// Used in weierstrass, der\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex_(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n abytes_(bytes);\n return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes_(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'secret key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes_(hex);\n } catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n } else if (isBytes_(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return Uint8Array.from(bytes);\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as utf8ToBytes for ASCII or throws.\n */\nexport function asciiToBytes(ascii: string): Uint8Array {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n });\n}\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\n// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\n// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;\n\n// Is positive bigint\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\ntype Pred<T> = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n const u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\n const u8of = (byte: number) => Uint8Array.of(byte); // another shortcut\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n(0)) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes_(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes_(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\n\nexport function validateObject<T extends Record<string, any>>(\n object: T,\n validators: ValMap<T>,\n optValidators: ValMap<T> = {}\n): T {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function') throw new Error('invalid validator function');\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n 'param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n\nexport function isHash(val: CHash): boolean {\n return typeof val === 'function' && Number.isSafeInteger(val.outputLen);\n}\nexport function _validateObject(\n object: Record<string, any>,\n fields: Record<string, string>,\n optFields: Record<string, string> = {}\n): void {\n if (!object || typeof object !== 'object') throw new Error('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));\n Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));\n}\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized<T extends object, R, O extends any[]>(\n fn: (arg: T, ...args: O) => R\n): (arg: T, ...args: O) => R {\n const map = new WeakMap<T, R>();\n return (arg: T, ...args: O): R => {\n const val = map.get(arg);\n if (val !== undefined) return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n _validateObject,\n anumber,\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n} from '../utils.ts';\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);\n// prettier-ignore\nconst _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\n}\n\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n) throw new Error('invert: expected non-zero number');\n if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\nfunction assertIsSquare<T>(Fp: IField<T>, root: T, n: T): void {\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4<T>(Fp: IField<T>, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\n\nfunction sqrt5mod8<T>(Fp: IField<T>, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n assertIsSquare(Fp, root, n);\n return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));// 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return <T>(Fp: IField<T>, n: T) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3);// 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: IField<T>, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n) return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint): boolean =>\n (mod(num, modulo) & _1n) === _1n;\n\n/** Field is not always over prime: for example, Fp2 has ORDER(q)=p^m. */\nexport interface IField<T> {\n ORDER: bigint;\n isLE: boolean;\n BYTES: number;\n BITS: number;\n MASK: bigint;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n isValidNot0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n allowedLengths?: number[];\n // legendre?(num: T): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array, skipValidation?: boolean): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField<T>(field: IField<T>): IField<T> {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n _validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow<T>(Fp: IField<T>, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch<T>(Fp: IField<T>, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv<T>(Fp: IField<T>, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n */\nexport function FpLegendre<T>(Fp: IField<T>, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare<T>(Fp: IField<T>, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\nexport type NLength = { nByteLength: number; nBitLength: number };\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number): NLength {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n sqrt: SqrtFn;\n isLE: boolean;\n BITS: number;\n modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes)\n}>;\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLenOrOpts?: number | FieldOpts, // TODO: use opts only in v2?\n isLE = false,\n opts: { sqrt?: SqrtFn } = {}\n): Readonly<FpField> {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength: number | undefined = undefined;\n let _sqrt: SqrtFn | undefined = undefined;\n let modFromBytes: boolean = false;\n let allowedLengths: undefined | readonly number[] = undefined;\n if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {\n if (opts.sqrt || isLE) throw new Error('cannot specify opts in two arguments');\n const _opts = bitLenOrOpts;\n if (_opts.BITS) _nbitLength = _opts.BITS;\n if (_opts.sqrt) _sqrt = _opts.sqrt;\n if (typeof _opts.isLE === 'boolean') isLE = _opts.isLE;\n if (typeof _opts.modFromBytes === 'boolean') modFromBytes = _opts.modFromBytes;\n allowedLengths = _opts.allowedLengths;\n } else {\n if (typeof bitLenOrOpts === 'number') _nbitLength = bitLenOrOpts;\n if (opts.sqrt) _sqrt = opts.sqrt;\n }\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);\n if (BYTES > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP: ReturnType<typeof FpSqrt>; // cached sqrtP\n const f: Readonly<FpField> = Object.freeze({\n ORDER,\n isLE,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n allowedLengths: allowedLengths,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n // is valid and invertible\n isValidNot0: (num: bigint) => !f.is0(num) && f.isValid(num),\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt:\n _sqrt ||\n ((n) => {\n if (!sqrtP) sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes, skipValidation = true) => {\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error(\n 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n );\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes) scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!f.isValid(scalar)) throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n },\n // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n } as FpField);\n return Object.freeze(f);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\n\nexport function FpSqrtOdd<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(\n 'hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen\n );\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, validateObject } from '../utils.ts';\nimport { Field, FpInvertBatch, nLength, validateField, type IField } from './modular.ts';\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint<T> = {\n x: T;\n y: T;\n} & { Z?: never };\n\n// This was initialy do this way to re-use montgomery ladder in field (add->mul,double->sqr), but\n// that didn't happen and there is probably not much reason to have separate Group like this?\nexport interface Group<T extends Group<T>> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n toAffine?(invertedZ?: any): AffinePoint<any>;\n}\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic curve Points. */\nexport interface CurvePoint<F, P extends CurvePoint<F, P>> extends Group<P> {\n /** Affine x coordinate. Different from projective / extended X coordinate. */\n x: F;\n /** Affine y coordinate. Different from projective / extended Y coordinate. */\n y: F;\n Z?: F;\n double(): P;\n negate(): P;\n add(other: P): P;\n subtract(other: P): P;\n equals(other: P): boolean;\n multiply(scalar: bigint): P;\n assertValidity(): void;\n clearCofactor(): P;\n is0(): boolean;\n isTorsionFree(): boolean;\n isSmallOrder(): boolean;\n multiplyUnsafe(scalar: bigint): P;\n /**\n * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n * @param isLazy calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n */\n precompute(windowSize?: number, isLazy?: boolean): P;\n /** Converts point to 2D xy affine coordinates */\n toAffine(invertedZ?: F): AffinePoint<F>;\n toBytes(): Uint8Array;\n toHex(): string;\n}\n\n/** Base interface for all elliptic curve Point constructors. */\nexport interface CurvePointCons<P extends CurvePoint<any, P>> {\n [Symbol.hasInstance]: (item: unknown) => boolean;\n BASE: P;\n ZERO: P;\n /** Field for basic curve math */\n Fp: IField<P_F<P>>;\n /** Scalar field, for scalars in multiply and others */\n Fn: IField<bigint>;\n /** Creates point from x, y. Does NOT validate if the point is valid. Use `.assertValidity()`. */\n fromAffine(p: AffinePoint<P_F<P>>): P;\n fromBytes(bytes: Uint8Array): P;\n fromHex(hex: Uint8Array | string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint<PC>': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint<PC>': it won't be accesible for arguments/return types\n// * `CurvePointCons<P extends CurvePoint<any, P>>` constraints from interface definition\n// won't propagate, if `PC extends CurvePointCons<any>`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint<any, P>.\n// this means we need to do stuff like\n// `function test<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(`\n// if we want type safety around P, otherwise PC_P<PC> will be any\n\n/** Returns Fp type from Point (P_F<P> == P.F) */\nexport type P_F<P extends CurvePoint<any, P>> = P extends CurvePoint<infer F, P> ? F : never;\n/** Returns Fp type from PointCons (PC_F<PC> == PC.P.F) */\nexport type PC_F<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['Fp']['ZERO'];\n/** Returns Point type from PointCons (PC_P<PC> == PC.P) */\nexport type PC_P<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons<CurvePoint<any, any>>`, will return `any` after 1 operation\n// * `CurvePointCons<any>: WeierstrassPointCons<bigint> extends CurvePointCons<any> = false`\n// * `P extends CurvePoint, PC extends CurvePointCons<P>`\n// * It can't infer P from PC alone\n// * Too many relations between F, P & PC\n// * It will infer P/F if `arg: CurvePointCons<F, P>`, but will fail if PC is generic\n// * It will work correctly if there is an additional argument of type P\n// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n// types, making them un-inferable\n// prettier-ignore\nexport type PC_ANY = CurvePointCons<\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any, any>\n >>>>>>>>>\n>;\n\nexport interface CurveLengths {\n secretKey?: number;\n publicKey?: number;\n publicKeyUncompressed?: number;\n publicKeyHasPrefix?: boolean;\n signature?: number;\n seed?: number;\n}\nexport type GroupConstructor<T> = {\n BASE: T;\n ZERO: T;\n};\n/** @deprecated */\nexport type ExtendedGroupConstructor<T> = GroupConstructor<T> & {\n Fp: IField<any>;\n Fn: IField<bigint>;\n fromAffine(ap: AffinePoint<any>): T;\n};\nexport type Mapper<T> = (i: T[]) => T[];\n\nexport function negateCt<T extends { negate: () => T }>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\n}\n\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\nexport function normalizeZ<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[]\n): P[] {\n const invertedZs = FpInvertBatch(\n c.Fp,\n points.map((p) => p.Z!)\n );\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\n\nfunction validateW(W: number, bits: number) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\n/** Internal wNAF opts for specific W and scalarBits */\nexport type WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n if (!Array.isArray(points)) throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap<any, any[]>();\nconst pointWindowSizes = new WeakMap<any, number>();\n\nfunction getW(P: any): number {\n // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF<PC extends PC_ANY> {\n private readonly BASE: PC_P<PC>;\n private readonly ZERO: PC_P<PC>;\n private readonly Fn: PC['Fn'];\n readonly bits: number;\n\n // Parametrized with a given Point class (not individual point)\n constructor(Point: PC, bits: number) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n\n // non-const time multiplication ladder\n _unsafeLadder(elm: PC_P<PC>, n: bigint, p: PC_P<PC> = this.ZERO): PC_P<PC> {\n let d: PC_P<PC> = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n private precomputeWindow(point: PC_P<PC>, W: number): PC_P<PC>[] {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points: PC_P<PC>[] = [];\n let p: PC_P<PC> = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n private wNAF(W: number, precomputes: PC_P<PC>[], n: bigint): { p: PC_P<PC>; f: PC_P<PC> } {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points: JIT won't eliminate f.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n }\n\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n private wNAFUnsafe(\n W: number,\n precomputes: PC_P<PC>[],\n n: bigint,\n acc: PC_P<PC> = this.ZERO\n ): PC_P<PC> {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n\n private getPrecomputes(W: number, point: PC_P<PC>, transform?: Mapper<PC_P<PC>>): PC_P<PC>[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W) as PC_P<PC>[];\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function') comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n\n cached(\n point: PC_P<PC>,\n scalar: bigint,\n transform?: Mapper<PC_P<PC>>\n ): { p: PC_P<PC>; f: PC_P<PC> } {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n\n unsafe(point: PC_P<PC>, scalar: bigint, transform?: Mapper<PC_P<PC>>, prev?: PC_P<PC>): PC_P<PC> {\n const W = getW(point);\n if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P: PC_P<PC>, W: number): void {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n\n hasCache(elm: PC_P<PC>): boolean {\n return getW(elm) !== 1;\n }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n Point: PC,\n point: P,\n k1: bigint,\n k2: bigint\n): { p1: P; p2: P } {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) p1 = p1.add(acc);\n if (k2 & _1n) p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka secret keys / bigints)\n */\nexport function pippenger<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n fieldN: IField<bigint>,\n points: P[],\n scalars: bigint[]\n): P {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as P;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n fieldN: IField<bigint>,\n points: P[],\n windowSize: number\n): (scalars: bigint[]) => P {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p: P) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars: bigint[]): P => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr) continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n\n// TODO: remove\n/**\n * Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n * Though generator can be different (Fp2 / Fp6 for BLS).\n */\nexport type BasicCurve<T> = {\n Fp: IField<T>; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\n// TODO: remove\n/** @deprecated */\nexport function validateBasic<FP, T>(\n curve: BasicCurve<FP> & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve<FP> &\n T & {\n p: bigint;\n }\n> {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\n}\n\nexport type ValidCurveParams<T> = {\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b?: T;\n d?: T;\n Gx: T;\n Gy: T;\n};\n\nfunction createField<T>(order: bigint, field?: IField<T>, isLE?: boolean): IField<T> {\n if (field) {\n if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n } else {\n return Field(order, { isLE }) as unknown as IField<T>;\n }\n}\nexport type FpFn<T> = { Fp: IField<T>; Fn: IField<bigint> };\n\n/** Validates CURVE opts and creates fields */\nexport function _createCurveFields<T>(\n type: 'weierstrass' | 'edwards',\n CURVE: ValidCurveParams<T>,\n curveOpts: Partial<FpFn<T>> = {},\n FpFnLE?: boolean\n): FpFn<T> & { CURVE: ValidCurveParams<T> } {\n if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h'] as const) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b] as const;\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n","/**\n * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².\n * For design rationale of types / exports, see weierstrass module documentation.\n * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n _validateObject,\n _abool2 as abool,\n _abytes2 as abytes,\n aInRange,\n bytesToHex,\n bytesToNumberLE,\n concatBytes,\n copyBytes,\n ensureBytes,\n isBytes,\n memoized,\n notImplemented,\n randomBytes as randomBytesWeb,\n type FHash,\n type Hex,\n} from '../utils.ts';\nimport {\n _createCurveFields,\n normalizeZ,\n pippenger,\n wNAF,\n type AffinePoint,\n type BasicCurve,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport { Field, type IField, type NLength } from './modular.ts';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n\nexport type UVRatio = (u: bigint, v: bigint) => { isValid: boolean; value: bigint };\n\n/** Instance of Extended Point with coordinates in X, Y, Z, T. */\nexport interface EdwardsPoint extends CurvePoint<bigint, EdwardsPoint> {\n /** extended X coordinate. Different from affine x. */\n readonly X: bigint;\n /** extended Y coordinate. Different from affine y. */\n readonly Y: bigint;\n /** extended Z coordinate */\n readonly Z: bigint;\n /** extended T coordinate */\n readonly T: bigint;\n\n /** @deprecated use `toBytes` */\n toRawBytes(): Uint8Array;\n /** @deprecated use `p.precompute(windowSize)` */\n _setWindowSize(windowSize: number): void;\n /** @deprecated use .X */\n readonly ex: bigint;\n /** @deprecated use .Y */\n readonly ey: bigint;\n /** @deprecated use .Z */\n readonly ez: bigint;\n /** @deprecated use .T */\n readonly et: bigint;\n}\n/** Static methods of Extended Point with coordinates in X, Y, Z, T. */\nexport interface EdwardsPointCons extends CurvePointCons<EdwardsPoint> {\n new (X: bigint, Y: bigint, Z: bigint, T: bigint): EdwardsPoint;\n CURVE(): EdwardsOpts;\n fromBytes(bytes: Uint8Array, zip215?: boolean): EdwardsPoint;\n fromHex(hex: Hex, zip215?: boolean): EdwardsPoint;\n /** @deprecated use `import { pippenger } from '@noble/curves/abstract/curve.js';` */\n msm(points: EdwardsPoint[], scalars: bigint[]): EdwardsPoint;\n}\n/** @deprecated use EdwardsPoint */\nexport type ExtPointType = EdwardsPoint;\n/** @deprecated use EdwardsPointCons */\nexport type ExtPointConstructor = EdwardsPointCons;\n\n/**\n * Twisted Edwards curve options.\n *\n * * a: formula param\n * * d: formula param\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor. h*n is group order; n is subgroup order\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type EdwardsOpts = Readonly<{\n p: bigint;\n n: bigint;\n h: bigint;\n a: bigint;\n d: bigint;\n Gx: bigint;\n Gy: bigint;\n}>;\n\n/**\n * Extra curve options for Twisted Edwards.\n *\n * * Fp: redefined Field over curve.p\n * * Fn: redefined Field over curve.n\n * * uvRatio: helper function for decompression, calculating √(u/v)\n */\nexport type EdwardsExtraOpts = Partial<{\n Fp: IField<bigint>;\n Fn: IField<bigint>;\n FpFnLE: boolean;\n uvRatio: (u: bigint, v: bigint) => { isValid: boolean; value: bigint };\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) options.\n *\n * * hash: hash function used to hash secret keys and messages\n * * adjustScalarBytes: clears bits to get valid field element\n * * domain: Used for hashing\n * * mapToCurve: for hash-to-curve standard\n * * prehash: RFC 8032 pre-hashing of messages to sign() / verify()\n * * randomBytes: function generating random bytes, used for randomSecretKey\n */\nexport type EdDSAOpts = Partial<{\n adjustScalarBytes: (bytes: Uint8Array) => Uint8Array;\n domain: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;\n mapToCurve: (scalar: bigint[]) => AffinePoint<bigint>;\n prehash: FHash;\n randomBytes: (bytesLength?: number) => Uint8Array;\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) interface.\n *\n * Allows to create and verify signatures, create public and secret keys.\n */\nexport interface EdDSA {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Hex) => Uint8Array;\n sign: (message: Hex, secretKey: Hex, options?: { context?: Hex }) => Uint8Array;\n verify: (\n sig: Hex,\n message: Hex,\n publicKey: Hex,\n options?: { context?: Hex; zip215: boolean }\n ) => boolean;\n Point: EdwardsPointCons;\n utils: {\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n isValidSecretKey: (secretKey: Uint8Array) => boolean;\n isValidPublicKey: (publicKey: Uint8Array, zip215?: boolean) => boolean;\n\n /**\n * Converts ed public key to x public key.\n *\n * There is NO `fromMontgomery`:\n * - There are 2 valid ed25519 points for every x25519, with flipped coordinate\n * - Sometimes there are 0 valid ed25519 points, because x25519 *additionally*\n * accepts inputs on the quadratic twist, which can't be moved to ed25519\n *\n * @example\n * ```js\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomSecretKey());\n * const aPriv = x25519.utils.randomSecretKey();\n * x25519.getSharedSecret(aPriv, ed25519.utils.toMontgomery(someonesPub))\n * ```\n */\n toMontgomery: (publicKey: Uint8Array) => Uint8Array;\n /**\n * Converts ed secret key to x secret key.\n * @example\n * ```js\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomSecretKey());\n * const aPriv = ed25519.utils.randomSecretKey();\n * x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(aPriv), someonesPub)\n * ```\n */\n toMontgomerySecret: (privateKey: Uint8Array) => Uint8Array;\n getExtendedPublicKey: (key: Hex) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: EdwardsPoint;\n pointBytes: Uint8Array;\n };\n\n /** @deprecated use `randomSecretKey` */\n randomPrivateKey: (seed?: Uint8Array) => Uint8Array;\n /** @deprecated use `point.precompute()` */\n precompute: (windowSize?: number, point?: EdwardsPoint) => EdwardsPoint;\n };\n lengths: CurveLengths;\n}\n\nfunction isEdValidXY(Fp: IField<bigint>, CURVE: EdwardsOpts, x: bigint, y: bigint): boolean {\n const x2 = Fp.sqr(x);\n const y2 = Fp.sqr(y);\n const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n return Fp.eql(left, right);\n}\n\nexport function edwards(params: EdwardsOpts, extraOpts: EdwardsExtraOpts = {}): EdwardsPointCons {\n const validated = _createCurveFields('edwards', params, extraOpts, extraOpts.FpFnLE);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE as EdwardsOpts;\n const { h: cofactor } = CURVE;\n _validateObject(extraOpts, {}, { uvRatio: 'function' });\n\n // Important:\n // There are some places where Fp.BYTES is used instead of nByteLength.\n // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n // TODO: test and find curves which behave otherwise.\n const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n);\n const modP = (n: bigint) => Fp.create(n); // Function overrides\n\n // sqrt(u/v)\n const uvRatio =\n extraOpts.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n\n // Validate whether the passed curve params are valid.\n // equation ax² + y² = 1 + dx²y² should work for generator point.\n if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n\n /**\n * Asserts coordinate is valid: 0 <= n < MASK.\n * Coordinates >= Fp.ORDER are allowed for zip215.\n */\n function acoord(title: string, n: bigint, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n return n;\n }\n\n function aextpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p: Point, iz?: bigint): AffinePoint<bigint> => {\n const { X, Y, Z } = p;\n const is0 = p.is0();\n if (iz == null) iz = is0 ? _8n : (Fp.inv(Z) as bigint); // 8 was chosen arbitrarily\n const x = modP(X * iz);\n const y = modP(Y * iz);\n const zz = Fp.mul(Z, iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x, y };\n });\n const assertValidMemo = memoized((p: Point) => {\n const { a, d } = CURVE;\n if (p.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { X, Y, Z, T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right) throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n return true;\n });\n\n // Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point implements EdwardsPoint {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n // zero / infinity / identity point\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: bigint;\n readonly Y: bigint;\n readonly Z: bigint;\n readonly T: bigint;\n\n constructor(X: bigint, Y: bigint, Z: bigint, T: bigint) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y);\n this.Z = acoord('z', Z, true);\n this.T = acoord('t', T);\n Object.freeze(this);\n }\n\n static CURVE(): EdwardsOpts {\n return CURVE;\n }\n\n static fromAffine(p: AffinePoint<bigint>): Point {\n if (p instanceof Point) throw new Error('extended point not allowed');\n const { x, y } = p || {};\n acoord('x', x);\n acoord('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n\n // Uses algo from RFC8032 5.1.3.\n static fromBytes(bytes: Uint8Array, zip215 = false): Point {\n const len = Fp.BYTES;\n const { a, d } = CURVE;\n bytes = copyBytes(abytes(bytes, len, 'point'));\n abool(zip215, 'zip215');\n const normed = copyBytes(bytes); // copy again, we'll manipulate it\n const lastByte = bytes[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = bytesToNumberLE(normed);\n\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n aInRange('point.y', y, _0n, max);\n\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid) throw new Error('bad point: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('bad point: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromHex(bytes: Uint8Array, zip215 = false): Point {\n return Point.fromBytes(ensureBytes('point', bytes), zip215);\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n precompute(windowSize: number = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_2n); // random number\n return this;\n }\n\n // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n aextpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n negate(): Point {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));\n }\n\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double(): Point {\n const { a } = CURVE;\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other: Point) {\n aextpoint(other);\n const { a, d } = CURVE;\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n subtract(other: Point): Point {\n return this.add(other.negate());\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n // 1 <= scalar < L\n if (!Fn.isValidNot0(scalar)) throw new Error('invalid scalar: expected 1 <= sc < curve.n');\n const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));\n return normalizeZ(Point, [p, f])[0];\n }\n\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n // Accepts optional accumulator to merge with multiply (important for sparse scalars)\n multiplyUnsafe(scalar: bigint, acc = Point.ZERO): Point {\n // 0 <= scalar < L\n if (!Fn.isValid(scalar)) throw new Error('invalid scalar: expected 0 <= sc < curve.n');\n if (scalar === _0n) return Point.ZERO;\n if (this.is0() || scalar === _1n) return this;\n return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);\n }\n\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree(): boolean {\n return wnaf.unsafe(this, CURVE.n).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n return toAffineMemo(this, invertedZ);\n }\n\n clearCofactor(): Point {\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n toBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n // Fp.toBytes() allows non-canonical encoding of y (>= p).\n const bytes = Fp.toBytes(y);\n // Each y has 2 valid points: (x, y), (x,-y).\n // When compressing, it's enough to store y and use the last byte to encode sign of x\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;\n return bytes;\n }\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n\n // TODO: remove\n get ex(): bigint {\n return this.X;\n }\n get ey(): bigint {\n return this.Y;\n }\n get ez(): bigint {\n return this.Z;\n }\n get et(): bigint {\n return this.T;\n }\n static normalizeZ(points: Point[]): Point[] {\n return normalizeZ(Point, points);\n }\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n _setWindowSize(windowSize: number) {\n this.precompute(windowSize);\n }\n toRawBytes(): Uint8Array {\n return this.toBytes();\n }\n }\n const wnaf = new wNAF(Point, Fn.BITS);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points.\n */\nexport abstract class PrimeEdwardsPoint<T extends PrimeEdwardsPoint<T>>\n implements CurvePoint<bigint, T>\n{\n static BASE: PrimeEdwardsPoint<any>;\n static ZERO: PrimeEdwardsPoint<any>;\n static Fp: IField<bigint>;\n static Fn: IField<bigint>;\n\n protected readonly ep: EdwardsPoint;\n\n constructor(ep: EdwardsPoint) {\n this.ep = ep;\n }\n\n // Abstract methods that must be implemented by subclasses\n abstract toBytes(): Uint8Array;\n abstract equals(other: T): boolean;\n\n // Static methods that must be implemented by subclasses\n static fromBytes(_bytes: Uint8Array): any {\n notImplemented();\n }\n\n static fromHex(_hex: Hex): any {\n notImplemented();\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n // Common implementations\n clearCofactor(): T {\n // no-op for prime-order groups\n return this as any;\n }\n\n assertValidity(): void {\n this.ep.assertValidity();\n }\n\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n return this.ep.toAffine(invertedZ);\n }\n\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n isTorsionFree(): boolean {\n return true;\n }\n\n isSmallOrder(): boolean {\n return false;\n }\n\n add(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.add(other.ep));\n }\n\n subtract(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): T {\n return this.init(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): T {\n return this.init(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): T {\n return this.init(this.ep.double());\n }\n\n negate(): T {\n return this.init(this.ep.negate());\n }\n\n precompute(windowSize?: number, isLazy?: boolean): T {\n return this.init(this.ep.precompute(windowSize, isLazy));\n }\n\n // Helper methods\n abstract is0(): boolean;\n protected abstract assertSame(other: T): void;\n protected abstract init(ep: EdwardsPoint): T;\n\n /** @deprecated use `toBytes` */\n toRawBytes(): Uint8Array {\n return this.toBytes();\n }\n}\n\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n */\nexport function eddsa(Point: EdwardsPointCons, cHash: FHash, eddsaOpts: EdDSAOpts = {}): EdDSA {\n if (typeof cHash !== 'function') throw new Error('\"hash\" function param is required');\n _validateObject(\n eddsaOpts,\n {},\n {\n adjustScalarBytes: 'function',\n randomBytes: 'function',\n domain: 'function',\n prehash: 'function',\n mapToCurve: 'function',\n }\n );\n\n const { prehash } = eddsaOpts;\n const { BASE, Fp, Fn } = Point;\n\n const randomBytes = eddsaOpts.randomBytes || randomBytesWeb;\n const adjustScalarBytes = eddsaOpts.adjustScalarBytes || ((bytes: Uint8Array) => bytes);\n const domain =\n eddsaOpts.domain ||\n ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => {\n abool(phflag, 'phflag');\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n }\n\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key: Hex) {\n const len = lengths.secretKey;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n return { head, prefix, scalar };\n }\n\n /** Convenience method that creates public key from scalar. RFC8032 5.1.5 */\n function getExtendedPublicKey(secretKey: Hex) {\n const { head, prefix, scalar } = getPrivateScalar(secretKey);\n const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toBytes();\n return { head, prefix, scalar, point, pointBytes };\n }\n\n /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n function getPublicKey(secretKey: Hex): Uint8Array {\n return getExtendedPublicKey(secretKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Hex = Uint8Array.of(), ...msgs: Uint8Array[]) {\n const msg = concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg: Hex, secretKey: Hex, options: { context?: Hex } = {}): Uint8Array {\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = BASE.multiply(r).toBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n if (!Fn.isValid(s)) throw new Error('sign failed: invalid s'); // 0 <= s < L\n const rs = concatBytes(R, Fn.toBytes(s));\n return abytes(rs, lengths.signature, 'result');\n }\n\n // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\n const verifyOpts: { context?: Hex; zip215?: boolean } = { zip215: true };\n\n /**\n * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n * An extended group equation is checked.\n */\n function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean {\n const { context, zip215 } = options;\n const len = lengths.signature;\n sig = ensureBytes('signature', sig, len);\n msg = ensureBytes('message', msg);\n publicKey = ensureBytes('publicKey', publicKey, lengths.publicKey);\n if (zip215 !== undefined) abool(zip215, 'zip215');\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const mid = len / 2;\n const r = sig.subarray(0, mid);\n const s = bytesToNumberLE(sig.subarray(mid, len));\n let A, R, SB;\n try {\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false; // zip215 allows public keys of small order\n\n const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Extended group equation\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n }\n\n const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n const lengths = {\n secretKey: _size,\n publicKey: _size,\n signature: 2 * _size,\n seed: _size,\n };\n function randomSecretKey(seed = randomBytes(lengths.seed)): Uint8Array {\n return abytes(seed, lengths.seed, 'seed');\n }\n function keygen(seed?: Uint8Array) {\n const secretKey = utils.randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n }\n function isValidSecretKey(key: Uint8Array): boolean {\n return isBytes(key) && key.length === Fn.BYTES;\n }\n function isValidPublicKey(key: Uint8Array, zip215?: boolean): boolean {\n try {\n return !!Point.fromBytes(key, zip215);\n } catch (error) {\n return false;\n }\n }\n\n const utils = {\n getExtendedPublicKey,\n randomSecretKey,\n isValidSecretKey,\n isValidPublicKey,\n /**\n * Converts ed public key to x public key. Uses formula:\n * - ed25519:\n * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * - ed448:\n * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n */\n toMontgomery(publicKey: Uint8Array): Uint8Array {\n const { y } = Point.fromBytes(publicKey);\n const size = lengths.publicKey;\n const is25519 = size === 32;\n if (!is25519 && size !== 57) throw new Error('only defined for 25519 and 448');\n const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);\n return Fp.toBytes(u);\n },\n\n toMontgomerySecret(secretKey: Uint8Array): Uint8Array {\n const size = lengths.secretKey;\n abytes(secretKey, size);\n const hashed = cHash(secretKey.subarray(0, size));\n return adjustScalarBytes(hashed).subarray(0, size);\n },\n\n /** @deprecated */\n randomPrivateKey: randomSecretKey,\n /** @deprecated */\n precompute(windowSize = 8, point: EdwardsPoint = Point.BASE): EdwardsPoint {\n return point.precompute(windowSize, false);\n },\n };\n\n return Object.freeze({\n keygen,\n getPublicKey,\n sign,\n verify,\n utils,\n Point,\n lengths,\n });\n}\n\n// TODO: remove everything below\nexport type CurveType = BasicCurve<bigint> & {\n a: bigint; // curve param a\n d: bigint; // curve param d\n /** @deprecated the property will be removed in next release */\n hash: FHash; // Hashing\n randomBytes?: (bytesLength?: number) => Uint8Array; // CSPRNG\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing\n uvRatio?: UVRatio; // Ratio √(u/v)\n prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify()\n mapToCurve?: (scalar: bigint[]) => AffinePoint<bigint>; // for hash-to-curve standard\n};\nexport type CurveTypeWithLength = Readonly<CurveType & Partial<NLength>>;\nexport type CurveFn = {\n /** @deprecated the property will be removed in next release */\n CURVE: CurveType;\n keygen: EdDSA['keygen'];\n getPublicKey: EdDSA['getPublicKey'];\n sign: EdDSA['sign'];\n verify: EdDSA['verify'];\n Point: EdwardsPointCons;\n /** @deprecated use `Point` */\n ExtendedPoint: EdwardsPointCons;\n utils: EdDSA['utils'];\n lengths: CurveLengths;\n};\nexport type EdComposed = {\n CURVE: EdwardsOpts;\n curveOpts: EdwardsExtraOpts;\n hash: FHash;\n eddsaOpts: EdDSAOpts;\n};\nfunction _eddsa_legacy_opts_to_new(c: CurveTypeWithLength): EdComposed {\n const CURVE: EdwardsOpts = {\n a: c.a,\n d: c.d,\n p: c.Fp.ORDER,\n n: c.n,\n h: c.h,\n Gx: c.Gx,\n Gy: c.Gy,\n };\n const Fp = c.Fp;\n const Fn = Field(CURVE.n, c.nBitLength, true);\n const curveOpts: EdwardsExtraOpts = { Fp, Fn, uvRatio: c.uvRatio };\n const eddsaOpts: EdDSAOpts = {\n randomBytes: c.randomBytes,\n adjustScalarBytes: c.adjustScalarBytes,\n domain: c.domain,\n prehash: c.prehash,\n mapToCurve: c.mapToCurve,\n };\n return { CURVE, curveOpts, hash: c.hash, eddsaOpts };\n}\nfunction _eddsa_new_output_to_legacy(c: CurveTypeWithLength, eddsa: EdDSA): CurveFn {\n const Point = eddsa.Point;\n const legacy = Object.assign({}, eddsa, {\n ExtendedPoint: Point,\n CURVE: c,\n nBitLength: Point.Fn.BITS,\n nByteLength: Point.Fn.BYTES,\n });\n return legacy;\n}\n// TODO: remove. Use eddsa\nexport function twistedEdwards(c: CurveTypeWithLength): CurveFn {\n const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);\n const Point = edwards(CURVE, curveOpts);\n const EDDSA = eddsa(Point, hash, eddsaOpts);\n return _eddsa_new_output_to_legacy(c, EDDSA);\n}\n","/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, utf8ToBytes } from '@noble/hashes/utils.js';\nimport { pippenger, type AffinePoint } from './abstract/curve.ts';\nimport {\n PrimeEdwardsPoint,\n twistedEdwards,\n type CurveFn,\n type EdwardsOpts,\n type EdwardsPoint,\n} from './abstract/edwards.ts';\nimport {\n _DST_scalar,\n createHasher,\n expand_message_xmd,\n type H2CHasher,\n type H2CHasherBase,\n type H2CMethod,\n type htfBasicOpts,\n} from './abstract/hash-to-curve.ts';\nimport {\n Field,\n FpInvertBatch,\n FpSqrtEven,\n isNegativeLE,\n mod,\n pow2,\n type IField,\n} from './abstract/modular.ts';\nimport { montgomery, type MontgomeryECDH as XCurveFn } from './abstract/montgomery.ts';\nimport { bytesToNumberLE, ensureBytes, equalBytes, type Hex } from './utils.ts';\n\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\n\n// P = 2n**255n-19n\nconst ed25519_CURVE_p = BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed'\n);\n\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE: EdwardsOpts = /* @__PURE__ */ (() => ({\n p: ed25519_CURVE_p,\n n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n h: _8n,\n a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ed25519_CURVE_p;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\n\nfunction adjustScalarBytes(bytes: Uint8Array): Uint8Array {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n\n// √(-1) aka √(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt(\n '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ed25519_CURVE_p;\n const v3 = mod(v * v * v, P); // v³\n const v7 = mod(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P)) x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n\nconst Fp = /* @__PURE__ */ (() => Field(ed25519_CURVE.p, { isLE: true }))();\nconst Fn = /* @__PURE__ */ (() => Field(ed25519_CURVE.n, { isLE: true }))();\n\nconst ed25519Defaults = /* @__PURE__ */ (() => ({\n ...ed25519_CURVE,\n Fp,\n hash: sha512,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/√v\n uvRatio,\n}))();\n\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * import { ed25519 } from '@noble/curves/ed25519';\n * const { secretKey, publicKey } = ed25519.keygen();\n * const msg = new TextEncoder().encode('hello');\n * const sig = ed25519.sign(msg, priv);\n * ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215\n * ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5\n */\nexport const ed25519: CurveFn = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();\n\nfunction ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n utf8ToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\n/** Context of ed25519. Uses context for domain separation. */\nexport const ed25519ctx: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n }))();\n\n/** Prehashed version of ed25519. Accepts already-hashed messages in sign() and verify(). */\nexport const ed25519ph: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards(\n Object.assign({}, ed25519Defaults, {\n domain: ed25519_domain,\n prehash: sha512,\n })\n ))();\n\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * import { x25519 } from '@noble/curves/ed25519';\n * const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4';\n * const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c';\n * x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases\n * x25519.getPublicKey(priv) === x25519.scalarMultBase(priv);\n * x25519.getPublicKey(x25519.utils.randomSecretKey());\n */\nexport const x25519: XCurveFn = /* @__PURE__ */ (() => {\n const P = Fp.ORDER;\n return montgomery({\n P,\n type: 'x25519',\n powPminus2: (x: bigint): bigint => {\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n });\n})();\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u: bigint) {\n const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J);// 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd!(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n\n/** Hashing to ed25519 points / field. RFC 9380 methods. */\nexport const ed25519_hasher: H2CHasher<bigint> = /* @__PURE__ */ (() =>\n createHasher(\n ed25519.Point,\n (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: ed25519_CURVE_p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\n\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d²\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)²\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/√(number)\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = /* @__PURE__ */ BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n);\nconst bytes255ToNumberLE = (bytes: Uint8Array) =>\n ed25519.Point.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\ntype ExtendedPoint = EdwardsPoint;\n\n/**\n * Computes Elligator map for Ristretto255.\n * Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-B) and on\n * the [website](https://ristretto.group/formulas/elligator.html).\n */\nfunction calcElligatorRistrettoMap(r0: bigint): ExtendedPoint {\n const { d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n if (!Ns_D_is_sq) s = s_; // 7\n if (!Ns_D_is_sq) c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\nfunction ristretto255_map(bytes: Uint8Array): _RistrettoPoint {\n abytes(bytes, 64);\n const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new _RistrettoPoint(R1.add(R2));\n}\n\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint<_RistrettoPoint> {\n // Do NOT change syntax: the following gymnastics is done,\n // because typescript strips comments, which makes bundlers disable tree-shaking.\n // prettier-ignore\n static BASE: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.BASE))();\n // prettier-ignore\n static ZERO: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519.Point.ZERO))();\n // prettier-ignore\n static Fp: IField<bigint> =\n /* @__PURE__ */ (() => Fp)();\n // prettier-ignore\n static Fn: IField<bigint> =\n /* @__PURE__ */ (() => Fn)();\n\n constructor(ep: ExtendedPoint) {\n super(ep);\n }\n\n static fromAffine(ap: AffinePoint<bigint>): _RistrettoPoint {\n return new _RistrettoPoint(ed25519.Point.fromAffine(ap));\n }\n\n protected assertSame(other: _RistrettoPoint): void {\n if (!(other instanceof _RistrettoPoint)) throw new Error('RistrettoPoint expected');\n }\n\n protected init(ep: EdwardsPoint): _RistrettoPoint {\n return new _RistrettoPoint(ep);\n }\n\n /** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\n static hashToCurve(hex: Hex): _RistrettoPoint {\n return ristretto255_map(ensureBytes('ristrettoHash', hex, 64));\n }\n\n static fromBytes(bytes: Uint8Array): _RistrettoPoint {\n abytes(bytes, 32);\n const { a, d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const s = bytes255ToNumberLE(bytes);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))\n throw new Error('invalid ristretto255 encoding 1');\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P)) x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n)\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519.Point(x, y, _1n, t));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: Hex): _RistrettoPoint {\n return _RistrettoPoint.fromBytes(ensureBytes('ristrettoHex', hex, 32));\n }\n\n static msm(points: _RistrettoPoint[], scalars: bigint[]): _RistrettoPoint {\n return pippenger(_RistrettoPoint, ed25519.Point.Fn, points, scalars);\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toBytes(): Uint8Array {\n let { X, Y, Z, T } = this.ep;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const u1 = mod(mod(Z + Y) * mod(Z - Y)); // 1\n const u2 = mod(X * Y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * T); // 6\n let D: bigint; // 7\n if (isNegativeLE(T * zInv, P)) {\n let _x = mod(Y * SQRT_M1);\n let _y = mod(X * SQRT_M1);\n X = _x;\n Y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n } else {\n D = D2; // 8\n }\n if (isNegativeLE(X * zInv, P)) Y = mod(-Y); // 9\n let s = mod((Z - Y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P)) s = mod(-s);\n return Fp.toBytes(s); // 11\n }\n\n /**\n * Compares two Ristretto points.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n */\n equals(other: _RistrettoPoint): boolean {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n const mod = (n: bigint) => Fp.create(n);\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n\n is0(): boolean {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\n\nexport const ristretto255: {\n Point: typeof _RistrettoPoint;\n} = { Point: _RistrettoPoint };\n\n/** Hashing to ristretto255 points / field. RFC 9380 methods. */\nexport const ristretto255_hasher: H2CHasherBase<bigint> = {\n hashToCurve(msg: Uint8Array, options?: htfBasicOpts): _RistrettoPoint {\n const DST = options?.DST || 'ristretto255_XMD:SHA-512_R255MAP_RO_';\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n return ristretto255_map(xmd);\n },\n hashToScalar(msg: Uint8Array, options: htfBasicOpts = { DST: _DST_scalar }) {\n const xmd = expand_message_xmd(msg, options.DST, 64, sha512);\n return Fn.create(bytesToNumberLE(xmd));\n },\n};\n\n// export const ristretto255_oprf: OPRF = createORPF({\n// name: 'ristretto255-SHA512',\n// Point: RistrettoPoint,\n// hash: sha512,\n// hashToGroup: ristretto255_hasher.hashToCurve,\n// hashToScalar: ristretto255_hasher.hashToScalar,\n// });\n\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * ⟨T⟩ = { O, T, 2T, 3T, 4T, 5T, 6T, 7T }\n */\nexport const ED25519_TORSION_SUBGROUP: string[] = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n\n/** @deprecated use `ed25519.utils.toMontgomery` */\nexport function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array {\n return ed25519.utils.toMontgomery(ensureBytes('pub', edwardsPub));\n}\n/** @deprecated use `ed25519.utils.toMontgomery` */\nexport const edwardsToMontgomery: typeof edwardsToMontgomeryPub = edwardsToMontgomeryPub;\n\n/** @deprecated use `ed25519.utils.toMontgomerySecret` */\nexport function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array {\n return ed25519.utils.toMontgomerySecret(ensureBytes('pub', edwardsPriv));\n}\n\n/** @deprecated use `ristretto255.Point` */\nexport const RistrettoPoint: typeof _RistrettoPoint = _RistrettoPoint;\n/** @deprecated use `import { ed25519_hasher } from '@noble/curves/ed25519.js';` */\nexport const hashToCurve: H2CMethod<bigint> = /* @__PURE__ */ (() => ed25519_hasher.hashToCurve)();\n/** @deprecated use `import { ed25519_hasher } from '@noble/curves/ed25519.js';` */\nexport const encodeToCurve: H2CMethod<bigint> = /* @__PURE__ */ (() =>\n ed25519_hasher.encodeToCurve)();\ntype RistHasher = (msg: Uint8Array, options: htfBasicOpts) => _RistrettoPoint;\n/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\nexport const hashToRistretto255: RistHasher = /* @__PURE__ */ (() =>\n ristretto255_hasher.hashToCurve as RistHasher)();\n/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */\nexport const hash_to_ristretto255: RistHasher = /* @__PURE__ */ (() =>\n ristretto255_hasher.hashToCurve as RistHasher)();\n","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils';\nimport {\n _validateObject,\n _abool2 as abool,\n _abytes2 as abytes,\n aInRange,\n bitLen,\n bitMask,\n bytesToHex,\n bytesToNumberBE,\n concatBytes,\n createHmacDrbg,\n ensureBytes,\n hexToBytes,\n inRange,\n isBytes,\n memoized,\n numberToHexUnpadded,\n randomBytes as randomBytesWeb,\n type CHash,\n type Hex,\n type PrivKey,\n} from '../utils.ts';\nimport {\n _createCurveFields,\n mulEndoUnsafe,\n negateCt,\n normalizeZ,\n pippenger,\n wNAF,\n type AffinePoint,\n type BasicCurve,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport {\n Field,\n FpInvertBatch,\n getMinHashLength,\n mapHashToField,\n nLength,\n validateField,\n type IField,\n type NLength,\n} from './modular.ts';\n\nexport type { AffinePoint };\nexport type HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\n\ntype EndoBasis = [[bigint, bigint], [bigint, bigint]];\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV endomorphism ψ**.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)`\n * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1\n * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1\n * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * [gist](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n */\nexport type EndomorphismOpts = {\n beta: bigint;\n basises?: EndoBasis;\n splitScalar?: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\n\n// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)\nconst divNearest = (num: bigint, den: bigint) => (num + (num >= 0 ? den : -den) / _2n) / den;\n\nexport type ScalarEndoParts = { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n\n/**\n * Splits scalar for GLV endomorphism.\n */\nexport function _splitEndoScalar(k: bigint, basis: EndoBasis, n: bigint): ScalarEndoParts {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg) k1 = -k1;\n if (k2neg) k2 = -k2;\n // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.\n // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n}\n\nexport type ECDSASigFormat = 'compact' | 'recovered' | 'der';\nexport type ECDSARecoverOpts = {\n prehash?: boolean;\n};\nexport type ECDSAVerifyOpts = {\n prehash?: boolean;\n lowS?: boolean;\n format?: ECDSASigFormat;\n};\nexport type ECDSASignOpts = {\n prehash?: boolean;\n lowS?: boolean;\n format?: ECDSASigFormat;\n extraEntropy?: Uint8Array | boolean;\n};\n\nfunction validateSigFormat(format: string): ECDSASigFormat {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format as ECDSASigFormat;\n}\n\nfunction validateSigOpts<T extends ECDSASignOpts, D extends Required<ECDSASignOpts>>(\n opts: T,\n def: D\n): Required<ECDSASignOpts> {\n const optsn: ECDSASignOpts = {};\n for (let optName of Object.keys(def)) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS!, 'lowS');\n abool(optsn.prehash!, 'prehash');\n if (optsn.format !== undefined) validateSigFormat(optsn.format);\n return optsn as Required<ECDSASignOpts>;\n}\n\n/** Instance methods for 3D XYZ projective points. */\nexport interface WeierstrassPoint<T> extends CurvePoint<T, WeierstrassPoint<T>> {\n /** projective X coordinate. Different from affine x. */\n readonly X: T;\n /** projective Y coordinate. Different from affine y. */\n readonly Y: T;\n /** projective z coordinate */\n readonly Z: T;\n /** affine x coordinate. Different from projective X. */\n get x(): T;\n /** affine y coordinate. Different from projective Y. */\n get y(): T;\n /** Encodes point using IEEE P1363 (DER) encoding. First byte is 2/3/4. Default = isCompressed. */\n toBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n\n /** @deprecated use `.X` */\n readonly px: T;\n /** @deprecated use `.Y` */\n readonly py: T;\n /** @deprecated use `.Z` */\n readonly pz: T;\n /** @deprecated use `toBytes` */\n toRawBytes(isCompressed?: boolean): Uint8Array;\n /** @deprecated use `multiplyUnsafe` */\n multiplyAndAddUnsafe(\n Q: WeierstrassPoint<T>,\n a: bigint,\n b: bigint\n ): WeierstrassPoint<T> | undefined;\n /** @deprecated use `p.y % 2n === 0n` */\n hasEvenY(): boolean;\n /** @deprecated use `p.precompute(windowSize)` */\n _setWindowSize(windowSize: number): void;\n}\n\n/** Static methods for 3D XYZ projective points. */\nexport interface WeierstrassPointCons<T> extends CurvePointCons<WeierstrassPoint<T>> {\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n new (X: T, Y: T, Z: T): WeierstrassPoint<T>;\n CURVE(): WeierstrassOpts<T>;\n /** @deprecated use `Point.BASE.multiply(Point.Fn.fromBytes(privateKey))` */\n fromPrivateKey(privateKey: PrivKey): WeierstrassPoint<T>;\n /** @deprecated use `import { normalizeZ } from '@noble/curves/abstract/curve.js';` */\n normalizeZ(points: WeierstrassPoint<T>[]): WeierstrassPoint<T>[];\n /** @deprecated use `import { pippenger } from '@noble/curves/abstract/curve.js';` */\n msm(points: WeierstrassPoint<T>[], scalars: bigint[]): WeierstrassPoint<T>;\n}\n\n/**\n * Weierstrass curve options.\n *\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor, usually 1. h*n is group order; n is subgroup order\n * * a: formula param, must be in field of p\n * * b: formula param, must be in field of p\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type WeierstrassOpts<T> = Readonly<{\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b: T;\n Gx: T;\n Gy: T;\n}>;\n\n// When a cofactor != 1, there can be an effective methods to:\n// 1. Determine whether a point is torsion-free\n// 2. Clear torsion component\n// wrapPrivateKey: bls12-381 requires mod(n) instead of rejecting keys >= n\nexport type WeierstrassExtraOpts<T> = Partial<{\n Fp: IField<T>;\n Fn: IField<bigint>;\n allowInfinityPoint: boolean;\n endo: EndomorphismOpts;\n isTorsionFree: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => boolean;\n clearCofactor: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => WeierstrassPoint<T>;\n fromBytes: (bytes: Uint8Array) => AffinePoint<T>;\n toBytes: (\n c: WeierstrassPointCons<T>,\n point: WeierstrassPoint<T>,\n isCompressed: boolean\n ) => Uint8Array;\n}>;\n\n/**\n * Options for ECDSA signatures over a Weierstrass curve.\n *\n * * lowS: (default: true) whether produced / verified signatures occupy low half of ecdsaOpts.p. Prevents malleability.\n * * hmac: (default: noble-hashes hmac) function, would be used to init hmac-drbg for k generation.\n * * randomBytes: (default: webcrypto os-level CSPRNG) custom method for fetching secure randomness.\n * * bits2int, bits2int_modN: used in sigs, sometimes overridden by curves\n */\nexport type ECDSAOpts = Partial<{\n lowS: boolean;\n hmac: HmacFnSync;\n randomBytes: (bytesLength?: number) => Uint8Array;\n bits2int: (bytes: Uint8Array) => bigint;\n bits2int_modN: (bytes: Uint8Array) => bigint;\n}>;\n\n/**\n * Elliptic Curve Diffie-Hellman interface.\n * Provides keygen, secret-to-public conversion, calculating shared secrets.\n */\nexport interface ECDH {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: PrivKey, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (secretKeyA: PrivKey, publicKeyB: Hex, isCompressed?: boolean) => Uint8Array;\n Point: WeierstrassPointCons<bigint>;\n utils: {\n isValidSecretKey: (secretKey: PrivKey) => boolean;\n isValidPublicKey: (publicKey: Uint8Array, isCompressed?: boolean) => boolean;\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n /** @deprecated use `randomSecretKey` */\n randomPrivateKey: (seed?: Uint8Array) => Uint8Array;\n /** @deprecated use `isValidSecretKey` */\n isValidPrivateKey: (secretKey: PrivKey) => boolean;\n /** @deprecated use `Point.Fn.fromBytes()` */\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n /** @deprecated use `point.precompute()` */\n precompute: (windowSize?: number, point?: WeierstrassPoint<bigint>) => WeierstrassPoint<bigint>;\n };\n lengths: CurveLengths;\n}\n\n/**\n * ECDSA interface.\n * Only supported for prime fields, not Fp2 (extension fields).\n */\nexport interface ECDSA extends ECDH {\n sign: (message: Hex, secretKey: PrivKey, opts?: ECDSASignOpts) => ECDSASigRecovered;\n verify: (\n signature: Uint8Array,\n message: Uint8Array,\n publicKey: Uint8Array,\n opts?: ECDSAVerifyOpts\n ) => boolean;\n recoverPublicKey(signature: Uint8Array, message: Uint8Array, opts?: ECDSARecoverOpts): Uint8Array;\n Signature: ECDSASignatureCons;\n}\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\nexport type IDER = {\n // asn.1 DER encoding utils\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array };\n };\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num: bigint): string;\n decode(data: Uint8Array): bigint;\n };\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint };\n hexFromSig(sig: { r: bigint; s: bigint }): string;\n};\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): string => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length & 1) throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 0b1000_0000) throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array } {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag) throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 0b1000_0000); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong) length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen) throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4) throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen) throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0) throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes) length = (length << 8) | b;\n pos += lenLen;\n if (length < 128) throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length) throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num: bigint): string {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000) hex = '00' + hex;\n if (hex.length & 1) throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data: Uint8Array): bigint {\n const { Err: E } = DER;\n if (data[0] & 0b1000_0000) throw new E('invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 0b1000_0000))\n throw new E('invalid signature integer: unnecessary leading zero');\n return bytesToNumberBE(data);\n },\n },\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = ensureBytes('signature', hex);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig: { r: bigint; s: bigint }): string {\n const { _tlv: tlv, _int: int } = DER;\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\n\nexport function _normFnElement(Fn: IField<bigint>, key: PrivKey): bigint {\n const { BYTES: expected } = Fn;\n let num: bigint;\n if (typeof key === 'bigint') {\n num = key;\n } else {\n let bytes = ensureBytes('private key', key);\n try {\n num = Fn.fromBytes(bytes);\n } catch (error) {\n throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);\n }\n }\n if (!Fn.isValidNot0(num)) throw new Error('invalid private key: out of range [1..N-1]');\n return num;\n}\n\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * @example\n```js\nconst opts = {\n p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),\n n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n h: BigInt(1),\n a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),\n b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),\n Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n};\nconst p256_Point = weierstrass(opts);\n```\n */\nexport function weierstrassN<T>(\n params: WeierstrassOpts<T>,\n extraOpts: WeierstrassExtraOpts<T> = {}\n): WeierstrassPointCons<T> {\n const validated = _createCurveFields('weierstrass', params, extraOpts);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE as WeierstrassOpts<T>;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n _validateObject(\n extraOpts,\n {},\n {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n wrapPrivateKey: 'boolean',\n }\n );\n\n const { endo } = extraOpts;\n if (endo) {\n // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n\n const lengths = getWLengths(Fp, Fn);\n\n function assertCompressionIsSupported() {\n if (!Fp.isOdd) throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n\n // Implements IEEE P1363 point encoding\n function pointToBytes(\n _c: WeierstrassPointCons<T>,\n point: WeierstrassPoint<T>,\n isCompressed: boolean\n ): Uint8Array {\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd!(y);\n return concatBytes(pprefix(hasEvenY), bx);\n } else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n }\n }\n function pointFromBytes(bytes: Uint8Array) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x)) throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y: T;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n } catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const isYOdd = Fp.isOdd!(y); // (y & _1n) === _1n;\n const isHeadOdd = (head & 1) === 1; // ECDSA-specific\n if (isHeadOdd !== isYOdd) y = Fp.neg(y);\n return { x, y };\n } else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y)) throw new Error('bad point: is not on curve');\n return { x, y };\n } else {\n throw new Error(\n `bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`\n );\n }\n }\n\n const encodePoint = extraOpts.toBytes || pointToBytes;\n const decodePoint = extraOpts.fromBytes || pointFromBytes;\n function weierstrassEquation(x: T): T {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b\n }\n\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y² == x³ + ax + b */\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title: string, n: T, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n))) throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n\n function aprjpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ProjectivePoint expected');\n }\n\n function splitEndoScalarN(k: bigint) {\n if (!endo || !endo.basises) throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n }\n\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)\n const toAffineMemo = memoized((p: Point, iz?: T): AffinePoint<T> => {\n const { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE)) return { x: X, y: Y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n return { x, y };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p: Point) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is invalid representation of ZERO.\n if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y)) return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y)) throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n\n function finishEndo(\n endoBeta: EndomorphismOpts['beta'],\n k1p: Point,\n k2p: Point,\n k1neg: boolean,\n k2neg: boolean\n ) {\n k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n k1p = negateCt(k1neg, k1p);\n k2p = negateCt(k2neg, k2p);\n return k1p.add(k2p);\n }\n\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).\n * Default Point works in 2d / affine coordinates: (x, y).\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point implements WeierstrassPoint<T> {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: T;\n readonly Y: T;\n readonly Z: T;\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X: T, Y: T, Z: T) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n\n static CURVE(): WeierstrassOpts<T> {\n return CURVE;\n }\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n static fromAffine(p: AffinePoint<T>): Point {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n if (p instanceof Point) throw new Error('projective point not allowed');\n // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n static fromBytes(bytes: Uint8Array): Point {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n static fromHex(hex: Hex): Point {\n return Point.fromBytes(ensureBytes('pointHex', hex));\n }\n\n get x(): T {\n return this.toAffine().x;\n }\n get y(): T {\n return this.toAffine().y;\n }\n\n /**\n *\n * @param windowSize\n * @param isLazy true will defer table computation until the first multiplication\n * @returns\n */\n precompute(windowSize: number = 8, isLazy = true): Point {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_3n); // random number\n return this;\n }\n\n // TODO: return `this`\n /** A point on curve is valid if it conforms to equation. */\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n hasEvenY(): boolean {\n const { y } = this.toAffine();\n if (!Fp.isOdd) throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n\n /** Compare one point to another. */\n equals(other: Point): boolean {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n\n /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate(): Point {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\n }\n\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other: Point): Point {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n\n subtract(other: Point) {\n return this.add(other.negate());\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar: bigint): Point {\n const { endo } = extraOpts;\n if (!Fn.isValidNot0(scalar)) throw new Error('invalid scalar: out of range'); // 0 is invalid\n let point: Point, fake: Point; // Fake point is used to const-time mult\n const mul = (n: bigint) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n const { p: k1p, f: k1f } = mul(k1);\n const { p: k2p, f: k2f } = mul(k2);\n fake = k1f.add(k2f);\n point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n } else {\n const { p, f } = mul(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return normalizeZ(Point, [point, fake])[0];\n }\n\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc: bigint): Point {\n const { endo } = extraOpts;\n const p = this as Point;\n if (!Fn.isValid(sc)) throw new Error('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0()) return Point.ZERO;\n if (sc === _1n) return p; // fast-path\n if (wnaf.hasCache(this)) return this.multiply(sc);\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n } else {\n return wnaf.unsafe(p, sc);\n }\n }\n\n multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined {\n const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));\n return sum.is0() ? undefined : sum;\n }\n\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ?: T): AffinePoint<T> {\n return toAffineMemo(this, invertedZ);\n }\n\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree(): boolean {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n) return true;\n if (isTorsionFree) return isTorsionFree(Point, this);\n return wnaf.unsafe(this, CURVE_ORDER).is0();\n }\n\n clearCofactor(): Point {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(cofactor);\n }\n\n isSmallOrder(): boolean {\n // can we use this.clearCofactor()?\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n toBytes(isCompressed = true): Uint8Array {\n abool(isCompressed, 'isCompressed');\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n return bytesToHex(this.toBytes(isCompressed));\n }\n\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n\n // TODO: remove\n get px(): T {\n return this.X;\n }\n get py(): T {\n return this.X;\n }\n get pz(): T {\n return this.Z;\n }\n toRawBytes(isCompressed = true): Uint8Array {\n return this.toBytes(isCompressed);\n }\n _setWindowSize(windowSize: number) {\n this.precompute(windowSize);\n }\n static normalizeZ(points: Point[]): Point[] {\n return normalizeZ(Point, points);\n }\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n static fromPrivateKey(privateKey: PrivKey) {\n return Point.BASE.multiply(_normFnElement(Fn, privateKey));\n }\n }\n const bits = Fn.BITS;\n const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n\n/** Methods of ECDSA signature instance. */\nexport interface ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n addRecoveryBit(recovery: number): ECDSASigRecovered;\n hasHighS(): boolean;\n toBytes(format?: string): Uint8Array;\n toHex(format?: string): string;\n\n /** @deprecated */\n assertValidity(): void;\n /** @deprecated */\n normalizeS(): ECDSASignature;\n /** @deprecated use standalone method `curve.recoverPublicKey(sig.toBytes('recovered'), msg)` */\n recoverPublicKey(msgHash: Hex): WeierstrassPoint<bigint>;\n /** @deprecated use `.toBytes('compact')` */\n toCompactRawBytes(): Uint8Array;\n /** @deprecated use `.toBytes('compact')` */\n toCompactHex(): string;\n /** @deprecated use `.toBytes('der')` */\n toDERRawBytes(): Uint8Array;\n /** @deprecated use `.toBytes('der')` */\n toDERHex(): string;\n}\nexport type ECDSASigRecovered = ECDSASignature & {\n readonly recovery: number;\n};\n/** Methods of ECDSA signature constructor. */\nexport type ECDSASignatureCons = {\n new (r: bigint, s: bigint, recovery?: number): ECDSASignature;\n fromBytes(bytes: Uint8Array, format?: ECDSASigFormat): ECDSASignature;\n fromHex(hex: string, format?: ECDSASigFormat): ECDSASignature;\n\n /** @deprecated use `.fromBytes(bytes, 'compact')` */\n fromCompact(hex: Hex): ECDSASignature;\n /** @deprecated use `.fromBytes(bytes, 'der')` */\n fromDER(hex: Hex): ECDSASignature;\n};\n\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY: boolean): Uint8Array {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio<T>(\n Fp: IField<T>,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: T } {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u: T, v: T) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU<T>(\n Fp: IField<T>,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n validateField(Fp);\n const { A, B, Z } = opts;\n if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, Z);\n if (!Fp.isOdd) throw new Error('Field does not have .isOdd()');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u: T): { x: T; y: T } => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd!(u) === Fp.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n\nfunction getWLengths<T>(Fp: IField<T>, Fn: IField<bigint>) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n signature: 2 * Fn.BYTES,\n };\n}\n\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n */\nexport function ecdh(\n Point: WeierstrassPointCons<bigint>,\n ecdhOpts: { randomBytes?: (bytesLength?: number) => Uint8Array } = {}\n): ECDH {\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes || randomBytesWeb;\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });\n\n function isValidSecretKey(secretKey: PrivKey) {\n try {\n return !!_normFnElement(Fn, secretKey);\n } catch (error) {\n return false;\n }\n }\n\n function isValidPublicKey(publicKey: Uint8Array, isCompressed?: boolean): boolean {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp) return false;\n if (isCompressed === false && l !== publicKeyUncompressed) return false;\n return !!Point.fromBytes(publicKey);\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed = randomBytes_(lengths.seed)): Uint8Array {\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\n }\n\n /**\n * Computes public key for a secret key. Checks for validity of the secret key.\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(secretKey: PrivKey, isCompressed = true): Uint8Array {\n return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);\n }\n\n function keygen(seed?: Uint8Array) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n }\n\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item: PrivKey | PubKey): boolean | undefined {\n if (typeof item === 'bigint') return false;\n if (item instanceof Point) return true;\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n if (Fn.allowedLengths || secretKey === publicKey) return undefined;\n const l = ensureBytes('key', item).length;\n return l === publicKey || l === publicKeyUncompressed;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(secretKeyA: PrivKey, publicKeyB: Hex, isCompressed = true): Uint8Array {\n if (isProbPub(secretKeyA) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false) throw new Error('second arg must be public key');\n const s = _normFnElement(Fn, secretKeyA);\n const b = Point.fromHex(publicKeyB); // checks for being on-curve\n return b.multiply(s).toBytes(isCompressed);\n }\n\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n\n // TODO: remove\n isValidPrivateKey: isValidSecretKey,\n randomPrivateKey: randomSecretKey,\n normPrivateKeyToScalar: (key: PrivKey) => _normFnElement(Fn, key),\n precompute(windowSize = 8, point = Point.BASE): WeierstrassPoint<bigint> {\n return point.precompute(windowSize, false);\n },\n };\n\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n * We need `hash` for 2 features:\n * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`\n * 2. k generation in `sign`, using HMAC-drbg(hash)\n *\n * ECDSAOpts are only rarely needed.\n *\n * @example\n * ```js\n * const p256_Point = weierstrass(...);\n * const p256_sha256 = ecdsa(p256_Point, sha256);\n * const p256_sha224 = ecdsa(p256_Point, sha224);\n * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });\n * ```\n */\nexport function ecdsa(\n Point: WeierstrassPointCons<bigint>,\n hash: CHash,\n ecdsaOpts: ECDSAOpts = {}\n): ECDSA {\n ahash(hash);\n _validateObject(\n ecdsaOpts,\n {},\n {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n }\n );\n\n const randomBytes = ecdsaOpts.randomBytes || randomBytesWeb;\n const hmac: HmacFnSync =\n ecdsaOpts.hmac ||\n (((key, ...msgs) => nobleHmac(hash, key, concatBytes(...msgs))) satisfies HmacFnSync);\n\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n const defaultSigOpts: Required<ECDSASignOpts> = {\n prehash: false,\n lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,\n format: undefined as any, //'compact' as ECDSASigFormat,\n extraEntropy: false,\n };\n const defaultSigOpts_format = 'compact';\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title: string, num: bigint): bigint {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function validateSigLength(bytes: Uint8Array, format: ECDSASigFormat) {\n validateSigFormat(format);\n const size = lengths.signature!;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer, `${format} signature`);\n }\n\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature implements ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n constructor(r: bigint, s: bigint, recovery?: number) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null) this.recovery = recovery;\n Object.freeze(this);\n }\n\n static fromBytes(bytes: Uint8Array, format: ECDSASigFormat = defaultSigOpts_format): Signature {\n validateSigLength(bytes, format);\n let recid: number | undefined;\n if (format === 'der') {\n const { r, s } = DER.toSig(abytes(bytes));\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = Fn.BYTES;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n\n static fromHex(hex: string, format?: ECDSASigFormat) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(messageHash: Hex): WeierstrassPoint<bigint> {\n const FIELD_ORDER = Fp.ORDER;\n const { r, s, recovery: rec } = this;\n if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid');\n\n // ECDSA recovery is hard for cofactor > 1 curves.\n // In sign, `r = q.x mod n`, and here we recover q.x from r.\n // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.\n // However, for cofactor>1, r+n may not get q.x:\n // r+n*i would need to be done instead where i is unknown.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit non-prime-order signatures (recid > 1).\n const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER;\n if (hasCofactor && rec > 1) throw new Error('recovery id is ambiguous for h>1 curve');\n\n const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj)) throw new Error('recovery id 2 or 3 invalid');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(ensureBytes('msgHash', messageHash)); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));\n if (Q.is0()) throw new Error('point at infinify');\n Q.assertValidity();\n return Q;\n }\n\n // Signatures should be low-s, to prevent malleability.\n hasHighS(): boolean {\n return isBiggerThanHalfOrder(this.s);\n }\n\n toBytes(format: ECDSASigFormat = defaultSigOpts_format) {\n validateSigFormat(format);\n if (format === 'der') return hexToBytes(DER.hexFromSig(this));\n const r = Fn.toBytes(this.r);\n const s = Fn.toBytes(this.s);\n if (format === 'recovered') {\n if (this.recovery == null) throw new Error('recovery bit must be present');\n return concatBytes(Uint8Array.of(this.recovery), r, s);\n }\n return concatBytes(r, s);\n }\n\n toHex(format?: ECDSASigFormat) {\n return bytesToHex(this.toBytes(format));\n }\n\n // TODO: remove\n assertValidity(): void {}\n static fromCompact(hex: Hex) {\n return Signature.fromBytes(ensureBytes('sig', hex), 'compact');\n }\n static fromDER(hex: Hex) {\n return Signature.fromBytes(ensureBytes('sig', hex), 'der');\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;\n }\n toDERRawBytes() {\n return this.toBytes('der');\n }\n toDERHex() {\n return bytesToHex(this.toBytes('der'));\n }\n toCompactRawBytes() {\n return this.toBytes('compact');\n }\n toCompactHex() {\n return bytesToHex(this.toBytes('compact'));\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int =\n ecdsaOpts.bits2int ||\n function bits2int_def(bytes: Uint8Array): bigint {\n // Our custom check \"just in case\", for protection against DoS\n if (bytes.length > 8192) throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n ecdsaOpts.bits2int_modN ||\n function bits2int_modN_def(bytes: Uint8Array): bigint {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // Pads output with zero as per spec\n const ORDER_MASK = bitMask(fnBits);\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num: bigint): Uint8Array {\n // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num);\n }\n\n function validateMsgAndHash(message: Uint8Array, prehash: boolean) {\n abytes(message, undefined, 'message');\n return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;\n }\n\n /**\n * Steps A, D of RFC6979 3.2.\n * Creates RFC6979 seed; converts msg/privKey to numbers.\n * Used only in sign, not in verify.\n *\n * Warning: we cannot assume here that message has same amount of bytes as curve order,\n * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.\n */\n function prepSig(message: Uint8Array, privateKey: PrivKey, opts: ECDSASignOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(message);\n const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n // To transform k => Signature:\n // q = k⋅G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // mod n, not mod p\n if (!Fn.isValidNot0(k)) return; // Valid scalars (including k) must be in 1..N-1\n const ik = Fn.inv(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n) return;\n const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above\n if (s === _0n) return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = Fn.neg(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s\n }\n return { seed, k2sig };\n }\n\n /**\n * Signs message hash with a secret key.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(message: Hex, secretKey: PrivKey, opts: ECDSASignOpts = {}): RecoveredSignature {\n message = ensureBytes('message', message);\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg<RecoveredSignature>(hash.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig;\n }\n\n function tryParsingSig(sg: Hex | SignatureLike) {\n // Try to deduce format\n let sig: Signature | undefined = undefined;\n const isHex = typeof sg === 'string' || isBytes(sg);\n const isObj =\n !isHex &&\n sg !== null &&\n typeof sg === 'object' &&\n typeof sg.r === 'bigint' &&\n typeof sg.s === 'bigint';\n if (!isHex && !isObj)\n throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');\n if (isObj) {\n sig = new Signature(sg.r, sg.s);\n } else if (isHex) {\n try {\n sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');\n } catch (derError) {\n if (!(derError instanceof DER.Err)) throw derError;\n }\n if (!sig) {\n try {\n sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');\n } catch (error) {\n return false;\n }\n }\n }\n if (!sig) return false;\n return sig;\n }\n\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * u1 = hs^-1 mod n\n * u2 = rs^-1 mod n\n * R = u1⋅G + u2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(\n signature: Hex | SignatureLike,\n message: Hex,\n publicKey: Hex,\n opts: ECDSAVerifyOpts = {}\n ): boolean {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = ensureBytes('publicKey', publicKey);\n message = validateMsgAndHash(ensureBytes('message', message), prehash);\n if ('strict' in opts) throw new Error('options.strict was renamed to lowS');\n const sig =\n format === undefined\n ? tryParsingSig(signature)\n : Signature.fromBytes(ensureBytes('sig', signature as Hex), format);\n if (sig === false) return false;\n try {\n const P = Point.fromBytes(publicKey);\n if (lowS && sig.hasHighS()) return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P\n if (R.is0()) return false;\n const v = Fn.create(R.x); // v = r.x mod n\n return v === r;\n } catch (e) {\n return false;\n }\n }\n\n function recoverPublicKey(\n signature: Uint8Array,\n message: Uint8Array,\n opts: ECDSARecoverOpts = {}\n ): Uint8Array {\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash,\n });\n}\n\n// TODO: remove everything below\n/** @deprecated use ECDSASignature */\nexport type SignatureType = ECDSASignature;\n/** @deprecated use ECDSASigRecovered */\nexport type RecoveredSignatureType = ECDSASigRecovered;\n/** @deprecated switch to Uint8Array signatures in format 'compact' */\nexport type SignatureLike = { r: bigint; s: bigint };\nexport type ECDSAExtraEntropy = Hex | boolean;\n/** @deprecated use `ECDSAExtraEntropy` */\nexport type Entropy = Hex | boolean;\nexport type BasicWCurve<T> = BasicCurve<T> & {\n // Params: a, b\n a: T;\n b: T;\n\n // Optional params\n allowedPrivateKeyLengths?: readonly number[]; // for P521\n wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n endo?: EndomorphismOpts;\n // When a cofactor != 1, there can be an effective methods to:\n // 1. Determine whether a point is torsion-free\n isTorsionFree?: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => boolean;\n // 2. Clear torsion component\n clearCofactor?: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => WeierstrassPoint<T>;\n};\n/** @deprecated use ECDSASignOpts */\nexport type SignOpts = ECDSASignOpts;\n/** @deprecated use ECDSASignOpts */\nexport type VerOpts = ECDSAVerifyOpts;\n\n/** @deprecated use WeierstrassPoint */\nexport type ProjPointType<T> = WeierstrassPoint<T>;\n/** @deprecated use WeierstrassPointCons */\nexport type ProjConstructor<T> = WeierstrassPointCons<T>;\n/** @deprecated use ECDSASignatureCons */\nexport type SignatureConstructor = ECDSASignatureCons;\n\n// TODO: remove\nexport type CurvePointsType<T> = BasicWCurve<T> & {\n fromBytes?: (bytes: Uint8Array) => AffinePoint<T>;\n toBytes?: (\n c: WeierstrassPointCons<T>,\n point: WeierstrassPoint<T>,\n isCompressed: boolean\n ) => Uint8Array;\n};\n\n// LegacyWeierstrassOpts\nexport type CurvePointsTypeWithLength<T> = Readonly<CurvePointsType<T> & Partial<NLength>>;\n\n// LegacyWeierstrass\nexport type CurvePointsRes<T> = {\n Point: WeierstrassPointCons<T>;\n\n /** @deprecated use `Point.CURVE()` */\n CURVE: CurvePointsType<T>;\n /** @deprecated use `Point` */\n ProjectivePoint: WeierstrassPointCons<T>;\n /** @deprecated use `Point.Fn.fromBytes(privateKey)` */\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n /** @deprecated */\n weierstrassEquation: (x: T) => T;\n /** @deprecated use `Point.Fn.isValidNot0(num)` */\n isWithinCurveOrder: (num: bigint) => boolean;\n};\n\n// Aliases to legacy types\n// export type CurveType = LegacyECDSAOpts;\n// export type CurveFn = LegacyECDSA;\n// export type CurvePointsRes<T> = LegacyWeierstrass<T>;\n// export type CurvePointsType<T> = LegacyWeierstrassOpts<T>;\n// export type CurvePointsTypeWithLength<T> = LegacyWeierstrassOpts<T>;\n// export type BasicWCurve<T> = LegacyWeierstrassOpts<T>;\n\n/** @deprecated use `Uint8Array` */\nexport type PubKey = Hex | WeierstrassPoint<bigint>;\nexport type CurveType = BasicWCurve<bigint> & {\n hash: CHash; // CHash not FHash because we need outputLen for DRBG\n hmac?: HmacFnSync;\n randomBytes?: (bytesLength?: number) => Uint8Array;\n lowS?: boolean;\n bits2int?: (bytes: Uint8Array) => bigint;\n bits2int_modN?: (bytes: Uint8Array) => bigint;\n};\nexport type CurveFn = {\n /** @deprecated use `Point.CURVE()` */\n CURVE: CurvePointsType<bigint>;\n keygen: ECDSA['keygen'];\n getPublicKey: ECDSA['getPublicKey'];\n getSharedSecret: ECDSA['getSharedSecret'];\n sign: ECDSA['sign'];\n verify: ECDSA['verify'];\n Point: WeierstrassPointCons<bigint>;\n /** @deprecated use `Point` */\n ProjectivePoint: WeierstrassPointCons<bigint>;\n Signature: ECDSASignatureCons;\n utils: ECDSA['utils'];\n lengths: ECDSA['lengths'];\n};\n/** @deprecated use `weierstrass` in newer releases */\nexport function weierstrassPoints<T>(c: CurvePointsTypeWithLength<T>): CurvePointsRes<T> {\n const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);\n const Point = weierstrassN(CURVE, curveOpts);\n return _weierstrass_new_output_to_legacy(c, Point);\n}\nexport type WsPointComposed<T> = {\n CURVE: WeierstrassOpts<T>;\n curveOpts: WeierstrassExtraOpts<T>;\n};\nexport type WsComposed = {\n /** @deprecated use `Point.CURVE()` */\n CURVE: WeierstrassOpts<bigint>;\n hash: CHash;\n curveOpts: WeierstrassExtraOpts<bigint>;\n ecdsaOpts: ECDSAOpts;\n};\nfunction _weierstrass_legacy_opts_to_new<T>(c: CurvePointsType<T>): WsPointComposed<T> {\n const CURVE: WeierstrassOpts<T> = {\n a: c.a,\n b: c.b,\n p: c.Fp.ORDER,\n n: c.n,\n h: c.h,\n Gx: c.Gx,\n Gy: c.Gy,\n };\n const Fp = c.Fp;\n let allowedLengths = c.allowedPrivateKeyLengths\n ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))\n : undefined;\n const Fn = Field(CURVE.n, {\n BITS: c.nBitLength,\n allowedLengths: allowedLengths,\n modFromBytes: c.wrapPrivateKey,\n });\n const curveOpts: WeierstrassExtraOpts<T> = {\n Fp,\n Fn,\n allowInfinityPoint: c.allowInfinityPoint,\n endo: c.endo,\n isTorsionFree: c.isTorsionFree,\n clearCofactor: c.clearCofactor,\n fromBytes: c.fromBytes,\n toBytes: c.toBytes,\n };\n return { CURVE, curveOpts };\n}\nfunction _ecdsa_legacy_opts_to_new(c: CurveType): WsComposed {\n const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);\n const ecdsaOpts: ECDSAOpts = {\n hmac: c.hmac,\n randomBytes: c.randomBytes,\n lowS: c.lowS,\n bits2int: c.bits2int,\n bits2int_modN: c.bits2int_modN,\n };\n return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };\n}\nexport function _legacyHelperEquat<T>(Fp: IField<T>, a: T, b: T): (x: T) => T {\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².\n * @returns y²\n */\n function weierstrassEquation(x: T): T {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b\n }\n return weierstrassEquation;\n}\nfunction _weierstrass_new_output_to_legacy<T>(\n c: CurvePointsType<T>,\n Point: WeierstrassPointCons<T>\n): CurvePointsRes<T> {\n const { Fp, Fn } = Point;\n function isWithinCurveOrder(num: bigint): boolean {\n return inRange(num, _1n, Fn.ORDER);\n }\n const weierstrassEquation = _legacyHelperEquat(Fp, c.a, c.b);\n return Object.assign(\n {},\n {\n CURVE: c,\n Point: Point,\n ProjectivePoint: Point,\n normPrivateKeyToScalar: (key: PrivKey) => _normFnElement(Fn, key),\n weierstrassEquation,\n isWithinCurveOrder,\n }\n );\n}\nfunction _ecdsa_new_output_to_legacy(c: CurveType, _ecdsa: ECDSA): CurveFn {\n const Point = _ecdsa.Point;\n return Object.assign({}, _ecdsa, {\n ProjectivePoint: Point,\n CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),\n });\n}\n\n// _ecdsa_legacy\nexport function weierstrass(c: CurveType): CurveFn {\n const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);\n const Point = weierstrassN(CURVE, curveOpts);\n const signs = ecdsa(Point, hash, ecdsaOpts);\n return _ecdsa_new_output_to_legacy(c, signs);\n}\n","/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { type CurveFn, type CurveType, weierstrass } from './abstract/weierstrass.ts';\nimport type { CHash } from './utils.ts';\n\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash: CHash): { hash: CHash } {\n return { hash };\n}\n/** Same API as @noble/hashes, with ability to create curve with custom hash */\nexport type CurveDef = Readonly<Omit<CurveType, 'hash'>>;\nexport type CurveFnWithCreate = CurveFn & { create: (hash: CHash) => CurveFn };\n\n/** @deprecated use new `weierstrass()` and `ecdsa()` methods */\nexport function createCurve(curveDef: CurveDef, defHash: CHash): CurveFnWithCreate {\n const create = (hash: CHash): CurveFn => weierstrass({ ...curveDef, hash: hash });\n return { ...create(defHash), create };\n}\n","/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createCurve, type CurveFnWithCreate } from './_shortw_utils.ts';\nimport type { CurveLengths } from './abstract/curve.ts';\nimport {\n createHasher,\n type H2CHasher,\n type H2CMethod,\n isogenyMap,\n} from './abstract/hash-to-curve.ts';\nimport { Field, mapHashToField, mod, pow2 } from './abstract/modular.ts';\nimport {\n _normFnElement,\n type EndomorphismOpts,\n mapToCurveSimpleSWU,\n type WeierstrassPoint as PointType,\n type WeierstrassOpts,\n type WeierstrassPointCons,\n} from './abstract/weierstrass.ts';\nimport type { Hex, PrivKey } from './utils.ts';\nimport {\n bytesToNumberBE,\n concatBytes,\n ensureBytes,\n inRange,\n numberToBytesBE,\n utf8ToBytes,\n} from './utils.ts';\n\n// Seems like generator was produced from some seed:\n// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE: WeierstrassOpts<bigint> = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\n\nconst secp256k1_ENDO: EndomorphismOpts = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\n\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y: bigint): bigint {\n const P = secp256k1_CURVE.p;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error('Cannot find square root');\n return root;\n}\n\nconst Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });\n\n/**\n * secp256k1 curve, ECDSA and ECDH methods.\n *\n * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * const msg = new TextEncoder().encode('hello');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey) === true;\n * ```\n */\nexport const secp256k1: CurveFnWithCreate = createCurve(\n { ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO },\n sha256\n);\n\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\nfunction taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(utf8ToBytes(tag));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: PointType<bigint>) => point.toBytes(true).slice(1);\nconst Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();\nconst hasEven = (y: bigint) => y % _2n === _0n;\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: PrivKey) {\n const { Fn, BASE } = Pointk1;\n const d_ = _normFnElement(Fn, priv);\n const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);\n return { scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x: bigint): PointType<bigint> {\n const Fp = Fpk1;\n if (!Fp.isValidNot0(x)) throw new Error('invalid x: Fail if x ≥ p');\n const xx = Fp.create(x * x);\n const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y)) y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args: Uint8Array[]): bigint {\n return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(secretKey: Hex): Uint8Array {\n return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message: Hex, secretKey: PrivKey, auxRand: Hex = randomBytes(32)): Uint8Array {\n const { Fn } = Pointk1;\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');\n return sig;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean {\n const { Fn, BASE } = Pointk1;\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!inRange(r, _1n, secp256k1_CURVE.p)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!inRange(s, _1n, secp256k1_CURVE.n)) return false;\n // int(challenge(bytes(r)||bytes(P)||m))%n\n const e = challenge(Fn.toBytes(r), pointToBytes(P), m);\n // R = s⋅G - e⋅P, where -eP == (n-e)P\n const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n if (R.is0() || !hasEven(y) || x !== r) return false;\n return true;\n } catch (error) {\n return false;\n }\n}\n\nexport type SecpSchnorr = {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n Point: WeierstrassPointCons<bigint>;\n utils: {\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n pointToBytes: (point: PointType<bigint>) => Uint8Array;\n lift_x: typeof lift_x;\n taggedHash: typeof taggedHash;\n\n /** @deprecated use `randomSecretKey` */\n randomPrivateKey: (seed?: Uint8Array) => Uint8Array;\n /** @deprecated use `utils` */\n numberToBytesBE: typeof numberToBytesBE;\n /** @deprecated use `utils` */\n bytesToNumberBE: typeof bytesToNumberBE;\n /** @deprecated use `modular` */\n mod: typeof mod;\n };\n lengths: CurveLengths;\n};\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed = randomBytes(seedLength)): Uint8Array => {\n return mapHashToField(seed, secp256k1_CURVE.n);\n };\n // TODO: remove\n secp256k1.utils.randomSecretKey;\n function keygen(seed?: Uint8Array) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };\n }\n return {\n keygen,\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: {\n randomSecretKey: randomSecretKey,\n randomPrivateKey: randomSecretKey,\n taggedHash,\n\n // TODO: remove\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n mod,\n },\n lengths: {\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n },\n };\n})();\n\nconst isoMap = /* @__PURE__ */ (() =>\n isogenyMap(\n Fpk1,\n [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]\n ))();\nconst mapSWU = /* @__PURE__ */ (() =>\n mapToCurveSimpleSWU(Fpk1, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n }))();\n\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: H2CHasher<bigint> = /* @__PURE__ */ (() =>\n createHasher(\n secp256k1.Point,\n (scalars: bigint[]) => {\n const { x, y } = mapSWU(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n },\n {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n }\n ))();\n\n/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */\nexport const hashToCurve: H2CMethod<bigint> = /* @__PURE__ */ (() =>\n secp256k1_hasher.hashToCurve)();\n\n/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */\nexport const encodeToCurve: H2CMethod<bigint> = /* @__PURE__ */ (() =>\n secp256k1_hasher.encodeToCurve)();\n","// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { Config } from './types.js';\n\nexport const MAX_U64 = BigInt('18446744073709551615');\n\n/**\n * Allowed keys for metadata.\n */\nexport const ALLOWED_METADATA = {\n\tcontentHash: 'content_hash',\n\tavatar: 'avatar',\n\twalrusSiteId: 'walrus_site_id',\n};\n\nexport const mainPackage: Config = {\n\tmainnet: {\n\t\tpackageId: '0x71af035413ed499710980ed8adb010bbf2cc5cacf4ab37c7710a4bb87eb58ba5',\n\t\tpackageIdV1: '0xd22b24490e0bae52676651b4f56660a5ff8022a2576e0089f79b3c88d44e08f0',\n\t\tpackageIdPricing: '0x71af035413ed499710980ed8adb010bbf2cc5cacf4ab37c7710a4bb87eb58ba5',\n\t\tsuins: '0x6e0ddefc0ad98889c04bab9639e512c21766c5e6366f89e696956d9be6952871',\n\t\tdiscountsPackage: {\n\t\t\tpackageId: '0x03f625d805339b1b0235ba8c503fa6ea62c88c02ddf14cd9d246d9e1febc0c76',\n\t\t\tdiscountHouseId: '0x4ce82dee11e6f4858509dcdba1a62985f12e5afb054df680a04f16790bfe1d04',\n\t\t},\n\t\tsubNamesPackageId: '0xe177697e191327901637f8d2c5ffbbde8b1aaac27ec1024c4b62d1ebd1cd7430',\n\t\ttempSubdomainsProxyPackageId:\n\t\t\t'0xf335dfbcb2020fc996250c0d6fd4655c5e2036b0606cac7408aa163f51340886',\n\t\tcoupons: {\n\t\t\tpackageId: '0xb162340524e0697461c307b9dc530c17e837b0f2c6d7f787da40d29d29681e5e',\n\t\t},\n\t\tpayments: {\n\t\t\tpackageId: '0xdd0a4a34152a80d7841710e916a407b2a62961eee5b2188dcfdaa24194f66286',\n\t\t},\n\t\tbbb: {\n\t\t\tpackageId: '0x6268d072063a311f6f0a1db516d06d97c06a3fa6d10e797cad578937a47b3992',\n\t\t\tvault: '0x869f5100c0ecc0b35c7edad87ba3d488fd291bdba4a7aae84b70d188f440f393',\n\t\t},\n\t\tpyth: {\n\t\t\tpythStateId: '0x1f9310238ee9298fb703c3419030b35b22bb1cc37113e3bb5007c99aec79e5b8',\n\t\t\twormholeStateId: '0xaeab97f96cf9877fee2883315d459552b2b921edc16d7ceac6eab944dd88919c',\n\t\t},\n\t\tcoins: {\n\t\t\tSUI: {\n\t\t\t\ttype: '0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI',\n\t\t\t\tfeed: '0x23d7315113f5b1d3ba7a83604c44b94d79f4fd69af77f804fc7f920a6dc65744',\n\t\t\t},\n\t\t\tNS: {\n\t\t\t\ttype: '0x5145494a5f5100e645e4b0aa950fa6b68f614e8c59e17bc5ded3495123a79178::ns::NS',\n\t\t\t\tfeed: '0xbb5ff26e47a3a6cc7ec2fce1db996c2a145300edc5acaabe43bf9ff7c5dd5d32',\n\t\t\t},\n\t\t\tUSDC: {\n\t\t\t\ttype: '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC',\n\t\t\t\tfeed: '',\n\t\t\t},\n\t\t},\n\t\tregistryTableId: '0xe64cd9db9f829c6cc405d9790bd71567ae07259855f4fba6f02c84f52298c106',\n\t},\n\ttestnet: {\n\t\tpackageId: '0x40eee27b014a872f5c3330dcd5329aa55c7fe0fcc6e70c6498852e2e3727172e',\n\t\tpackageIdV1: '0x22fa05f21b1ad71442491220bb9338f7b7095fe35000ef88d5400d28523bdd93',\n\t\tpackageIdPricing: '0x8a4df604a449ccb9ef2efb9747046b78f78ba60fc8d88df098d0dd47619df5a4',\n\t\tsuins: '0x300369e8909b9a6464da265b9a5a9ab6fe2158a040e84e808628cde7a07ee5a3',\n\t\tdiscountsPackage: {\n\t\t\tpackageId: '0x7976f9bfe81dcbdbb635efb0ecb02844cd79109d3a698d05c06ca9fd2f97d262',\n\t\t\tdiscountHouseId: '0x9f1ac0f49ddaec4fd2248ae1cc63ed91946f43a236b333439efb9126f31f8e9b',\n\t\t},\n\t\tsubNamesPackageId: '0x3c272bc45f9157b7818ece4f7411bdfa8af46303b071aca4e18c03119c9ff636',\n\t\ttempSubdomainsProxyPackageId:\n\t\t\t'0x295a0749dae0e76126757c305f218f929df0656df66a6361f8b6c6480a943f12',\n\t\tcoupons: {\n\t\t\tpackageId: '0x63029aae8abbefae4f4ac6c5e3e0021159ea93a94ba648681fd64caf5b40677a',\n\t\t},\n\t\tpayments: {\n\t\t\tpackageId: '0xc391c200188dd1a363ff12dcffe07eaac5cf28ad1cd8dc0fcc18f2f8625f0da2',\n\t\t},\n\t\tbbb: {\n\t\t\tpackageId: '0xed9b18147ca81c8f3f60192c8d0630574e42387cd200a6e39b3e4e07df1ce6e6',\n\t\t\tvault: '0xa0b7a4dcbb85209c9096a4e0e85e43b716377c605743193abe915e9c9f3043e5',\n\t\t},\n\t\tpyth: {\n\t\t\tpythStateId: '0x243759059f4c3111179da5878c12f68d612c21a8d54d85edc86164bb18be1c7c',\n\t\t\twormholeStateId: '0x31358d198147da50db32eda2562951d53973a0c0ad5ed738e9b17d88b213d790',\n\t\t},\n\t\t/// Testnet coins will be different here for testing purposes, we can publish our own\n\t\tcoins: {\n\t\t\tSUI: {\n\t\t\t\ttype: '0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI',\n\t\t\t\tfeed: '0x50c67b3fd225db8912a424dd4baed60ffdde625ed2feaaf283724f9608fea266',\n\t\t\t},\n\t\t\t/// this is a test token published as 0xb48aac3f53bab328e1eb4c5b3c34f55e760f2fb3f2305ee1a474878d80f650f0::TESTNS::TESTNS\n\t\t\t/// NS token is using the HFT feed since NS feed on testnet is not available\n\t\t\tNS: {\n\t\t\t\ttype: '0xb48aac3f53bab328e1eb4c5b3c34f55e760f2fb3f2305ee1a474878d80f650f0::TESTNS::TESTNS',\n\t\t\t\tfeed: '0x99137a18354efa7fb6840889d059fdb04c46a6ce21be97ab60d9ad93e91ac758',\n\t\t\t},\n\t\t\t/// this is a test token published as 0xb48aac3f53bab328e1eb4c5b3c34f55e760f2fb3f2305ee1a474878d80f650f0::TESTUSDC::TESTUSDC\n\t\t\tUSDC: {\n\t\t\t\ttype: '0xb48aac3f53bab328e1eb4c5b3c34f55e760f2fb3f2305ee1a474878d80f650f0::TESTUSDC::TESTUSDC',\n\t\t\t\tfeed: '',\n\t\t\t},\n\t\t},\n\t\tregistryTableId: '0xb120c0d55432630fce61f7854795a3463deb6e3b443cc4ae72e1282073ff56e4',\n\t},\n};\n","// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { Transaction } from '@mysten/sui/transactions';\nimport { normalizeSuiNSName } from '@mysten/sui/utils';\n\nexport function isSubName(name: string): boolean {\n\treturn normalizeSuiNSName(name, 'dot').split('.').length > 2;\n}\n\n/**\n * Checks if a name is a nested subname.\n * A nested subdomain is a subdomain that is a subdomain of another subdomain.\n * @param name The name to check (e.g test.example.sub.sui)\n */\nexport function isNestedSubName(name: string): boolean {\n\treturn normalizeSuiNSName(name, 'dot').split('.').length > 3;\n}\n\n/**\n * The years must be between 1 and 5.\n */\nexport function validateYears(years: number) {\n\tif (!(years > 0 && years < 6)) throw new Error('Years must be between 1 and 5');\n}\n\nexport function zeroCoin(tx: Transaction, type: string) {\n\treturn tx.moveCall({\n\t\ttarget: '0x2::coin::zero',\n\t\ttypeArguments: [type],\n\t});\n}\n\nexport function getConfigType(suinsPackageV1: string, innerType: string): string {\n\treturn `${suinsPackageV1}::suins::ConfigKey<${innerType}>`;\n}\n\nexport function getDomainType(suinsPackageV1: string): string {\n\treturn `${suinsPackageV1}::domain::Domain`;\n}\n\nexport function getPricelistConfigType(suinsPackageId: string): string {\n\treturn `${suinsPackageId}::pricing_config::PricingConfig`;\n}\n\nexport function getRenewalPricelistConfigType(suinsPackageId: string): string {\n\treturn `${suinsPackageId}::pricing_config::RenewalConfig`;\n}\n\nexport function getCoinDiscountConfigType(paymentPackageId: string): string {\n\treturn `${paymentPackageId}::payments::PaymentsConfig`;\n}\n","import {\n\tbcs,\n\ttype BcsType,\n\ttype TypeTag,\n\tTypeTagSerializer,\n\tBcsStruct,\n\tBcsEnum,\n\tBcsTuple,\n} from '@mysten/sui/bcs';\nimport { normalizeSuiAddress } from '@mysten/sui/utils';\nimport { type TransactionArgument, isArgument } from '@mysten/sui/transactions';\nimport { type ClientWithCoreApi, type SuiClientTypes } from '@mysten/sui/client';\n\nconst MOVE_STDLIB_ADDRESS = normalizeSuiAddress('0x1');\nconst SUI_FRAMEWORK_ADDRESS = normalizeSuiAddress('0x2');\n\nexport type RawTransactionArgument<T> = T | TransactionArgument;\n\nexport type GetOptions<Include extends Omit<SuiClientTypes.ObjectInclude, 'content'> = {}> =\n\tSuiClientTypes.GetObjectOptions<Include> & { client: ClientWithCoreApi };\n\nexport type GetManyOptions<Include extends Omit<SuiClientTypes.ObjectInclude, 'content'> = {}> =\n\tSuiClientTypes.GetObjectsOptions<Include> & { client: ClientWithCoreApi };\n\nexport function getPureBcsSchema(typeTag: string | TypeTag): BcsType<any> | null {\n\tconst parsedTag = typeof typeTag === 'string' ? TypeTagSerializer.parseFromStr(typeTag) : typeTag;\n\n\tif ('u8' in parsedTag) {\n\t\treturn bcs.U8;\n\t} else if ('u16' in parsedTag) {\n\t\treturn bcs.U16;\n\t} else if ('u32' in parsedTag) {\n\t\treturn bcs.U32;\n\t} else if ('u64' in parsedTag) {\n\t\treturn bcs.U64;\n\t} else if ('u128' in parsedTag) {\n\t\treturn bcs.U128;\n\t} else if ('u256' in parsedTag) {\n\t\treturn bcs.U256;\n\t} else if ('address' in parsedTag) {\n\t\treturn bcs.Address;\n\t} else if ('bool' in parsedTag) {\n\t\treturn bcs.Bool;\n\t} else if ('vector' in parsedTag) {\n\t\tconst type = getPureBcsSchema(parsedTag.vector);\n\t\treturn type ? bcs.vector(type) : null;\n\t} else if ('struct' in parsedTag) {\n\t\tconst structTag = parsedTag.struct;\n\t\tconst pkg = normalizeSuiAddress(structTag.address);\n\n\t\tif (pkg === MOVE_STDLIB_ADDRESS) {\n\t\t\tif (\n\t\t\t\t(structTag.module === 'ascii' || structTag.module === 'string') &&\n\t\t\t\tstructTag.name === 'String'\n\t\t\t) {\n\t\t\t\treturn bcs.String;\n\t\t\t}\n\n\t\t\tif (structTag.module === 'option' && structTag.name === 'Option') {\n\t\t\t\tconst inner = structTag.typeParams[0];\n\t\t\t\tconst type = inner ? getPureBcsSchema(inner) : null;\n\t\t\t\treturn type ? bcs.option(type) : null;\n\t\t\t}\n\t\t}\n\n\t\tif (\n\t\t\tpkg === SUI_FRAMEWORK_ADDRESS &&\n\t\t\tstructTag.module === 'object' &&\n\t\t\t(structTag.name === 'ID' || structTag.name === 'UID')\n\t\t) {\n\t\t\treturn bcs.Address;\n\t\t}\n\t}\n\n\treturn null;\n}\n\nexport function normalizeMoveArguments(\n\targs: unknown[] | object,\n\targTypes: readonly (string | null)[],\n\tparameterNames?: string[],\n) {\n\tconst argLen = Array.isArray(args) ? args.length : Object.keys(args).length;\n\tif (parameterNames && argLen !== parameterNames.length) {\n\t\tthrow new Error(\n\t\t\t`Invalid number of arguments, expected ${parameterNames.length}, got ${argLen}`,\n\t\t);\n\t}\n\n\tconst normalizedArgs: TransactionArgument[] = [];\n\n\tlet index = 0;\n\tfor (const argType of argTypes) {\n\t\tif (argType === '0x2::clock::Clock') {\n\t\t\tnormalizedArgs.push((tx) => tx.object.clock());\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (argType === '0x2::random::Random') {\n\t\t\tnormalizedArgs.push((tx) => tx.object.random());\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (argType === '0x2::deny_list::DenyList') {\n\t\t\tnormalizedArgs.push((tx) => tx.object.denyList());\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (argType === '0x3::sui_system::SuiSystemState') {\n\t\t\tnormalizedArgs.push((tx) => tx.object.system());\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet arg;\n\t\tif (Array.isArray(args)) {\n\t\t\tif (index >= args.length) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Invalid number of arguments, expected at least ${index + 1}, got ${args.length}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\targ = args[index];\n\t\t} else {\n\t\t\tif (!parameterNames) {\n\t\t\t\tthrow new Error(`Expected arguments to be passed as an array`);\n\t\t\t}\n\t\t\tconst name = parameterNames[index];\n\t\t\targ = args[name as keyof typeof args];\n\n\t\t\tif (arg === undefined) {\n\t\t\t\tthrow new Error(`Parameter ${name} is required`);\n\t\t\t}\n\t\t}\n\n\t\tindex += 1;\n\n\t\tif (typeof arg === 'function' || isArgument(arg)) {\n\t\t\tnormalizedArgs.push(arg as TransactionArgument);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst bcsType = argType === null ? null : getPureBcsSchema(argType);\n\n\t\tif (bcsType) {\n\t\t\tconst bytes = bcsType.serialize(arg as never);\n\t\t\tnormalizedArgs.push((tx) => tx.pure(bytes));\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (typeof arg === 'string') {\n\t\t\tnormalizedArgs.push((tx) => tx.object(arg));\n\t\t\tcontinue;\n\t\t}\n\n\t\tthrow new Error(`Invalid argument ${stringify(arg)} for type ${argType}`);\n\t}\n\n\treturn normalizedArgs;\n}\n\nexport class MoveStruct<\n\tT extends Record<string, BcsType<any>>,\n\tconst Name extends string = string,\n> extends BcsStruct<T, Name> {\n\tasync get<Include extends Omit<SuiClientTypes.ObjectInclude, 'content' | 'json'> = {}>({\n\t\tobjectId,\n\t\t...options\n\t}: GetOptions<Include>): Promise<\n\t\tSuiClientTypes.Object<Include & { content: true; json: true }> & {\n\t\t\tjson: BcsStruct<T>['$inferType'];\n\t\t}\n\t> {\n\t\tconst [res] = await this.getMany<Include>({\n\t\t\t...options,\n\t\t\tobjectIds: [objectId],\n\t\t});\n\n\t\tif (!res) {\n\t\t\tthrow new Error(`No object found for id ${objectId}`);\n\t\t}\n\n\t\treturn res;\n\t}\n\n\tasync getMany<Include extends Omit<SuiClientTypes.ObjectInclude, 'content' | 'json'> = {}>({\n\t\tclient,\n\t\t...options\n\t}: GetManyOptions<Include>): Promise<\n\t\tArray<\n\t\t\tSuiClientTypes.Object<Include & { content: true; json: true }> & {\n\t\t\t\tjson: BcsStruct<T>['$inferType'];\n\t\t\t}\n\t\t>\n\t> {\n\t\tconst response = (await client.core.getObjects({\n\t\t\t...options,\n\t\t\tinclude: {\n\t\t\t\t...options.include,\n\t\t\t\tcontent: true,\n\t\t\t},\n\t\t})) as SuiClientTypes.GetObjectsResponse<Include & { content: true }>;\n\n\t\treturn response.objects.map((obj) => {\n\t\t\tif (obj instanceof Error) {\n\t\t\t\tthrow obj;\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\t...obj,\n\t\t\t\tjson: this.parse(obj.content),\n\t\t\t};\n\t\t});\n\t}\n}\n\nexport class MoveEnum<\n\tT extends Record<string, BcsType<any> | null>,\n\tconst Name extends string,\n> extends BcsEnum<T, Name> {}\n\nexport class MoveTuple<\n\tconst T extends readonly BcsType<any>[],\n\tconst Name extends string,\n> extends BcsTuple<T, Name> {}\n\nfunction stringify(val: unknown) {\n\tif (typeof val === 'object') {\n\t\treturn JSON.stringify(val, (val: unknown) => val);\n\t}\n\tif (typeof val === 'bigint') {\n\t\treturn val.toString();\n\t}\n\n\treturn val;\n}\n","/**************************************************************\n * THIS FILE IS GENERATED AND SHOULD NOT BE MANUALLY MODIFIED *\n **************************************************************/\n\n/**\n * Defines the `Domain` type and helper functions.\n *\n * Domains are structured similar to their web2 counterpart and the rules\n * determining what a valid domain is can be found here:\n * https://en.wikipedia.org/wiki/Domain_name#Domain_name_syntax\n */\n\nimport { MoveStruct, normalizeMoveArguments, type RawTransactionArgument } from '../utils/index.js';\nimport { bcs } from '@mysten/sui/bcs';\nimport { type Transaction, type TransactionArgument } from '@mysten/sui/transactions';\nconst $moduleName = '@suins/core::domain';\nexport const Domain = new MoveStruct({\n\tname: `${$moduleName}::Domain`,\n\tfields: {\n\t\t/**\n\t\t * Vector of labels that make up a domain.\n\t\t *\n\t\t * Labels are stored in reverse order such that the TLD is always in position `0`.\n\t\t * e.g. domain \"pay.name.sui\" will be stored in the vector as [\"sui\", \"name\",\n\t\t * \"pay\"].\n\t\t */\n\t\tlabels: bcs.vector(bcs.string()),\n\t},\n});\nexport interface NewArguments {\n\tdomain: RawTransactionArgument<string>;\n}\nexport interface NewOptions {\n\tpackage?: string;\n\targuments: NewArguments | [domain: RawTransactionArgument<string>];\n}\nexport function _new(options: NewOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = ['0x1::string::String'] satisfies (string | null)[];\n\tconst parameterNames = ['domain'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'domain',\n\t\t\tfunction: 'new',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface ToStringArguments {\n\tself: TransactionArgument;\n}\nexport interface ToStringOptions {\n\tpackage?: string;\n\targuments: ToStringArguments | [self: TransactionArgument];\n}\n/** Converts a domain into a fully-qualified string representation. */\nexport function toString(options: ToStringOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null] satisfies (string | null)[];\n\tconst parameterNames = ['self'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'domain',\n\t\t\tfunction: 'to_string',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface LabelArguments {\n\tself: TransactionArgument;\n\tlevel: RawTransactionArgument<number | bigint>;\n}\nexport interface LabelOptions {\n\tpackage?: string;\n\targuments:\n\t\t| LabelArguments\n\t\t| [self: TransactionArgument, level: RawTransactionArgument<number | bigint>];\n}\n/**\n * Returns the `label` in a domain specified by `level`.\n *\n * Given the domain \"pay.name.sui\" the individual labels have the following levels:\n *\n * - \"pay\" - `2`\n * - \"name\" - `1`\n * - \"sui\" - `0`\n *\n * This means that the TLD will always be at level `0`.\n */\nexport function label(options: LabelOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null, 'u64'] satisfies (string | null)[];\n\tconst parameterNames = ['self', 'level'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'domain',\n\t\t\tfunction: 'label',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface TldArguments {\n\tself: TransactionArgument;\n}\nexport interface TldOptions {\n\tpackage?: string;\n\targuments: TldArguments | [self: TransactionArgument];\n}\n/**\n * Returns the TLD (Top-Level Domain) of a `Domain`.\n *\n * \"name.sui\" -> \"sui\"\n */\nexport function tld(options: TldOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null] satisfies (string | null)[];\n\tconst parameterNames = ['self'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'domain',\n\t\t\tfunction: 'tld',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface SldArguments {\n\tself: TransactionArgument;\n}\nexport interface SldOptions {\n\tpackage?: string;\n\targuments: SldArguments | [self: TransactionArgument];\n}\n/**\n * Returns the SLD (Second-Level Domain) of a `Domain`.\n *\n * \"name.sui\" -> \"sui\"\n */\nexport function sld(options: SldOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null] satisfies (string | null)[];\n\tconst parameterNames = ['self'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'domain',\n\t\t\tfunction: 'sld',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface NumberOfLevelsArguments {\n\tself: TransactionArgument;\n}\nexport interface NumberOfLevelsOptions {\n\tpackage?: string;\n\targuments: NumberOfLevelsArguments | [self: TransactionArgument];\n}\nexport function numberOfLevels(options: NumberOfLevelsOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null] satisfies (string | null)[];\n\tconst parameterNames = ['self'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'domain',\n\t\t\tfunction: 'number_of_levels',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface IsSubdomainArguments {\n\tdomain: TransactionArgument;\n}\nexport interface IsSubdomainOptions {\n\tpackage?: string;\n\targuments: IsSubdomainArguments | [domain: TransactionArgument];\n}\nexport function isSubdomain(options: IsSubdomainOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null] satisfies (string | null)[];\n\tconst parameterNames = ['domain'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'domain',\n\t\t\tfunction: 'is_subdomain',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface ParentArguments {\n\tdomain: TransactionArgument;\n}\nexport interface ParentOptions {\n\tpackage?: string;\n\targuments: ParentArguments | [domain: TransactionArgument];\n}\n/** Derive the parent of a subdomain. e.g. `subdomain.example.sui` -> `example.sui` */\nexport function parent(options: ParentOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null] satisfies (string | null)[];\n\tconst parameterNames = ['domain'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'domain',\n\t\t\tfunction: 'parent',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface IsParentOfArguments {\n\tparent: TransactionArgument;\n\tchild: TransactionArgument;\n}\nexport interface IsParentOfOptions {\n\tpackage?: string;\n\targuments: IsParentOfArguments | [parent: TransactionArgument, child: TransactionArgument];\n}\n/** Checks if `parent` domain is a valid parent for `child`. */\nexport function isParentOf(options: IsParentOfOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null, null] satisfies (string | null)[];\n\tconst parameterNames = ['parent', 'child'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'domain',\n\t\t\tfunction: 'is_parent_of',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\n","/**************************************************************\n * THIS FILE IS GENERATED AND SHOULD NOT BE MANUALLY MODIFIED *\n **************************************************************/\nimport { type BcsType, bcs } from '@mysten/sui/bcs';\nimport { MoveStruct } from '../../../utils/index.js';\nconst $moduleName = '0x2::vec_map';\n/** An entry in the map */\nexport function Entry<K extends BcsType<any>, V extends BcsType<any>>(...typeParameters: [K, V]) {\n\treturn new MoveStruct({\n\t\tname: `${$moduleName}::Entry<${typeParameters[0].name as K['name']}, ${typeParameters[1].name as V['name']}>`,\n\t\tfields: {\n\t\t\tkey: typeParameters[0],\n\t\t\tvalue: typeParameters[1],\n\t\t},\n\t});\n}\n/**\n * A map data structure backed by a vector. The map is guaranteed not to contain\n * duplicate keys, but entries are _not_ sorted by key--entries are included in\n * insertion order. All operations are O(N) in the size of the map--the intention\n * of this data structure is only to provide the convenience of programming against\n * a map API. Large maps should use handwritten parent/child relationships instead.\n * Maps that need sorted iteration rather than insertion order iteration should\n * also be handwritten.\n */\nexport function VecMap<K extends BcsType<any>, V extends BcsType<any>>(...typeParameters: [K, V]) {\n\treturn new MoveStruct({\n\t\tname: `${$moduleName}::VecMap<${typeParameters[0].name as K['name']}, ${typeParameters[1].name as V['name']}>`,\n\t\tfields: {\n\t\t\tcontents: bcs.vector(Entry(typeParameters[0], typeParameters[1])),\n\t\t},\n\t});\n}\n","/**************************************************************\n * THIS FILE IS GENERATED AND SHOULD NOT BE MANUALLY MODIFIED *\n **************************************************************/\n\n/** Functionality for converting Move types into values. Use with care! */\n\nimport { MoveStruct } from '../../../utils/index.js';\nimport { bcs } from '@mysten/sui/bcs';\nconst $moduleName = 'std::type_name';\nexport const TypeName = new MoveStruct({\n\tname: `${$moduleName}::TypeName`,\n\tfields: {\n\t\t/**\n\t\t * String representation of the type. All types are represented using their source\n\t\t * syntax: \"u8\", \"u64\", \"bool\", \"address\", \"vector\", and so on for primitive types.\n\t\t * Struct types are represented as fully qualified type names; e.g.\n\t\t * `00000000000000000000000000000001::string::String` or\n\t\t * `0000000000000000000000000000000a::module_name1::type_name1<0000000000000000000000000000000a::module_name2::type_name2<u64>>`\n\t\t * Addresses are hex-encoded lowercase values of length ADDRESS_LENGTH (16, 20, or\n\t\t * 32 depending on the Move platform)\n\t\t */\n\t\tname: bcs.string(),\n\t},\n});\n","/**************************************************************\n * THIS FILE IS GENERATED AND SHOULD NOT BE MANUALLY MODIFIED *\n **************************************************************/\nimport { type BcsType, bcs } from '@mysten/sui/bcs';\nimport { MoveStruct } from '../../../utils/index.js';\nconst $moduleName = '0x2::vec_map';\n/** An entry in the map */\nexport function Entry<K extends BcsType<any>, V extends BcsType<any>>(...typeParameters: [K, V]) {\n\treturn new MoveStruct({\n\t\tname: `${$moduleName}::Entry<${typeParameters[0].name as K['name']}, ${typeParameters[1].name as V['name']}>`,\n\t\tfields: {\n\t\t\tkey: typeParameters[0],\n\t\t\tvalue: typeParameters[1],\n\t\t},\n\t});\n}\n/**\n * A map data structure backed by a vector. The map is guaranteed not to contain\n * duplicate keys, but entries are _not_ sorted by key--entries are included in\n * insertion order. All operations are O(N) in the size of the map--the intention\n * of this data structure is only to provide the convenience of programming against\n * a map API. Large maps should use handwritten parent/child relationships instead.\n * Maps that need sorted iteration rather than insertion order iteration should\n * also be handwritten.\n */\nexport function VecMap<K extends BcsType<any>, V extends BcsType<any>>(...typeParameters: [K, V]) {\n\treturn new MoveStruct({\n\t\tname: `${$moduleName}::VecMap<${typeParameters[0].name as K['name']}, ${typeParameters[1].name as V['name']}>`,\n\t\tfields: {\n\t\t\tcontents: bcs.vector(Entry(typeParameters[0], typeParameters[1])),\n\t\t},\n\t});\n}\n","/**************************************************************\n * THIS FILE IS GENERATED AND SHOULD NOT BE MANUALLY MODIFIED *\n **************************************************************/\nimport {\n\tMoveTuple,\n\tMoveStruct,\n\tnormalizeMoveArguments,\n\ttype RawTransactionArgument,\n} from '../utils/index.js';\nimport { bcs } from '@mysten/sui/bcs';\nimport { type Transaction, type TransactionArgument } from '@mysten/sui/transactions';\nimport * as type_name from './deps/std/type_name.js';\nimport * as vec_map from './deps/sui/vec_map.js';\nconst $moduleName = '@suins/payments::payments';\nexport const PaymentsApp = new MoveTuple({\n\tname: `${$moduleName}::PaymentsApp`,\n\tfields: [bcs.bool()],\n});\nexport const CoinTypeData = new MoveStruct({\n\tname: `${$moduleName}::CoinTypeData`,\n\tfields: {\n\t\t/** The coin's decimals. */\n\t\tdecimals: bcs.u8(),\n\t\tdiscount_percentage: bcs.u8(),\n\t\tprice_feed_id: bcs.vector(bcs.u8()),\n\t\ttype_name: type_name.TypeName,\n\t},\n});\nexport const PaymentsConfig = new MoveStruct({\n\tname: `${$moduleName}::PaymentsConfig`,\n\tfields: {\n\t\tcurrencies: vec_map.VecMap(type_name.TypeName, CoinTypeData),\n\t\tbase_currency: type_name.TypeName,\n\t\tmax_age: bcs.u64(),\n\t\t/** The percentage of the payment that gets burned, in basis points. */\n\t\tburn_bps: bcs.u64(),\n\t},\n});\nexport interface HandleBasePaymentArguments {\n\tsuins: RawTransactionArgument<string>;\n\tbbbVault: RawTransactionArgument<string>;\n\tintent: TransactionArgument;\n\tpayment: RawTransactionArgument<string>;\n}\nexport interface HandleBasePaymentOptions {\n\tpackage?: string;\n\targuments:\n\t\t| HandleBasePaymentArguments\n\t\t| [\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\tbbbVault: RawTransactionArgument<string>,\n\t\t\t\tintent: TransactionArgument,\n\t\t\t\tpayment: RawTransactionArgument<string>,\n\t\t ];\n\ttypeArguments: [string];\n}\n/**\n * This has to be called with our base payment currency. The payment has to be\n * equal to the base price of the domain. We do not need to check the price feed\n * for the base currency.\n */\nexport function handleBasePayment(options: HandleBasePaymentOptions) {\n\tconst packageAddress = options.package ?? '@suins/payments';\n\tconst argumentsTypes = [null, null, null, null] satisfies (string | null)[];\n\tconst parameterNames = ['suins', 'bbbVault', 'intent', 'payment'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'payments',\n\t\t\tfunction: 'handle_base_payment',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t\ttypeArguments: options.typeArguments,\n\t\t});\n}\nexport interface HandlePaymentArguments {\n\tsuins: RawTransactionArgument<string>;\n\tbbbVault: RawTransactionArgument<string>;\n\tintent: TransactionArgument;\n\tpayment: RawTransactionArgument<string>;\n\tpriceInfoObject: RawTransactionArgument<string>;\n\tuserPriceGuard: RawTransactionArgument<number | bigint>;\n}\nexport interface HandlePaymentOptions {\n\tpackage?: string;\n\targuments:\n\t\t| HandlePaymentArguments\n\t\t| [\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\tbbbVault: RawTransactionArgument<string>,\n\t\t\t\tintent: TransactionArgument,\n\t\t\t\tpayment: RawTransactionArgument<string>,\n\t\t\t\tpriceInfoObject: RawTransactionArgument<string>,\n\t\t\t\tuserPriceGuard: RawTransactionArgument<number | bigint>,\n\t\t ];\n\ttypeArguments: [string];\n}\n/**\n * Handles a payment done for a non-base currency payment. E.g. SUI, NS.\n *\n * The payment amount is derived from the base currency price and the Pyth price\n * feed.\n *\n * The `user_price_guard` is a value that the user expects to pay. If the payment\n * amount is higher than this value, the payment will be rejected. This is to\n * protect the user from paying more than they expected on their FEs. Ideally, this\n * number should be calculated on the FE based on the price that is being displayed\n * to the user (with a buffer determined by the FE).\n */\nexport function handlePayment(options: HandlePaymentOptions) {\n\tconst packageAddress = options.package ?? '@suins/payments';\n\tconst argumentsTypes = [null, null, null, null, '0x2::clock::Clock', null, 'u64'] satisfies (\n\t\t| string\n\t\t| null\n\t)[];\n\tconst parameterNames = [\n\t\t'suins',\n\t\t'bbbVault',\n\t\t'intent',\n\t\t'payment',\n\t\t'priceInfoObject',\n\t\t'userPriceGuard',\n\t];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'payments',\n\t\t\tfunction: 'handle_payment',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t\ttypeArguments: options.typeArguments,\n\t\t});\n}\nexport interface CalculatePriceArguments {\n\tsuins: RawTransactionArgument<string>;\n\tbaseAmount: RawTransactionArgument<number | bigint>;\n\tpriceInfoObject: RawTransactionArgument<string>;\n}\nexport interface CalculatePriceOptions {\n\tpackage?: string;\n\targuments:\n\t\t| CalculatePriceArguments\n\t\t| [\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\tbaseAmount: RawTransactionArgument<number | bigint>,\n\t\t\t\tpriceInfoObject: RawTransactionArgument<string>,\n\t\t ];\n\ttypeArguments: [string];\n}\n/**\n * Calculates the amount that has to be paid in the target currency.\n *\n * Can be used to split the payment amount in a single PTB.\n *\n * 1. const intent = function_to_get_intent();\n * 2. const price = calculate_price<SUI>(suins, intent, ...);\n * 3. const coin = txb.splitCoins(baseCoin, [price])\n * 4. handle_payment<SUI>(suins, intent, coin, ...);\n */\nexport function calculatePrice(options: CalculatePriceOptions) {\n\tconst packageAddress = options.package ?? '@suins/payments';\n\tconst argumentsTypes = [null, 'u64', '0x2::clock::Clock', null] satisfies (string | null)[];\n\tconst parameterNames = ['suins', 'baseAmount', 'priceInfoObject'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'payments',\n\t\t\tfunction: 'calculate_price',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t\ttypeArguments: options.typeArguments,\n\t\t});\n}\nexport interface CalculatePriceAfterDiscountArguments {\n\tsuins: RawTransactionArgument<string>;\n\tintent: TransactionArgument;\n}\nexport interface CalculatePriceAfterDiscountOptions {\n\tpackage?: string;\n\targuments:\n\t\t| CalculatePriceAfterDiscountArguments\n\t\t| [suins: RawTransactionArgument<string>, intent: TransactionArgument];\n\ttypeArguments: [string];\n}\nexport function calculatePriceAfterDiscount(options: CalculatePriceAfterDiscountOptions) {\n\tconst packageAddress = options.package ?? '@suins/payments';\n\tconst argumentsTypes = [null, null] satisfies (string | null)[];\n\tconst parameterNames = ['suins', 'intent'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'payments',\n\t\t\tfunction: 'calculate_price_after_discount',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t\ttypeArguments: options.typeArguments,\n\t\t});\n}\nexport interface NewCoinTypeDataArguments {\n\tcoinMetadata: RawTransactionArgument<string>;\n\tdiscountPercentage: RawTransactionArgument<number>;\n\tpriceFeedId: RawTransactionArgument<Array<number>>;\n}\nexport interface NewCoinTypeDataOptions {\n\tpackage?: string;\n\targuments:\n\t\t| NewCoinTypeDataArguments\n\t\t| [\n\t\t\t\tcoinMetadata: RawTransactionArgument<string>,\n\t\t\t\tdiscountPercentage: RawTransactionArgument<number>,\n\t\t\t\tpriceFeedId: RawTransactionArgument<Array<number>>,\n\t\t ];\n\ttypeArguments: [string];\n}\n/** Creates a new CoinTypeData struct. Leave price_feed_id empty for base currency. */\nexport function newCoinTypeData(options: NewCoinTypeDataOptions) {\n\tconst packageAddress = options.package ?? '@suins/payments';\n\tconst argumentsTypes = [null, 'u8', 'vector<u8>'] satisfies (string | null)[];\n\tconst parameterNames = ['coinMetadata', 'discountPercentage', 'priceFeedId'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'payments',\n\t\t\tfunction: 'new_coin_type_data',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t\ttypeArguments: options.typeArguments,\n\t\t});\n}\nexport interface NewPaymentsConfigArguments {\n\tsetups: TransactionArgument;\n\tbaseCurrency: TransactionArgument;\n\tmaxAge: RawTransactionArgument<number | bigint>;\n\tburnBps: RawTransactionArgument<number | bigint>;\n}\nexport interface NewPaymentsConfigOptions {\n\tpackage?: string;\n\targuments:\n\t\t| NewPaymentsConfigArguments\n\t\t| [\n\t\t\t\tsetups: TransactionArgument,\n\t\t\t\tbaseCurrency: TransactionArgument,\n\t\t\t\tmaxAge: RawTransactionArgument<number | bigint>,\n\t\t\t\tburnBps: RawTransactionArgument<number | bigint>,\n\t\t ];\n}\n/**\n * Creates a new PaymentsConfig struct. Can be attached by the Admin to SuiNS to\n * allow the payments module to work.\n */\nexport function newPaymentsConfig(options: NewPaymentsConfigOptions) {\n\tconst packageAddress = options.package ?? '@suins/payments';\n\tconst argumentsTypes = ['vector<null>', null, 'u64', 'u64'] satisfies (string | null)[];\n\tconst parameterNames = ['setups', 'baseCurrency', 'maxAge', 'burnBps'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'payments',\n\t\t\tfunction: 'new_payments_config',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\n","/**************************************************************\n * THIS FILE IS GENERATED AND SHOULD NOT BE MANUALLY MODIFIED *\n **************************************************************/\n\n/** Functionality for converting Move types into values. Use with care! */\n\nimport { MoveStruct } from '../../../utils/index.js';\nimport { bcs } from '@mysten/sui/bcs';\nconst $moduleName = 'std::type_name';\nexport const TypeName = new MoveStruct({\n\tname: `${$moduleName}::TypeName`,\n\tfields: {\n\t\t/**\n\t\t * String representation of the type. All types are represented using their source\n\t\t * syntax: \"u8\", \"u64\", \"bool\", \"address\", \"vector\", and so on for primitive types.\n\t\t * Struct types are represented as fully qualified type names; e.g.\n\t\t * `00000000000000000000000000000001::string::String` or\n\t\t * `0000000000000000000000000000000a::module_name1::type_name1<0000000000000000000000000000000a::module_name2::type_name2<u64>>`\n\t\t * Addresses are hex-encoded lowercase values of length ADDRESS_LENGTH (16, 20, or\n\t\t * 32 depending on the Move platform)\n\t\t */\n\t\tname: bcs.string(),\n\t},\n});\n","/**************************************************************\n * THIS FILE IS GENERATED AND SHOULD NOT BE MANUALLY MODIFIED *\n **************************************************************/\nimport {\n\tMoveStruct,\n\tMoveEnum,\n\tnormalizeMoveArguments,\n\ttype RawTransactionArgument,\n} from '../utils/index.js';\nimport { bcs, type BcsType } from '@mysten/sui/bcs';\nimport { type Transaction, type TransactionArgument } from '@mysten/sui/transactions';\nimport * as domain_1 from './domain.js';\nimport * as vec_map from './deps/sui/vec_map.js';\nimport * as type_name from './deps/std/type_name.js';\nconst $moduleName = '@suins/core::payment';\nexport const RequestData = new MoveStruct({\n\tname: `${$moduleName}::RequestData`,\n\tfields: {\n\t\t/** The version of the payment module. */\n\t\tversion: bcs.u8(),\n\t\t/** The domain for which the payment is being made. */\n\t\tdomain: domain_1.Domain,\n\t\t/** The years for which the payment is being made. Defaults to 1 for registration. */\n\t\tyears: bcs.u8(),\n\t\t/** The amount the user has to pay in base units. */\n\t\tbase_amount: bcs.u64(),\n\t\t/**\n\t\t * The discounts (each app can add a key for its discount) to avoid multiple\n\t\t * additions of the same discount.\n\t\t */\n\t\tdiscounts_applied: vec_map.VecMap(bcs.string(), bcs.u64()),\n\t\t/**\n\t\t * a metadata field for future-proofness. No use-cases are enabled in the current\n\t\t * release.\n\t\t */\n\t\tmetadata: vec_map.VecMap(bcs.string(), bcs.string()),\n\t},\n});\nexport const TransactionEvent = new MoveStruct({\n\tname: `${$moduleName}::TransactionEvent`,\n\tfields: {\n\t\tapp: type_name.TypeName,\n\t\tdomain: domain_1.Domain,\n\t\tyears: bcs.u8(),\n\t\trequest_data_version: bcs.u8(),\n\t\tbase_amount: bcs.u64(),\n\t\tdiscounts_applied: vec_map.VecMap(bcs.string(), bcs.u64()),\n\t\tmetadata: vec_map.VecMap(bcs.string(), bcs.string()),\n\t\tis_renewal: bcs.bool(),\n\t\tcurrency: type_name.TypeName,\n\t\tcurrency_amount: bcs.u64(),\n\t},\n});\n/**\n * The payment intent for a given domain\n *\n * - Registration: The user is registering a new domain.\n * - Renewal: The user is renewing an existing domain.\n */\nexport const PaymentIntent = new MoveEnum({\n\tname: `${$moduleName}::PaymentIntent`,\n\tfields: {\n\t\tRegistration: RequestData,\n\t\tRenewal: RequestData,\n\t},\n});\n/**\n * A receipt that is generated after a successful payment. Can be used to:\n *\n * - Prove that the payment was successful.\n * - Register a new name, or renew an existing one.\n */\nexport const Receipt = new MoveEnum({\n\tname: `${$moduleName}::Receipt`,\n\tfields: {\n\t\tRegistration: new MoveStruct({\n\t\t\tname: `Receipt.Registration`,\n\t\t\tfields: {\n\t\t\t\tdomain: domain_1.Domain,\n\t\t\t\tyears: bcs.u8(),\n\t\t\t\tversion: bcs.u8(),\n\t\t\t},\n\t\t}),\n\t\tRenewal: new MoveStruct({\n\t\t\tname: `Receipt.Renewal`,\n\t\t\tfields: {\n\t\t\t\tdomain: domain_1.Domain,\n\t\t\t\tyears: bcs.u8(),\n\t\t\t\tversion: bcs.u8(),\n\t\t\t},\n\t\t}),\n\t},\n});\nexport interface ApplyPercentageDiscountArguments<A extends BcsType<any>> {\n\tintent: TransactionArgument;\n\tsuins: RawTransactionArgument<string>;\n\t_: RawTransactionArgument<A>;\n\tdiscountKey: RawTransactionArgument<string>;\n\tdiscount: RawTransactionArgument<number>;\n\tallowMultipleDiscounts: RawTransactionArgument<boolean>;\n}\nexport interface ApplyPercentageDiscountOptions<A extends BcsType<any>> {\n\tpackage?: string;\n\targuments:\n\t\t| ApplyPercentageDiscountArguments<A>\n\t\t| [\n\t\t\t\tintent: TransactionArgument,\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\t_: RawTransactionArgument<A>,\n\t\t\t\tdiscountKey: RawTransactionArgument<string>,\n\t\t\t\tdiscount: RawTransactionArgument<number>,\n\t\t\t\tallowMultipleDiscounts: RawTransactionArgument<boolean>,\n\t\t ];\n\ttypeArguments: [string];\n}\n/**\n * Allow an authorized app to apply a percentage discount to the payment intent.\n * E.g. an NS payment can apply a 10% discount on top of a user's 20% discount if\n * allow_multiple_discounts is true\n */\nexport function applyPercentageDiscount<A extends BcsType<any>>(\n\toptions: ApplyPercentageDiscountOptions<A>,\n) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [\n\t\tnull,\n\t\tnull,\n\t\t`${options.typeArguments[0]}`,\n\t\t'0x1::string::String',\n\t\t'u8',\n\t\t'bool',\n\t] satisfies (string | null)[];\n\tconst parameterNames = [\n\t\t'intent',\n\t\t'suins',\n\t\t'_',\n\t\t'discountKey',\n\t\t'discount',\n\t\t'allowMultipleDiscounts',\n\t];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'payment',\n\t\t\tfunction: 'apply_percentage_discount',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t\ttypeArguments: options.typeArguments,\n\t\t});\n}\nexport interface FinalizePaymentArguments<A extends BcsType<any>> {\n\tintent: TransactionArgument;\n\tsuins: RawTransactionArgument<string>;\n\tapp: RawTransactionArgument<A>;\n\tcoin: RawTransactionArgument<string>;\n}\nexport interface FinalizePaymentOptions<A extends BcsType<any>> {\n\tpackage?: string;\n\targuments:\n\t\t| FinalizePaymentArguments<A>\n\t\t| [\n\t\t\t\tintent: TransactionArgument,\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\tapp: RawTransactionArgument<A>,\n\t\t\t\tcoin: RawTransactionArgument<string>,\n\t\t ];\n\ttypeArguments: [string, string];\n}\n/**\n * Allow an authorized app to finalize a payment. Returns a receipt that can be\n * used to register or renew a domain.\n *\n * SAFETY: Only authorized packages can call this. We do not check the amount of\n * funds in this helper. This is the responsibility of the `payments` app.\n */\nexport function finalizePayment<A extends BcsType<any>>(options: FinalizePaymentOptions<A>) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null, null, `${options.typeArguments[0]}`, null] satisfies (\n\t\t| string\n\t\t| null\n\t)[];\n\tconst parameterNames = ['intent', 'suins', 'app', 'coin'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'payment',\n\t\t\tfunction: 'finalize_payment',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t\ttypeArguments: options.typeArguments,\n\t\t});\n}\nexport interface InitRegistrationArguments {\n\tsuins: RawTransactionArgument<string>;\n\tdomain: RawTransactionArgument<string>;\n}\nexport interface InitRegistrationOptions {\n\tpackage?: string;\n\targuments:\n\t\t| InitRegistrationArguments\n\t\t| [suins: RawTransactionArgument<string>, domain: RawTransactionArgument<string>];\n}\n/**\n * Creates a `PaymentIntent` for registering a new domain. This is a hot-potato and\n * can only be consumed in a single transaction.\n */\nexport function initRegistration(options: InitRegistrationOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null, '0x1::string::String'] satisfies (string | null)[];\n\tconst parameterNames = ['suins', 'domain'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'payment',\n\t\t\tfunction: 'init_registration',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface InitRenewalArguments {\n\tsuins: RawTransactionArgument<string>;\n\tnft: RawTransactionArgument<string>;\n\tyears: RawTransactionArgument<number>;\n}\nexport interface InitRenewalOptions {\n\tpackage?: string;\n\targuments:\n\t\t| InitRenewalArguments\n\t\t| [\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\tnft: RawTransactionArgument<string>,\n\t\t\t\tyears: RawTransactionArgument<number>,\n\t\t ];\n}\n/**\n * Creates a `PaymentIntent` for renewing an existing domain. This is a hot-potato\n * and can only be consumed in a single transaction.\n */\nexport function initRenewal(options: InitRenewalOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null, null, 'u8'] satisfies (string | null)[];\n\tconst parameterNames = ['suins', 'nft', 'years'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'payment',\n\t\t\tfunction: 'init_renewal',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface RegisterArguments {\n\treceipt: TransactionArgument;\n\tsuins: RawTransactionArgument<string>;\n}\nexport interface RegisterOptions {\n\tpackage?: string;\n\targuments:\n\t\t| RegisterArguments\n\t\t| [receipt: TransactionArgument, suins: RawTransactionArgument<string>];\n}\n/**\n * Register a domain with the given receipt. This is a hot-potato and can only be\n * consumed in a single transaction.\n */\nexport function register(options: RegisterOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null, null, '0x2::clock::Clock'] satisfies (string | null)[];\n\tconst parameterNames = ['receipt', 'suins'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'payment',\n\t\t\tfunction: 'register',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface RenewArguments {\n\treceipt: TransactionArgument;\n\tsuins: RawTransactionArgument<string>;\n\tnft: RawTransactionArgument<string>;\n}\nexport interface RenewOptions {\n\tpackage?: string;\n\targuments:\n\t\t| RenewArguments\n\t\t| [\n\t\t\t\treceipt: TransactionArgument,\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\tnft: RawTransactionArgument<string>,\n\t\t ];\n}\n/**\n * Renew a domain with the given receipt. This is a hot-potato and can only be\n * consumed in a single transaction.\n */\nexport function renew(options: RenewOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null, null, null, '0x2::clock::Clock'] satisfies (string | null)[];\n\tconst parameterNames = ['receipt', 'suins', 'nft'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'payment',\n\t\t\tfunction: 'renew',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface RequestDataArguments {\n\tintent: TransactionArgument;\n}\nexport interface RequestDataOptions {\n\tpackage?: string;\n\targuments: RequestDataArguments | [intent: TransactionArgument];\n}\n/** Getters */\nexport function requestData(options: RequestDataOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null] satisfies (string | null)[];\n\tconst parameterNames = ['intent'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'payment',\n\t\t\tfunction: 'request_data',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface YearsArguments {\n\tself: TransactionArgument;\n}\nexport interface YearsOptions {\n\tpackage?: string;\n\targuments: YearsArguments | [self: TransactionArgument];\n}\nexport function years(options: YearsOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null] satisfies (string | null)[];\n\tconst parameterNames = ['self'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'payment',\n\t\t\tfunction: 'years',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface BaseAmountArguments {\n\tself: TransactionArgument;\n}\nexport interface BaseAmountOptions {\n\tpackage?: string;\n\targuments: BaseAmountArguments | [self: TransactionArgument];\n}\nexport function baseAmount(options: BaseAmountOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null] satisfies (string | null)[];\n\tconst parameterNames = ['self'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'payment',\n\t\t\tfunction: 'base_amount',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface DomainArguments {\n\tself: TransactionArgument;\n}\nexport interface DomainOptions {\n\tpackage?: string;\n\targuments: DomainArguments | [self: TransactionArgument];\n}\nexport function domain(options: DomainOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null] satisfies (string | null)[];\n\tconst parameterNames = ['self'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'payment',\n\t\t\tfunction: 'domain',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface DiscountAppliedArguments {\n\tself: TransactionArgument;\n}\nexport interface DiscountAppliedOptions {\n\tpackage?: string;\n\targuments: DiscountAppliedArguments | [self: TransactionArgument];\n}\n/** Returns true if at least one discount has been applied to the payment intent. */\nexport function discountApplied(options: DiscountAppliedOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null] satisfies (string | null)[];\n\tconst parameterNames = ['self'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'payment',\n\t\t\tfunction: 'discount_applied',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface DiscountsAppliedArguments {\n\tself: TransactionArgument;\n}\nexport interface DiscountsAppliedOptions {\n\tpackage?: string;\n\targuments: DiscountsAppliedArguments | [self: TransactionArgument];\n}\n/** A list of discounts that have been applied to the payment intent. */\nexport function discountsApplied(options: DiscountsAppliedOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null] satisfies (string | null)[];\n\tconst parameterNames = ['self'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'payment',\n\t\t\tfunction: 'discounts_applied',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface CalculateTotalAfterDiscountArguments {\n\tdata: TransactionArgument;\n\tdiscount: RawTransactionArgument<number>;\n}\nexport interface CalculateTotalAfterDiscountOptions {\n\tpackage?: string;\n\targuments:\n\t\t| CalculateTotalAfterDiscountArguments\n\t\t| [data: TransactionArgument, discount: RawTransactionArgument<number>];\n}\n/** Public helper to calculate price after a percentage discount has been applied. */\nexport function calculateTotalAfterDiscount(options: CalculateTotalAfterDiscountOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null, 'u8'] satisfies (string | null)[];\n\tconst parameterNames = ['data', 'discount'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'payment',\n\t\t\tfunction: 'calculate_total_after_discount',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\n","/**************************************************************\n * THIS FILE IS GENERATED AND SHOULD NOT BE MANUALLY MODIFIED *\n **************************************************************/\nimport {\n\tMoveStruct,\n\tMoveTuple,\n\tnormalizeMoveArguments,\n\ttype RawTransactionArgument,\n} from '../utils/index.js';\nimport { bcs } from '@mysten/sui/bcs';\nimport { type Transaction } from '@mysten/sui/transactions';\nimport * as domain from './domain.js';\nconst $moduleName = '@suins/core::controller';\nexport const SubnamePrunedEvent = new MoveStruct({\n\tname: `${$moduleName}::SubnamePrunedEvent`,\n\tfields: {\n\t\tsubdomain: domain.Domain,\n\t\tparent_domain: domain.Domain,\n\t},\n});\nexport const ControllerV2 = new MoveTuple({\n\tname: `${$moduleName}::ControllerV2`,\n\tfields: [bcs.bool()],\n});\nexport const Controller = new MoveStruct({\n\tname: `${$moduleName}::Controller`,\n\tfields: {\n\t\tdummy_field: bcs.bool(),\n\t},\n});\nexport interface SetTargetAddressArguments {\n\tsuins: RawTransactionArgument<string>;\n\tnft: RawTransactionArgument<string>;\n\tnewTarget: RawTransactionArgument<string | null>;\n}\nexport interface SetTargetAddressOptions {\n\tpackage?: string;\n\targuments:\n\t\t| SetTargetAddressArguments\n\t\t| [\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\tnft: RawTransactionArgument<string>,\n\t\t\t\tnewTarget: RawTransactionArgument<string | null>,\n\t\t ];\n}\n/** Set the target address of a domain. */\nexport function setTargetAddress(options: SetTargetAddressOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [\n\t\tnull,\n\t\tnull,\n\t\t'0x1::option::Option<address>',\n\t\t'0x2::clock::Clock',\n\t] satisfies (string | null)[];\n\tconst parameterNames = ['suins', 'nft', 'newTarget'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'controller',\n\t\t\tfunction: 'set_target_address',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface SetReverseLookupArguments {\n\tsuins: RawTransactionArgument<string>;\n\tdomainName: RawTransactionArgument<string>;\n}\nexport interface SetReverseLookupOptions {\n\tpackage?: string;\n\targuments:\n\t\t| SetReverseLookupArguments\n\t\t| [suins: RawTransactionArgument<string>, domainName: RawTransactionArgument<string>];\n}\n/** Set the reverse lookup address for the domain */\nexport function setReverseLookup(options: SetReverseLookupOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null, '0x1::string::String'] satisfies (string | null)[];\n\tconst parameterNames = ['suins', 'domainName'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'controller',\n\t\t\tfunction: 'set_reverse_lookup',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface UnsetReverseLookupArguments {\n\tsuins: RawTransactionArgument<string>;\n}\nexport interface UnsetReverseLookupOptions {\n\tpackage?: string;\n\targuments: UnsetReverseLookupArguments | [suins: RawTransactionArgument<string>];\n}\n/** User-facing function - unset the reverse lookup address for the domain. */\nexport function unsetReverseLookup(options: UnsetReverseLookupOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null] satisfies (string | null)[];\n\tconst parameterNames = ['suins'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'controller',\n\t\t\tfunction: 'unset_reverse_lookup',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface SetObjectReverseLookupArguments {\n\tsuins: RawTransactionArgument<string>;\n\tobj: RawTransactionArgument<string>;\n\tdomainName: RawTransactionArgument<string>;\n}\nexport interface SetObjectReverseLookupOptions {\n\tpackage?: string;\n\targuments:\n\t\t| SetObjectReverseLookupArguments\n\t\t| [\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\tobj: RawTransactionArgument<string>,\n\t\t\t\tdomainName: RawTransactionArgument<string>,\n\t\t ];\n}\n/**\n * Allows setting the reverse lookup address for an object. Expects a mutable\n * reference of the object.\n */\nexport function setObjectReverseLookup(options: SetObjectReverseLookupOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null, '0x2::object::ID', '0x1::string::String'] satisfies (\n\t\t| string\n\t\t| null\n\t)[];\n\tconst parameterNames = ['suins', 'obj', 'domainName'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'controller',\n\t\t\tfunction: 'set_object_reverse_lookup',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface UnsetObjectReverseLookupArguments {\n\tsuins: RawTransactionArgument<string>;\n\tobj: RawTransactionArgument<string>;\n}\nexport interface UnsetObjectReverseLookupOptions {\n\tpackage?: string;\n\targuments:\n\t\t| UnsetObjectReverseLookupArguments\n\t\t| [suins: RawTransactionArgument<string>, obj: RawTransactionArgument<string>];\n}\n/**\n * Allows unsetting the reverse lookup address for an object. Expects a mutable\n * reference of the object.\n */\nexport function unsetObjectReverseLookup(options: UnsetObjectReverseLookupOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null, '0x2::object::ID'] satisfies (string | null)[];\n\tconst parameterNames = ['suins', 'obj'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'controller',\n\t\t\tfunction: 'unset_object_reverse_lookup',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface SetUserDataArguments {\n\tsuins: RawTransactionArgument<string>;\n\tnft: RawTransactionArgument<string>;\n\tkey: RawTransactionArgument<string>;\n\tvalue: RawTransactionArgument<string>;\n}\nexport interface SetUserDataOptions {\n\tpackage?: string;\n\targuments:\n\t\t| SetUserDataArguments\n\t\t| [\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\tnft: RawTransactionArgument<string>,\n\t\t\t\tkey: RawTransactionArgument<string>,\n\t\t\t\tvalue: RawTransactionArgument<string>,\n\t\t ];\n}\n/** User-facing function - add a new key-value pair to the name record's data. */\nexport function setUserData(options: SetUserDataOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [\n\t\tnull,\n\t\tnull,\n\t\t'0x1::string::String',\n\t\t'0x1::string::String',\n\t\t'0x2::clock::Clock',\n\t] satisfies (string | null)[];\n\tconst parameterNames = ['suins', 'nft', 'key', 'value'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'controller',\n\t\t\tfunction: 'set_user_data',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface UnsetUserDataArguments {\n\tsuins: RawTransactionArgument<string>;\n\tnft: RawTransactionArgument<string>;\n\tkey: RawTransactionArgument<string>;\n}\nexport interface UnsetUserDataOptions {\n\tpackage?: string;\n\targuments:\n\t\t| UnsetUserDataArguments\n\t\t| [\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\tnft: RawTransactionArgument<string>,\n\t\t\t\tkey: RawTransactionArgument<string>,\n\t\t ];\n}\n/** User-facing function - remove a key from the name record's data. */\nexport function unsetUserData(options: UnsetUserDataOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null, null, '0x1::string::String', '0x2::clock::Clock'] satisfies (\n\t\t| string\n\t\t| null\n\t)[];\n\tconst parameterNames = ['suins', 'nft', 'key'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'controller',\n\t\t\tfunction: 'unset_user_data',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface BurnExpiredArguments {\n\tsuins: RawTransactionArgument<string>;\n\tnft: RawTransactionArgument<string>;\n}\nexport interface BurnExpiredOptions {\n\tpackage?: string;\n\targuments:\n\t\t| BurnExpiredArguments\n\t\t| [suins: RawTransactionArgument<string>, nft: RawTransactionArgument<string>];\n}\nexport function burnExpired(options: BurnExpiredOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null, null, '0x2::clock::Clock'] satisfies (string | null)[];\n\tconst parameterNames = ['suins', 'nft'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'controller',\n\t\t\tfunction: 'burn_expired',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface BurnExpiredSubnameArguments {\n\tsuins: RawTransactionArgument<string>;\n\tnft: RawTransactionArgument<string>;\n}\nexport interface BurnExpiredSubnameOptions {\n\tpackage?: string;\n\targuments:\n\t\t| BurnExpiredSubnameArguments\n\t\t| [suins: RawTransactionArgument<string>, nft: RawTransactionArgument<string>];\n}\nexport function burnExpiredSubname(options: BurnExpiredSubnameOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null, null, '0x2::clock::Clock'] satisfies (string | null)[];\n\tconst parameterNames = ['suins', 'nft'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'controller',\n\t\t\tfunction: 'burn_expired_subname',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface PruneExpiredSubnameArguments {\n\tsuins: RawTransactionArgument<string>;\n\tparent: RawTransactionArgument<string>;\n\tsubdomainName: RawTransactionArgument<string>;\n}\nexport interface PruneExpiredSubnameOptions {\n\tpackage?: string;\n\targuments:\n\t\t| PruneExpiredSubnameArguments\n\t\t| [\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\tparent: RawTransactionArgument<string>,\n\t\t\t\tsubdomainName: RawTransactionArgument<string>,\n\t\t ];\n}\n/**\n * Prunes an expired subdomain record from the registry by name, gated by ownership\n * of the parent. This allows the parent holder to clean up expired subdomain\n * records even when they don't possess the SubDomainRegistration object. After\n * pruning, the subdomain name becomes available for re-registration. The orphaned\n * SubDomainRegistration object (if it still exists) becomes useless.\n *\n * Use this when you control the parent domain but someone else holds the expired\n * subdomain NFT.\n */\nexport function pruneExpiredSubname(options: PruneExpiredSubnameOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [null, null, '0x1::string::String', '0x2::clock::Clock'] satisfies (\n\t\t| string\n\t\t| null\n\t)[];\n\tconst parameterNames = ['suins', 'parent', 'subdomainName'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'controller',\n\t\t\tfunction: 'prune_expired_subname',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface PruneExpiredSubnamesArguments {\n\tsuins: RawTransactionArgument<string>;\n\tparent: RawTransactionArgument<string>;\n\tsubdomainNames: RawTransactionArgument<Array<string>>;\n}\nexport interface PruneExpiredSubnamesOptions {\n\tpackage?: string;\n\targuments:\n\t\t| PruneExpiredSubnamesArguments\n\t\t| [\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\tparent: RawTransactionArgument<string>,\n\t\t\t\tsubdomainNames: RawTransactionArgument<Array<string>>,\n\t\t ];\n}\n/**\n * Best-effort pruning of multiple expired subdomain records for a given parent.\n *\n * This function does **not** abort if individual entries are:\n *\n * - not subdomains,\n * - not direct children of the parent,\n * - missing from the registry,\n * - not expired,\n * - leaf records.\n *\n * It prunes what it can, emitting `SubnamePrunedEvent` for each successfully\n * pruned record, and returns the total count of pruned entries.\n */\nexport function pruneExpiredSubnames(options: PruneExpiredSubnamesOptions) {\n\tconst packageAddress = options.package ?? '@suins/core';\n\tconst argumentsTypes = [\n\t\tnull,\n\t\tnull,\n\t\t'vector<0x1::string::String>',\n\t\t'0x2::clock::Clock',\n\t] satisfies (string | null)[];\n\tconst parameterNames = ['suins', 'parent', 'subdomainNames'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'controller',\n\t\t\tfunction: 'prune_expired_subnames',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\n","/**************************************************************\n * THIS FILE IS GENERATED AND SHOULD NOT BE MANUALLY MODIFIED *\n **************************************************************/\n\n/**\n * A bag is a heterogeneous map-like collection. The collection is similar to\n * `sui::table` in that its keys and values are not stored within the `Bag` value,\n * but instead are stored using Sui's object system. The `Bag` struct acts only as\n * a handle into the object system to retrieve those keys and values. Note that\n * this means that `Bag` values with exactly the same key-value mapping will not be\n * equal, with `==`, at runtime. For example\n *\n * ```\n * let bag1 = bag::new();\n * let bag2 = bag::new();\n * bag::add(&mut bag1, 0, false);\n * bag::add(&mut bag1, 1, true);\n * bag::add(&mut bag2, 0, false);\n * bag::add(&mut bag2, 1, true);\n * // bag1 does not equal bag2, despite having the same entries\n * assert!(&bag1 != &bag2);\n * ```\n *\n * At it's core, `sui::bag` is a wrapper around `UID` that allows for access to\n * `sui::dynamic_field` while preventing accidentally stranding field values. A\n * `UID` can be deleted, even if it has dynamic fields associated with it, but a\n * bag, on the other hand, must be empty to be destroyed.\n */\n\nimport { MoveStruct } from '../../../utils/index.js';\nimport { bcs } from '@mysten/sui/bcs';\nconst $moduleName = '0x2::bag';\nexport const Bag = new MoveStruct({\n\tname: `${$moduleName}::Bag`,\n\tfields: {\n\t\t/** the ID of this bag */\n\t\tid: bcs.Address,\n\t\t/** the number of key-value pairs in the bag */\n\t\tsize: bcs.u64(),\n\t},\n});\n","/**************************************************************\n * THIS FILE IS GENERATED AND SHOULD NOT BE MANUALLY MODIFIED *\n **************************************************************/\nimport { MoveStruct } from '../utils/index.js';\nimport * as bag from './deps/sui/bag.js';\nconst $moduleName = '@suins/coupons::data';\nexport const Data = new MoveStruct({\n\tname: `${$moduleName}::Data`,\n\tfields: {\n\t\tcoupons: bag.Bag,\n\t},\n});\n","/**************************************************************\n * THIS FILE IS GENERATED AND SHOULD NOT BE MANUALLY MODIFIED *\n **************************************************************/\n\n/**\n * A module to support coupons for SuiNS. This module allows secondary modules\n * (e.g. Discord) to add or remove coupons too. This allows for separation of logic\n * & ease of de-authorization in case we don't want some functionality anymore.\n *\n * Coupons are unique string codes, that can be used (based on the business rules)\n * to claim discounts in the app. Each coupon is validated towards a list of rules.\n * View `rules` module for explanation. The app is authorized on `SuiNS` to be able\n * to claim names and add earnings to the registry.\n */\n\nimport { MoveStruct, normalizeMoveArguments, type RawTransactionArgument } from '../utils/index.js';\nimport { bcs, type BcsType } from '@mysten/sui/bcs';\nimport { type Transaction, type TransactionArgument } from '@mysten/sui/transactions';\nimport * as data from './data.js';\nconst $moduleName = '@suins/coupons::coupon_house';\nexport const CouponsApp = new MoveStruct({\n\tname: `${$moduleName}::CouponsApp`,\n\tfields: {\n\t\tdummy_field: bcs.bool(),\n\t},\n});\nexport const AppKey = new MoveStruct({\n\tname: `${$moduleName}::AppKey<phantom A>`,\n\tfields: {\n\t\tdummy_field: bcs.bool(),\n\t},\n});\nexport const CouponHouse = new MoveStruct({\n\tname: `${$moduleName}::CouponHouse`,\n\tfields: {\n\t\tdata: data.Data,\n\t\tversion: bcs.u8(),\n\t\tstorage: bcs.Address,\n\t},\n});\nexport interface SetupArguments {\n\tsuins: RawTransactionArgument<string>;\n\tcap: RawTransactionArgument<string>;\n}\nexport interface SetupOptions {\n\tpackage?: string;\n\targuments:\n\t\t| SetupArguments\n\t\t| [suins: RawTransactionArgument<string>, cap: RawTransactionArgument<string>];\n}\n/** Called once to setup the CouponHouse on SuiNS. */\nexport function setup(options: SetupOptions) {\n\tconst packageAddress = options.package ?? '@suins/coupons';\n\tconst argumentsTypes = [null, null] satisfies (string | null)[];\n\tconst parameterNames = ['suins', 'cap'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'coupon_house',\n\t\t\tfunction: 'setup',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface ApplyCouponArguments {\n\tsuins: RawTransactionArgument<string>;\n\tintent: TransactionArgument;\n\tcouponCode: RawTransactionArgument<string>;\n}\nexport interface ApplyCouponOptions {\n\tpackage?: string;\n\targuments:\n\t\t| ApplyCouponArguments\n\t\t| [\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\tintent: TransactionArgument,\n\t\t\t\tcouponCode: RawTransactionArgument<string>,\n\t\t ];\n}\nexport function applyCoupon(options: ApplyCouponOptions) {\n\tconst packageAddress = options.package ?? '@suins/coupons';\n\tconst argumentsTypes = [null, null, '0x1::string::String', '0x2::clock::Clock'] satisfies (\n\t\t| string\n\t\t| null\n\t)[];\n\tconst parameterNames = ['suins', 'intent', 'couponCode'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'coupon_house',\n\t\t\tfunction: 'apply_coupon',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface RegisterWithCouponArguments {\n\tSuins: RawTransactionArgument<string>;\n\tCouponCode: RawTransactionArgument<string>;\n\tDomainName: RawTransactionArgument<string>;\n\tNoYears: RawTransactionArgument<number>;\n\tPayment: RawTransactionArgument<string>;\n}\nexport interface RegisterWithCouponOptions {\n\tpackage?: string;\n\targuments:\n\t\t| RegisterWithCouponArguments\n\t\t| [\n\t\t\t\tSuins: RawTransactionArgument<string>,\n\t\t\t\tCouponCode: RawTransactionArgument<string>,\n\t\t\t\tDomainName: RawTransactionArgument<string>,\n\t\t\t\tNoYears: RawTransactionArgument<number>,\n\t\t\t\tPayment: RawTransactionArgument<string>,\n\t\t ];\n}\nexport function registerWithCoupon(options: RegisterWithCouponOptions) {\n\tconst packageAddress = options.package ?? '@suins/coupons';\n\tconst argumentsTypes = [\n\t\tnull,\n\t\t'0x1::string::String',\n\t\t'0x1::string::String',\n\t\t'u8',\n\t\tnull,\n\t\t'0x2::clock::Clock',\n\t] satisfies (string | null)[];\n\tconst parameterNames = ['Suins', 'CouponCode', 'DomainName', 'NoYears', 'Payment'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'coupon_house',\n\t\t\tfunction: 'register_with_coupon',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface CalculateSalePriceArguments {\n\tSuins: RawTransactionArgument<string>;\n\tPrice: RawTransactionArgument<number | bigint>;\n\tCouponCode: RawTransactionArgument<string>;\n}\nexport interface CalculateSalePriceOptions {\n\tpackage?: string;\n\targuments:\n\t\t| CalculateSalePriceArguments\n\t\t| [\n\t\t\t\tSuins: RawTransactionArgument<string>,\n\t\t\t\tPrice: RawTransactionArgument<number | bigint>,\n\t\t\t\tCouponCode: RawTransactionArgument<string>,\n\t\t ];\n}\nexport function calculateSalePrice(options: CalculateSalePriceOptions) {\n\tconst packageAddress = options.package ?? '@suins/coupons';\n\tconst argumentsTypes = [null, 'u64', '0x1::string::String'] satisfies (string | null)[];\n\tconst parameterNames = ['Suins', 'Price', 'CouponCode'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'coupon_house',\n\t\t\tfunction: 'calculate_sale_price',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface AppDataMutArguments<A extends BcsType<any>> {\n\tsuins: RawTransactionArgument<string>;\n\t_: RawTransactionArgument<A>;\n}\nexport interface AppDataMutOptions<A extends BcsType<any>> {\n\tpackage?: string;\n\targuments:\n\t\t| AppDataMutArguments<A>\n\t\t| [suins: RawTransactionArgument<string>, _: RawTransactionArgument<A>];\n\ttypeArguments: [string];\n}\nexport function appDataMut<A extends BcsType<any>>(options: AppDataMutOptions<A>) {\n\tconst packageAddress = options.package ?? '@suins/coupons';\n\tconst argumentsTypes = [null, `${options.typeArguments[0]}`] satisfies (string | null)[];\n\tconst parameterNames = ['suins', '_'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'coupon_house',\n\t\t\tfunction: 'app_data_mut',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t\ttypeArguments: options.typeArguments,\n\t\t});\n}\nexport interface AuthorizeAppArguments {\n\t_: RawTransactionArgument<string>;\n\tsuins: RawTransactionArgument<string>;\n}\nexport interface AuthorizeAppOptions {\n\tpackage?: string;\n\targuments:\n\t\t| AuthorizeAppArguments\n\t\t| [_: RawTransactionArgument<string>, suins: RawTransactionArgument<string>];\n\ttypeArguments: [string];\n}\n/**\n * Authorize an app on the coupon house. This allows to a secondary module to\n * add/remove coupons.\n */\nexport function authorizeApp(options: AuthorizeAppOptions) {\n\tconst packageAddress = options.package ?? '@suins/coupons';\n\tconst argumentsTypes = [null, null] satisfies (string | null)[];\n\tconst parameterNames = ['_', 'suins'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'coupon_house',\n\t\t\tfunction: 'authorize_app',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t\ttypeArguments: options.typeArguments,\n\t\t});\n}\nexport interface DeauthorizeAppArguments {\n\t_: RawTransactionArgument<string>;\n\tsuins: RawTransactionArgument<string>;\n}\nexport interface DeauthorizeAppOptions {\n\tpackage?: string;\n\targuments:\n\t\t| DeauthorizeAppArguments\n\t\t| [_: RawTransactionArgument<string>, suins: RawTransactionArgument<string>];\n\ttypeArguments: [string];\n}\n/** De-authorize an app. The app can no longer add or remove */\nexport function deauthorizeApp(options: DeauthorizeAppOptions) {\n\tconst packageAddress = options.package ?? '@suins/coupons';\n\tconst argumentsTypes = [null, null] satisfies (string | null)[];\n\tconst parameterNames = ['_', 'suins'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'coupon_house',\n\t\t\tfunction: 'deauthorize_app',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t\ttypeArguments: options.typeArguments,\n\t\t});\n}\nexport interface SetVersionArguments {\n\t_: RawTransactionArgument<string>;\n\tsuins: RawTransactionArgument<string>;\n\tversion: RawTransactionArgument<number>;\n}\nexport interface SetVersionOptions {\n\tpackage?: string;\n\targuments:\n\t\t| SetVersionArguments\n\t\t| [\n\t\t\t\t_: RawTransactionArgument<string>,\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\tversion: RawTransactionArgument<number>,\n\t\t ];\n}\n/**\n * An admin helper to set the version of the shared object. Registrations are only\n * possible if the latest version is being used.\n */\nexport function setVersion(options: SetVersionOptions) {\n\tconst packageAddress = options.package ?? '@suins/coupons';\n\tconst argumentsTypes = [null, null, 'u8'] satisfies (string | null)[];\n\tconst parameterNames = ['_', 'suins', 'version'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'coupon_house',\n\t\t\tfunction: 'set_version',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface AssertVersionIsValidArguments {\n\tself: TransactionArgument;\n}\nexport interface AssertVersionIsValidOptions {\n\tpackage?: string;\n\targuments: AssertVersionIsValidArguments | [self: TransactionArgument];\n}\n/** Validate that the version of the app is the latest. */\nexport function assertVersionIsValid(options: AssertVersionIsValidOptions) {\n\tconst packageAddress = options.package ?? '@suins/coupons';\n\tconst argumentsTypes = [null] satisfies (string | null)[];\n\tconst parameterNames = ['self'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'coupon_house',\n\t\t\tfunction: 'assert_version_is_valid',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface AdminAddCouponArguments {\n\t_: RawTransactionArgument<string>;\n\tsuins: RawTransactionArgument<string>;\n\tcode: RawTransactionArgument<string>;\n\tkind: RawTransactionArgument<number>;\n\tamount: RawTransactionArgument<number | bigint>;\n\trules: TransactionArgument;\n}\nexport interface AdminAddCouponOptions {\n\tpackage?: string;\n\targuments:\n\t\t| AdminAddCouponArguments\n\t\t| [\n\t\t\t\t_: RawTransactionArgument<string>,\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\tcode: RawTransactionArgument<string>,\n\t\t\t\tkind: RawTransactionArgument<number>,\n\t\t\t\tamount: RawTransactionArgument<number | bigint>,\n\t\t\t\trules: TransactionArgument,\n\t\t ];\n}\n/**\n * To create a coupon, you have to call the PTB in the specific order\n *\n * 1. (Optional) Call rules::new_domain_length_rule(type, length) // generate a\n * length specific rule (e.g. only domains of size 5)\n * 2. Call rules::coupon_rules(...) to create the coupon's ruleset.\n */\nexport function adminAddCoupon(options: AdminAddCouponOptions) {\n\tconst packageAddress = options.package ?? '@suins/coupons';\n\tconst argumentsTypes = [null, null, '0x1::string::String', 'u8', 'u64', null] satisfies (\n\t\t| string\n\t\t| null\n\t)[];\n\tconst parameterNames = ['_', 'suins', 'code', 'kind', 'amount', 'rules'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'coupon_house',\n\t\t\tfunction: 'admin_add_coupon',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface AdminRemoveCouponArguments {\n\t_: RawTransactionArgument<string>;\n\tsuins: RawTransactionArgument<string>;\n\tcode: RawTransactionArgument<string>;\n}\nexport interface AdminRemoveCouponOptions {\n\tpackage?: string;\n\targuments:\n\t\t| AdminRemoveCouponArguments\n\t\t| [\n\t\t\t\t_: RawTransactionArgument<string>,\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\tcode: RawTransactionArgument<string>,\n\t\t ];\n}\nexport function adminRemoveCoupon(options: AdminRemoveCouponOptions) {\n\tconst packageAddress = options.package ?? '@suins/coupons';\n\tconst argumentsTypes = [null, null, '0x1::string::String'] satisfies (string | null)[];\n\tconst parameterNames = ['_', 'suins', 'code'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'coupon_house',\n\t\t\tfunction: 'admin_remove_coupon',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface AppAddCouponArguments {\n\tdata: TransactionArgument;\n\tcode: RawTransactionArgument<string>;\n\tkind: RawTransactionArgument<number>;\n\tamount: RawTransactionArgument<number | bigint>;\n\trules: TransactionArgument;\n}\nexport interface AppAddCouponOptions {\n\tpackage?: string;\n\targuments:\n\t\t| AppAddCouponArguments\n\t\t| [\n\t\t\t\tdata: TransactionArgument,\n\t\t\t\tcode: RawTransactionArgument<string>,\n\t\t\t\tkind: RawTransactionArgument<number>,\n\t\t\t\tamount: RawTransactionArgument<number | bigint>,\n\t\t\t\trules: TransactionArgument,\n\t\t ];\n}\nexport function appAddCoupon(options: AppAddCouponOptions) {\n\tconst packageAddress = options.package ?? '@suins/coupons';\n\tconst argumentsTypes = [null, '0x1::string::String', 'u8', 'u64', null] satisfies (\n\t\t| string\n\t\t| null\n\t)[];\n\tconst parameterNames = ['data', 'code', 'kind', 'amount', 'rules'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'coupon_house',\n\t\t\tfunction: 'app_add_coupon',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface AppRemoveCouponArguments {\n\tdata: TransactionArgument;\n\tcode: RawTransactionArgument<string>;\n}\nexport interface AppRemoveCouponOptions {\n\tpackage?: string;\n\targuments:\n\t\t| AppRemoveCouponArguments\n\t\t| [data: TransactionArgument, code: RawTransactionArgument<string>];\n}\nexport function appRemoveCoupon(options: AppRemoveCouponOptions) {\n\tconst packageAddress = options.package ?? '@suins/coupons';\n\tconst argumentsTypes = [null, '0x1::string::String'] satisfies (string | null)[];\n\tconst parameterNames = ['data', 'code'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'coupon_house',\n\t\t\tfunction: 'app_remove_coupon',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\n","/**************************************************************\n * THIS FILE IS GENERATED AND SHOULD NOT BE MANUALLY MODIFIED *\n **************************************************************/\n\n/**\n * A module that allows purchasing names in a different price by presenting a\n * reference of type T. Each `T` can have a separate configuration for a discount\n * percentage. If a `T` doesn't exist, registration will fail.\n *\n * Can be called only when promotions are active for a specific type T. Activation\n * / deactivation happens through PTBs.\n */\n\nimport { MoveTuple, normalizeMoveArguments, type RawTransactionArgument } from '../utils/index.js';\nimport { bcs, type BcsType } from '@mysten/sui/bcs';\nimport { type Transaction, type TransactionArgument } from '@mysten/sui/transactions';\nconst $moduleName = '@suins/discounts::discounts';\nexport const RegularDiscountsApp = new MoveTuple({\n\tname: `${$moduleName}::RegularDiscountsApp`,\n\tfields: [bcs.bool()],\n});\nexport const DiscountKey = new MoveTuple({\n\tname: `${$moduleName}::DiscountKey<phantom T>`,\n\tfields: [bcs.bool()],\n});\nexport interface ApplyPercentageDiscountArguments<T extends BcsType<any>> {\n\tself: RawTransactionArgument<string>;\n\tintent: TransactionArgument;\n\tsuins: RawTransactionArgument<string>;\n\t_: RawTransactionArgument<T>;\n}\nexport interface ApplyPercentageDiscountOptions<T extends BcsType<any>> {\n\tpackage?: string;\n\targuments:\n\t\t| ApplyPercentageDiscountArguments<T>\n\t\t| [\n\t\t\t\tself: RawTransactionArgument<string>,\n\t\t\t\tintent: TransactionArgument,\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\t_: RawTransactionArgument<T>,\n\t\t ];\n\ttypeArguments: [string];\n}\n/** A function to register a name with a discount using type `T`. */\nexport function applyPercentageDiscount<T extends BcsType<any>>(\n\toptions: ApplyPercentageDiscountOptions<T>,\n) {\n\tconst packageAddress = options.package ?? '@suins/discounts';\n\tconst argumentsTypes = [null, null, null, `${options.typeArguments[0]}`] satisfies (\n\t\t| string\n\t\t| null\n\t)[];\n\tconst parameterNames = ['self', 'intent', 'suins', '_'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'discounts',\n\t\t\tfunction: 'apply_percentage_discount',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t\ttypeArguments: options.typeArguments,\n\t\t});\n}\nexport interface ApplyDayOneDiscountArguments {\n\tself: RawTransactionArgument<string>;\n\tintent: TransactionArgument;\n\tsuins: RawTransactionArgument<string>;\n\tdayOne: RawTransactionArgument<string>;\n}\nexport interface ApplyDayOneDiscountOptions {\n\tpackage?: string;\n\targuments:\n\t\t| ApplyDayOneDiscountArguments\n\t\t| [\n\t\t\t\tself: RawTransactionArgument<string>,\n\t\t\t\tintent: TransactionArgument,\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\tdayOne: RawTransactionArgument<string>,\n\t\t ];\n}\n/**\n * A special function for DayOne registration. We separate it from the normal\n * registration flow because we only want it to be usable for activated DayOnes.\n */\nexport function applyDayOneDiscount(options: ApplyDayOneDiscountOptions) {\n\tconst packageAddress = options.package ?? '@suins/discounts';\n\tconst argumentsTypes = [null, null, null, null] satisfies (string | null)[];\n\tconst parameterNames = ['self', 'intent', 'suins', 'dayOne'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'discounts',\n\t\t\tfunction: 'apply_day_one_discount',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface AuthorizeTypeArguments {\n\tself: RawTransactionArgument<string>;\n\t_: RawTransactionArgument<string>;\n\tpricingConfig: TransactionArgument;\n}\nexport interface AuthorizeTypeOptions {\n\tpackage?: string;\n\targuments:\n\t\t| AuthorizeTypeArguments\n\t\t| [\n\t\t\t\tself: RawTransactionArgument<string>,\n\t\t\t\t_: RawTransactionArgument<string>,\n\t\t\t\tpricingConfig: TransactionArgument,\n\t\t ];\n\ttypeArguments: [string];\n}\n/**\n * An admin action to authorize a type T for special pricing.\n *\n * When authorizing, we reuse the core `PricingConfig` struct, and only accept it\n * if all the values are in the [0, 100] range. make sure that all the percentages\n * are in the [0, 99] range. We can use `free_claims` to giveaway free names.\n */\nexport function authorizeType(options: AuthorizeTypeOptions) {\n\tconst packageAddress = options.package ?? '@suins/discounts';\n\tconst argumentsTypes = [null, null, null] satisfies (string | null)[];\n\tconst parameterNames = ['self', '_', 'pricingConfig'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'discounts',\n\t\t\tfunction: 'authorize_type',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t\ttypeArguments: options.typeArguments,\n\t\t});\n}\nexport interface DeauthorizeTypeArguments {\n\t_: RawTransactionArgument<string>;\n\tself: RawTransactionArgument<string>;\n}\nexport interface DeauthorizeTypeOptions {\n\tpackage?: string;\n\targuments:\n\t\t| DeauthorizeTypeArguments\n\t\t| [_: RawTransactionArgument<string>, self: RawTransactionArgument<string>];\n\ttypeArguments: [string];\n}\n/** An admin action to deauthorize type T from getting discounts. */\nexport function deauthorizeType(options: DeauthorizeTypeOptions) {\n\tconst packageAddress = options.package ?? '@suins/discounts';\n\tconst argumentsTypes = [null, null] satisfies (string | null)[];\n\tconst parameterNames = ['_', 'self'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'discounts',\n\t\t\tfunction: 'deauthorize_type',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t\ttypeArguments: options.typeArguments,\n\t\t});\n}\n","/**************************************************************\n * THIS FILE IS GENERATED AND SHOULD NOT BE MANUALLY MODIFIED *\n **************************************************************/\nimport { MoveTuple } from '../../../utils/index.js';\nimport { bcs } from '@mysten/sui/bcs';\nconst $moduleName = 'suins::pricing_config';\nexport const Range = new MoveTuple({\n\tname: `${$moduleName}::Range`,\n\tfields: [bcs.u64(), bcs.u64()],\n});\n","/**************************************************************\n * THIS FILE IS GENERATED AND SHOULD NOT BE MANUALLY MODIFIED *\n **************************************************************/\n\n/**\n * Similar to `sui::table` but the values are linked together, allowing for ordered\n * insertion and removal\n */\n\nimport { type BcsType, bcs } from '@mysten/sui/bcs';\nimport { MoveStruct } from '../../../utils/index.js';\nconst $moduleName = '0x2::linked_table';\nexport function LinkedTable<K extends BcsType<any>>(...typeParameters: [K]) {\n\treturn new MoveStruct({\n\t\tname: `${$moduleName}::LinkedTable<${typeParameters[0].name as K['name']}, phantom V>`,\n\t\tfields: {\n\t\t\t/** the ID of this table */\n\t\t\tid: bcs.Address,\n\t\t\t/** the number of key-value pairs in the table */\n\t\t\tsize: bcs.u64(),\n\t\t\t/** the front of the table, i.e. the key of the first entry */\n\t\t\thead: bcs.option(typeParameters[0]),\n\t\t\t/** the back of the table, i.e. the key of the last entry */\n\t\t\ttail: bcs.option(typeParameters[0]),\n\t\t},\n\t});\n}\n","/**************************************************************\n * THIS FILE IS GENERATED AND SHOULD NOT BE MANUALLY MODIFIED *\n **************************************************************/\n\n/**\n * A module that allows claiming names of a set length for free by presenting an\n * object T. Each `T` can have a separate configuration for a discount percentage.\n * If a `T` doesn't exist, registration will fail.\n *\n * Can be called only when promotions are active for a specific type T. Activation\n * / deactivation happens through PTBs.\n */\n\nimport {\n\tMoveTuple,\n\tMoveStruct,\n\tnormalizeMoveArguments,\n\ttype RawTransactionArgument,\n} from '../utils/index.js';\nimport { bcs, type BcsType } from '@mysten/sui/bcs';\nimport { type Transaction, type TransactionArgument } from '@mysten/sui/transactions';\nimport * as pricing_config from './deps/suins/pricing_config.js';\nimport * as linked_table from './deps/sui/linked_table.js';\nconst $moduleName = '@suins/discounts::free_claims';\nexport const FreeClaimsApp = new MoveTuple({\n\tname: `${$moduleName}::FreeClaimsApp`,\n\tfields: [bcs.bool()],\n});\nexport const FreeClaimsKey = new MoveTuple({\n\tname: `${$moduleName}::FreeClaimsKey<phantom T>`,\n\tfields: [bcs.bool()],\n});\nexport const FreeClaimsConfig = new MoveStruct({\n\tname: `${$moduleName}::FreeClaimsConfig`,\n\tfields: {\n\t\tdomain_length_range: pricing_config.Range,\n\t\tused_objects: linked_table.LinkedTable(bcs.Address),\n\t},\n});\nexport interface FreeClaimArguments<T extends BcsType<any>> {\n\tself: RawTransactionArgument<string>;\n\tsuins: RawTransactionArgument<string>;\n\tintent: TransactionArgument;\n\tobject: RawTransactionArgument<T>;\n}\nexport interface FreeClaimOptions<T extends BcsType<any>> {\n\tpackage?: string;\n\targuments:\n\t\t| FreeClaimArguments<T>\n\t\t| [\n\t\t\t\tself: RawTransactionArgument<string>,\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\tintent: TransactionArgument,\n\t\t\t\tobject: RawTransactionArgument<T>,\n\t\t ];\n\ttypeArguments: [string];\n}\n/** A function to register a name with a discount using type `T`. */\nexport function freeClaim<T extends BcsType<any>>(options: FreeClaimOptions<T>) {\n\tconst packageAddress = options.package ?? '@suins/discounts';\n\tconst argumentsTypes = [null, null, null, `${options.typeArguments[0]}`] satisfies (\n\t\t| string\n\t\t| null\n\t)[];\n\tconst parameterNames = ['self', 'suins', 'intent', 'object'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'free_claims',\n\t\t\tfunction: 'free_claim',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t\ttypeArguments: options.typeArguments,\n\t\t});\n}\nexport interface FreeClaimWithDayOneArguments {\n\tself: RawTransactionArgument<string>;\n\tsuins: RawTransactionArgument<string>;\n\tintent: TransactionArgument;\n\tdayOne: RawTransactionArgument<string>;\n}\nexport interface FreeClaimWithDayOneOptions {\n\tpackage?: string;\n\targuments:\n\t\t| FreeClaimWithDayOneArguments\n\t\t| [\n\t\t\t\tself: RawTransactionArgument<string>,\n\t\t\t\tsuins: RawTransactionArgument<string>,\n\t\t\t\tintent: TransactionArgument,\n\t\t\t\tdayOne: RawTransactionArgument<string>,\n\t\t ];\n}\nexport function freeClaimWithDayOne(options: FreeClaimWithDayOneOptions) {\n\tconst packageAddress = options.package ?? '@suins/discounts';\n\tconst argumentsTypes = [null, null, null, null] satisfies (string | null)[];\n\tconst parameterNames = ['self', 'suins', 'intent', 'dayOne'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'free_claims',\n\t\t\tfunction: 'free_claim_with_day_one',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t});\n}\nexport interface AuthorizeTypeArguments {\n\tself: RawTransactionArgument<string>;\n\t_: RawTransactionArgument<string>;\n\tdomainLengthRange: TransactionArgument;\n}\nexport interface AuthorizeTypeOptions {\n\tpackage?: string;\n\targuments:\n\t\t| AuthorizeTypeArguments\n\t\t| [\n\t\t\t\tself: RawTransactionArgument<string>,\n\t\t\t\t_: RawTransactionArgument<string>,\n\t\t\t\tdomainLengthRange: TransactionArgument,\n\t\t ];\n\ttypeArguments: [string];\n}\n/**\n * An admin action to authorize a type T for free claiming of names by presenting\n * an object of type `T`.\n */\nexport function authorizeType(options: AuthorizeTypeOptions) {\n\tconst packageAddress = options.package ?? '@suins/discounts';\n\tconst argumentsTypes = [null, null, null] satisfies (string | null)[];\n\tconst parameterNames = ['self', '_', 'domainLengthRange'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'free_claims',\n\t\t\tfunction: 'authorize_type',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t\ttypeArguments: options.typeArguments,\n\t\t});\n}\nexport interface DeauthorizeTypeArguments {\n\tself: RawTransactionArgument<string>;\n\t_: RawTransactionArgument<string>;\n}\nexport interface DeauthorizeTypeOptions {\n\tpackage?: string;\n\targuments:\n\t\t| DeauthorizeTypeArguments\n\t\t| [self: RawTransactionArgument<string>, _: RawTransactionArgument<string>];\n\ttypeArguments: [string];\n}\n/** Force-deauthorize type T from free claims. Drops the linked_table. */\nexport function deauthorizeType(options: DeauthorizeTypeOptions) {\n\tconst packageAddress = options.package ?? '@suins/discounts';\n\tconst argumentsTypes = [null, null] satisfies (string | null)[];\n\tconst parameterNames = ['self', '_'];\n\treturn (tx: Transaction) =>\n\t\ttx.moveCall({\n\t\t\tpackage: packageAddress,\n\t\t\tmodule: 'free_claims',\n\t\t\tfunction: 'deauthorize_type',\n\t\t\targuments: normalizeMoveArguments(options.arguments, argumentsTypes, parameterNames),\n\t\t\ttypeArguments: options.typeArguments,\n\t\t});\n}\n","// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { bcs } from '@mysten/sui/bcs';\nimport type {\n\tTransaction,\n\tTransactionObjectArgument,\n\tTransactionObjectInput,\n} from '@mysten/sui/transactions';\nimport { isValidSuiNSName, normalizeSuiNSName, SUI_CLOCK_OBJECT_ID } from '@mysten/sui/utils';\n\nimport { ALLOWED_METADATA, MAX_U64 } from './constants.js';\nimport { isNestedSubName, isSubName, zeroCoin } from './helpers.js';\nimport type { SuinsClient } from './suins-client.js';\nimport type { DiscountInfo, ReceiptParams, RegistrationParams, RenewalParams } from './types.js';\n\nimport * as payment from './contracts/suins/payment.js';\nimport * as controller from './contracts/suins/controller.js';\nimport * as paymentsModule from './contracts/suins_payments/payments.js';\nimport * as couponHouse from './contracts/suins_coupons/coupon_house.js';\nimport * as discounts from './contracts/suins_discounts/discounts.js';\nimport * as freeClaims from './contracts/suins_discounts/free_claims.js';\n\nexport class SuinsTransaction {\n\tsuinsClient: SuinsClient;\n\ttransaction: Transaction;\n\n\tconstructor(client: SuinsClient, transaction: Transaction) {\n\t\tthis.suinsClient = client;\n\t\tthis.transaction = transaction;\n\t}\n\n\t/**\n\t * Registers a domain for a number of years.\n\t */\n\tregister(params: RegistrationParams): TransactionObjectArgument {\n\t\tif (params.couponCode && params.discountInfo) {\n\t\t\tthrow new Error('Cannot apply both coupon and discount NFT');\n\t\t}\n\n\t\tconst paymentIntent = this.initRegistration(params.domain);\n\t\tif (params.couponCode) {\n\t\t\tthis.applyCoupon(paymentIntent, params.couponCode);\n\t\t}\n\t\tif (params.discountInfo) {\n\t\t\tthis.applyDiscount(paymentIntent, params.discountInfo);\n\t\t}\n\t\tconst priceAfterDiscount = this.calculatePriceAfterDiscount(\n\t\t\tpaymentIntent,\n\t\t\tparams.coinConfig.type,\n\t\t);\n\t\tconst receipt = this.generateReceipt({\n\t\t\tpaymentIntent,\n\t\t\tpriceAfterDiscount,\n\t\t\tcoinConfig: params.coinConfig,\n\t\t\tcoin: params.coin,\n\t\t\tmaxAmount: params.maxAmount,\n\t\t\tpriceInfoObjectId: params.priceInfoObjectId,\n\t\t});\n\t\tconst nft = this.finalizeRegister(receipt);\n\n\t\tif (params.years > 1) {\n\t\t\tthis.renew({\n\t\t\t\tnft,\n\t\t\t\tyears: params.years - 1,\n\t\t\t\tcoinConfig: params.coinConfig,\n\t\t\t\tcoin: params.coin,\n\t\t\t\tcouponCode: params.couponCode,\n\t\t\t\tdiscountInfo: params.discountInfo,\n\t\t\t\tmaxAmount: params.maxAmount,\n\t\t\t\tpriceInfoObjectId: params.priceInfoObjectId,\n\t\t\t});\n\t\t}\n\n\t\treturn nft as TransactionObjectArgument;\n\t}\n\n\t/**\n\t * Renews an NFT for a number of years.\n\t */\n\trenew(params: RenewalParams): void {\n\t\tif (params.couponCode && params.discountInfo) {\n\t\t\tthrow new Error('Cannot apply both coupon and discount NFT');\n\t\t}\n\n\t\tconst paymentIntent = this.initRenewal(params.nft, params.years);\n\t\tif (params.couponCode) {\n\t\t\tthis.applyCoupon(paymentIntent, params.couponCode);\n\t\t}\n\t\tif (params.discountInfo) {\n\t\t\tthis.applyDiscount(paymentIntent, params.discountInfo);\n\t\t}\n\t\tconst priceAfterDiscount = this.calculatePriceAfterDiscount(\n\t\t\tpaymentIntent,\n\t\t\tparams.coinConfig.type,\n\t\t);\n\t\tconst receipt = this.generateReceipt({\n\t\t\tpaymentIntent,\n\t\t\tpriceAfterDiscount,\n\t\t\tcoinConfig: params.coinConfig,\n\t\t\tcoin: params.coin,\n\t\t\tmaxAmount: params.maxAmount,\n\t\t\tpriceInfoObjectId: params.priceInfoObjectId,\n\t\t});\n\t\tthis.finalizeRenew(receipt, params.nft);\n\t}\n\n\tinitRegistration(domain: string): TransactionObjectArgument {\n\t\tconst config = this.suinsClient.config;\n\t\treturn this.transaction.add(\n\t\t\tpayment.initRegistration({\n\t\t\t\tpackage: config.packageId,\n\t\t\t\targuments: { suins: config.suins, domain },\n\t\t\t}),\n\t\t);\n\t}\n\n\tinitRenewal(nft: TransactionObjectInput, years: number): TransactionObjectArgument {\n\t\tconst config = this.suinsClient.config;\n\t\treturn this.transaction.add(\n\t\t\tpayment.initRenewal({\n\t\t\t\tpackage: config.packageId,\n\t\t\t\targuments: { suins: config.suins, nft: this.transaction.object(nft), years },\n\t\t\t}),\n\t\t);\n\t}\n\n\tcalculatePrice(\n\t\tbaseAmount: TransactionObjectArgument,\n\t\tpaymentType: string,\n\t\tpriceInfoObjectId: string,\n\t): TransactionObjectArgument {\n\t\tconst config = this.suinsClient.config;\n\t\treturn this.transaction.add(\n\t\t\tpaymentsModule.calculatePrice({\n\t\t\t\tpackage: config.payments.packageId,\n\t\t\t\targuments: {\n\t\t\t\t\tsuins: config.suins,\n\t\t\t\t\tbaseAmount,\n\t\t\t\t\tpriceInfoObject: priceInfoObjectId,\n\t\t\t\t},\n\t\t\t\ttypeArguments: [paymentType],\n\t\t\t}),\n\t\t);\n\t}\n\n\thandleBasePayment(\n\t\tpaymentIntent: TransactionObjectArgument,\n\t\tpaymentArg: TransactionObjectArgument,\n\t\tpaymentType: string,\n\t): TransactionObjectArgument {\n\t\tconst config = this.suinsClient.config;\n\t\treturn this.transaction.add(\n\t\t\tpaymentsModule.handleBasePayment({\n\t\t\t\tpackage: config.payments.packageId,\n\t\t\t\targuments: {\n\t\t\t\t\tsuins: config.suins,\n\t\t\t\t\tbbbVault: config.bbb.vault,\n\t\t\t\t\tintent: paymentIntent,\n\t\t\t\t\tpayment: paymentArg,\n\t\t\t\t},\n\t\t\t\ttypeArguments: [paymentType],\n\t\t\t}),\n\t\t);\n\t}\n\n\thandlePayment(\n\t\tpaymentIntent: TransactionObjectArgument,\n\t\tpaymentArg: TransactionObjectArgument,\n\t\tpaymentType: string,\n\t\tpriceInfoObjectId: string,\n\t\tmaxAmount: bigint = MAX_U64,\n\t): TransactionObjectArgument {\n\t\tconst config = this.suinsClient.config;\n\t\treturn this.transaction.add(\n\t\t\tpaymentsModule.handlePayment({\n\t\t\t\tpackage: config.payments.packageId,\n\t\t\t\targuments: {\n\t\t\t\t\tsuins: config.suins,\n\t\t\t\t\tbbbVault: config.bbb.vault,\n\t\t\t\t\tintent: paymentIntent,\n\t\t\t\t\tpayment: paymentArg,\n\t\t\t\t\tpriceInfoObject: priceInfoObjectId,\n\t\t\t\t\tuserPriceGuard: maxAmount,\n\t\t\t\t},\n\t\t\t\ttypeArguments: [paymentType],\n\t\t\t}),\n\t\t);\n\t}\n\n\tfinalizeRegister(receipt: TransactionObjectArgument): TransactionObjectArgument {\n\t\tconst config = this.suinsClient.config;\n\t\treturn this.transaction.add(\n\t\t\tpayment.register({\n\t\t\t\tpackage: config.packageId,\n\t\t\t\targuments: { receipt, suins: config.suins },\n\t\t\t}),\n\t\t);\n\t}\n\n\tfinalizeRenew(\n\t\treceipt: TransactionObjectArgument,\n\t\tnft: TransactionObjectInput,\n\t): TransactionObjectArgument {\n\t\tconst config = this.suinsClient.config;\n\t\treturn this.transaction.add(\n\t\t\tpayment.renew({\n\t\t\t\tpackage: config.packageId,\n\t\t\t\targuments: { receipt, suins: config.suins, nft: this.transaction.object(nft) },\n\t\t\t}),\n\t\t);\n\t}\n\n\tcalculatePriceAfterDiscount(\n\t\tpaymentIntent: TransactionObjectArgument,\n\t\tpaymentType: string,\n\t): TransactionObjectArgument {\n\t\tconst config = this.suinsClient.config;\n\t\treturn this.transaction.add(\n\t\t\tpaymentsModule.calculatePriceAfterDiscount({\n\t\t\t\tpackage: config.payments.packageId,\n\t\t\t\targuments: { suins: config.suins, intent: paymentIntent },\n\t\t\t\ttypeArguments: [paymentType],\n\t\t\t}),\n\t\t);\n\t}\n\n\tgenerateReceipt(params: ReceiptParams): TransactionObjectArgument {\n\t\tconst baseAssetPurchase = params.coinConfig.feed === '';\n\t\tif (baseAssetPurchase) {\n\t\t\tconst payment = params.coin\n\t\t\t\t? this.transaction.splitCoins(this.transaction.object(params.coin), [\n\t\t\t\t\t\tparams.priceAfterDiscount,\n\t\t\t\t\t])\n\t\t\t\t: zeroCoin(this.transaction, params.coinConfig.type);\n\t\t\tconst receipt = this.handleBasePayment(params.paymentIntent, payment, params.coinConfig.type);\n\t\t\treturn receipt;\n\t\t} else {\n\t\t\tconst priceInfoObjectId = params.priceInfoObjectId;\n\t\t\tif (!priceInfoObjectId)\n\t\t\t\tthrow new Error('Price info object ID is required for non-base asset purchases');\n\t\t\tconst price = this.calculatePrice(\n\t\t\t\tparams.priceAfterDiscount,\n\t\t\t\tparams.coinConfig.type,\n\t\t\t\tpriceInfoObjectId,\n\t\t\t);\n\t\t\tif (!params.coin) throw new Error('coin input is required');\n\t\t\tconst payment = this.transaction.splitCoins(this.transaction.object(params.coin!), [price]);\n\t\t\tconst receipt = this.handlePayment(\n\t\t\t\tparams.paymentIntent,\n\t\t\t\tpayment,\n\t\t\t\tparams.coinConfig.type,\n\t\t\t\tpriceInfoObjectId,\n\t\t\t\tparams.maxAmount,\n\t\t\t);\n\t\t\treturn receipt;\n\t\t}\n\t}\n\n\t/**\n\t * Applies a coupon to the payment intent.\n\t */\n\tapplyCoupon(intent: TransactionObjectArgument, couponCode: string): TransactionObjectArgument {\n\t\tconst config = this.suinsClient.config;\n\t\treturn this.transaction.add(\n\t\t\tcouponHouse.applyCoupon({\n\t\t\t\tpackage: config.coupons.packageId,\n\t\t\t\targuments: { suins: config.suins, intent, couponCode },\n\t\t\t}),\n\t\t);\n\t}\n\n\t/**\n\t * Applies a discount to the payment intent.\n\t */\n\tapplyDiscount(intent: TransactionObjectArgument, discountInfo: DiscountInfo): void {\n\t\tconst config = this.suinsClient.config;\n\n\t\tif (discountInfo.isFreeClaim) {\n\t\t\tthis.transaction.add(\n\t\t\t\tfreeClaims.freeClaim({\n\t\t\t\t\tpackage: config.discountsPackage.packageId,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\tself: config.discountsPackage.discountHouseId,\n\t\t\t\t\t\tsuins: config.suins,\n\t\t\t\t\t\tintent,\n\t\t\t\t\t\tobject: this.transaction.object(discountInfo.discountNft),\n\t\t\t\t\t},\n\t\t\t\t\ttypeArguments: [discountInfo.type],\n\t\t\t\t}),\n\t\t\t);\n\t\t} else {\n\t\t\tthis.transaction.add(\n\t\t\t\tdiscounts.applyPercentageDiscount({\n\t\t\t\t\tpackage: config.discountsPackage.packageId,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\tself: config.discountsPackage.discountHouseId,\n\t\t\t\t\t\tintent,\n\t\t\t\t\t\tsuins: config.suins,\n\t\t\t\t\t\t_: this.transaction.object(discountInfo.discountNft),\n\t\t\t\t\t},\n\t\t\t\t\ttypeArguments: [discountInfo.type],\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Creates a subdomain.\n\t */\n\tcreateSubName({\n\t\tparentNft,\n\t\tname,\n\t\texpirationTimestampMs,\n\t\tallowChildCreation,\n\t\tallowTimeExtension,\n\t}: {\n\t\tparentNft: TransactionObjectInput;\n\t\tname: string;\n\t\texpirationTimestampMs: number;\n\t\tallowChildCreation: boolean;\n\t\tallowTimeExtension: boolean;\n\t}) {\n\t\tif (!isValidSuiNSName(name)) throw new Error('Invalid SuiNS name');\n\t\tconst isParentSubdomain = isNestedSubName(name);\n\t\tif (!this.suinsClient.config.suins) throw new Error('SuiNS Object ID not found');\n\t\tif (!this.suinsClient.config.subNamesPackageId)\n\t\t\tthrow new Error('Subnames package ID not found');\n\t\tif (isParentSubdomain && !this.suinsClient.config.tempSubdomainsProxyPackageId)\n\t\t\tthrow new Error('Subnames proxy package ID not found');\n\n\t\tconst subNft = this.transaction.moveCall({\n\t\t\ttarget: isParentSubdomain\n\t\t\t\t? `${this.suinsClient.config.tempSubdomainsProxyPackageId}::subdomain_proxy::new`\n\t\t\t\t: `${this.suinsClient.config.subNamesPackageId}::subdomains::new`,\n\t\t\targuments: [\n\t\t\t\tthis.transaction.object(this.suinsClient.config.suins),\n\t\t\t\tthis.transaction.object(parentNft),\n\t\t\t\tthis.transaction.object(SUI_CLOCK_OBJECT_ID),\n\t\t\t\tthis.transaction.pure.string(normalizeSuiNSName(name, 'dot')),\n\t\t\t\tthis.transaction.pure.u64(expirationTimestampMs),\n\t\t\t\tthis.transaction.pure.bool(!!allowChildCreation),\n\t\t\t\tthis.transaction.pure.bool(!!allowTimeExtension),\n\t\t\t],\n\t\t});\n\n\t\treturn subNft;\n\t}\n\n\t/**\n\t * Builds the PTB to create a leaf subdomain.\n\t * Parent can be a `SuinsRegistration` or a `SubDomainRegistration` object.\n\t * Can be passed in as an ID or a TransactionArgument.\n\t */\n\tcreateLeafSubName({\n\t\tparentNft,\n\t\tname,\n\t\ttargetAddress,\n\t}: {\n\t\tparentNft: TransactionObjectInput;\n\t\tname: string;\n\t\ttargetAddress: string;\n\t}) {\n\t\tif (!isValidSuiNSName(name)) throw new Error('Invalid SuiNS name');\n\t\tconst isParentSubdomain = isNestedSubName(name);\n\t\tif (!this.suinsClient.config.suins) throw new Error('SuiNS Object ID not found');\n\t\tif (!this.suinsClient.config.subNamesPackageId)\n\t\t\tthrow new Error('Subnames package ID not found');\n\t\tif (isParentSubdomain && !this.suinsClient.config.tempSubdomainsProxyPackageId)\n\t\t\tthrow new Error('Subnames proxy package ID not found');\n\n\t\tthis.transaction.moveCall({\n\t\t\ttarget: isParentSubdomain\n\t\t\t\t? `${this.suinsClient.config.tempSubdomainsProxyPackageId}::subdomain_proxy::new_leaf`\n\t\t\t\t: `${this.suinsClient.config.subNamesPackageId}::subdomains::new_leaf`,\n\t\t\targuments: [\n\t\t\t\tthis.transaction.object(this.suinsClient.config.suins),\n\t\t\t\tthis.transaction.object(parentNft),\n\t\t\t\tthis.transaction.object(SUI_CLOCK_OBJECT_ID),\n\t\t\t\tthis.transaction.pure.string(normalizeSuiNSName(name, 'dot')),\n\t\t\t\tthis.transaction.pure.address(targetAddress),\n\t\t\t],\n\t\t});\n\t}\n\n\t/**\n\t * Removes a leaf subname.\n\t */\n\tremoveLeafSubName({ parentNft, name }: { parentNft: TransactionObjectInput; name: string }) {\n\t\tif (!isValidSuiNSName(name)) throw new Error('Invalid SuiNS name');\n\t\tconst isParentSubdomain = isNestedSubName(name);\n\t\tif (!isSubName(name)) throw new Error('This can only be invoked for subnames');\n\t\tif (!this.suinsClient.config.suins) throw new Error('SuiNS Object ID not found');\n\t\tif (!this.suinsClient.config.subNamesPackageId)\n\t\t\tthrow new Error('Subnames package ID not found');\n\t\tif (isParentSubdomain && !this.suinsClient.config.tempSubdomainsProxyPackageId)\n\t\t\tthrow new Error('Subnames proxy package ID not found');\n\n\t\tthis.transaction.moveCall({\n\t\t\ttarget: isParentSubdomain\n\t\t\t\t? `${this.suinsClient.config.tempSubdomainsProxyPackageId}::subdomain_proxy::remove_leaf`\n\t\t\t\t: `${this.suinsClient.config.subNamesPackageId}::subdomains::remove_leaf`,\n\t\t\targuments: [\n\t\t\t\tthis.transaction.object(this.suinsClient.config.suins),\n\t\t\t\tthis.transaction.object(parentNft),\n\t\t\t\tthis.transaction.object(SUI_CLOCK_OBJECT_ID),\n\t\t\t\tthis.transaction.pure.string(normalizeSuiNSName(name, 'dot')),\n\t\t\t],\n\t\t});\n\t}\n\n\t/**\n\t * Sets the target address of an NFT.\n\t */\n\tsetTargetAddress({\n\t\tnft, // Can be string or argument\n\t\taddress,\n\t\tisSubname,\n\t}: {\n\t\tnft: TransactionObjectInput;\n\t\taddress?: string;\n\t\tisSubname?: boolean;\n\t}) {\n\t\tif (isSubname && !this.suinsClient.config.tempSubdomainsProxyPackageId)\n\t\t\tthrow new Error('Subnames proxy package ID not found');\n\n\t\tthis.transaction.moveCall({\n\t\t\ttarget: isSubname\n\t\t\t\t? `${this.suinsClient.config.tempSubdomainsProxyPackageId}::subdomain_proxy::set_target_address`\n\t\t\t\t: `${this.suinsClient.config.packageId}::controller::set_target_address`,\n\t\t\targuments: [\n\t\t\t\tthis.transaction.object(this.suinsClient.config.suins),\n\t\t\t\tthis.transaction.object(nft),\n\t\t\t\tthis.transaction.pure(bcs.option(bcs.Address).serialize(address).toBytes()),\n\t\t\t\tthis.transaction.object(SUI_CLOCK_OBJECT_ID),\n\t\t\t],\n\t\t});\n\t}\n\n\t/**\n\t * Sets a default name for the user.\n\t */\n\tsetDefault(name: string) {\n\t\tif (!isValidSuiNSName(name)) throw new Error('Invalid SuiNS name');\n\t\tif (!this.suinsClient.config.suins) throw new Error('SuiNS Object ID not found');\n\n\t\tthis.transaction.add(\n\t\t\tcontroller.setReverseLookup({\n\t\t\t\tpackage: this.suinsClient.config.packageId,\n\t\t\t\targuments: {\n\t\t\t\t\tsuins: this.suinsClient.config.suins,\n\t\t\t\t\tdomainName: normalizeSuiNSName(name, 'dot'),\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n\t}\n\n\t/**\n\t * Edits the setup of a subname.\n\t */\n\teditSetup({\n\t\tparentNft,\n\t\tname,\n\t\tallowChildCreation,\n\t\tallowTimeExtension,\n\t}: {\n\t\tparentNft: TransactionObjectInput;\n\t\tname: string;\n\t\tallowChildCreation: boolean;\n\t\tallowTimeExtension: boolean;\n\t}) {\n\t\tif (!isValidSuiNSName(name)) throw new Error('Invalid SuiNS name');\n\t\tconst isParentSubdomain = isNestedSubName(name);\n\t\tif (!this.suinsClient.config.suins) throw new Error('SuiNS Object ID not found');\n\t\tif (!isParentSubdomain && !this.suinsClient.config.subNamesPackageId)\n\t\t\tthrow new Error('Subnames package ID not found');\n\t\tif (isParentSubdomain && !this.suinsClient.config.tempSubdomainsProxyPackageId)\n\t\t\tthrow new Error('Subnames proxy package ID not found');\n\n\t\tthis.transaction.moveCall({\n\t\t\ttarget: isParentSubdomain\n\t\t\t\t? `${this.suinsClient.config.tempSubdomainsProxyPackageId}::subdomain_proxy::edit_setup`\n\t\t\t\t: `${this.suinsClient.config.subNamesPackageId}::subdomains::edit_setup`,\n\t\t\targuments: [\n\t\t\t\tthis.transaction.object(this.suinsClient.config.suins),\n\t\t\t\tthis.transaction.object(parentNft),\n\t\t\t\tthis.transaction.object(SUI_CLOCK_OBJECT_ID),\n\t\t\t\tthis.transaction.pure.string(normalizeSuiNSName(name, 'dot')),\n\t\t\t\tthis.transaction.pure.bool(!!allowChildCreation),\n\t\t\t\tthis.transaction.pure.bool(!!allowTimeExtension),\n\t\t\t],\n\t\t});\n\t}\n\n\t/**\n\t * Extends the expiration of a subname.\n\t */\n\textendExpiration({\n\t\tnft,\n\t\texpirationTimestampMs,\n\t}: {\n\t\tnft: TransactionObjectInput;\n\t\texpirationTimestampMs: number;\n\t}) {\n\t\tif (!this.suinsClient.config.suins) throw new Error('SuiNS Object ID not found');\n\t\tif (!this.suinsClient.config.subNamesPackageId)\n\t\t\tthrow new Error('Subnames package ID not found');\n\n\t\tthis.transaction.moveCall({\n\t\t\ttarget: `${this.suinsClient.config.subNamesPackageId}::subdomains::extend_expiration`,\n\t\t\targuments: [\n\t\t\t\tthis.transaction.object(this.suinsClient.config.suins),\n\t\t\t\tthis.transaction.object(nft),\n\t\t\t\tthis.transaction.pure.u64(expirationTimestampMs),\n\t\t\t],\n\t\t});\n\t}\n\n\t/**\n\t * Sets the user data of an NFT.\n\t */\n\tsetUserData({\n\t\tnft,\n\t\tvalue,\n\t\tkey,\n\t\tisSubname,\n\t}: {\n\t\tnft: TransactionObjectInput;\n\t\tvalue: string;\n\t\tkey: string;\n\t\tisSubname?: boolean;\n\t}) {\n\t\tif (!this.suinsClient.config.suins) throw new Error('SuiNS Object ID not found');\n\t\tif (isSubname && !this.suinsClient.config.tempSubdomainsProxyPackageId)\n\t\t\tthrow new Error('Subnames proxy package ID not found');\n\n\t\tif (!Object.values(ALLOWED_METADATA).some((x) => x === key)) throw new Error('Invalid key');\n\n\t\tthis.transaction.moveCall({\n\t\t\ttarget: isSubname\n\t\t\t\t? `${this.suinsClient.config.tempSubdomainsProxyPackageId}::subdomain_proxy::set_user_data`\n\t\t\t\t: `${this.suinsClient.config.packageId}::controller::set_user_data`,\n\t\t\targuments: [\n\t\t\t\tthis.transaction.object(this.suinsClient.config.suins),\n\t\t\t\tthis.transaction.object(nft),\n\t\t\t\tthis.transaction.pure.string(key),\n\t\t\t\tthis.transaction.pure.string(value),\n\t\t\t\tthis.transaction.object(SUI_CLOCK_OBJECT_ID),\n\t\t\t],\n\t\t});\n\t}\n\n\t/**\n\t * Burns an expired NFT to collect storage rebates.\n\t */\n\tburnExpired({ nft, isSubname }: { nft: TransactionObjectInput; isSubname?: boolean }) {\n\t\tif (!this.suinsClient.config.suins) throw new Error('SuiNS Object ID not found');\n\n\t\tif (isSubname) {\n\t\t\tthis.transaction.add(\n\t\t\t\tcontroller.burnExpiredSubname({\n\t\t\t\t\tpackage: this.suinsClient.config.packageId,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\tsuins: this.suinsClient.config.suins,\n\t\t\t\t\t\tnft: this.transaction.object(nft),\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t\t} else {\n\t\t\tthis.transaction.add(\n\t\t\t\tcontroller.burnExpired({\n\t\t\t\t\tpackage: this.suinsClient.config.packageId,\n\t\t\t\t\targuments: {\n\t\t\t\t\t\tsuins: this.suinsClient.config.suins,\n\t\t\t\t\t\tnft: this.transaction.object(nft),\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n}\n","export type T2000ErrorCode =\n | 'INSUFFICIENT_BALANCE'\n | 'ADDRESS_BALANCE_UNSPONSORABLE'\n | 'INSUFFICIENT_GAS'\n | 'INVALID_ADDRESS'\n | 'INVALID_AMOUNT'\n | 'WALLET_NOT_FOUND'\n | 'WALLET_LOCKED'\n | 'WALLET_EXISTS'\n | 'WALLET_CORRUPT'\n | 'INVALID_KEY'\n | 'SIMULATION_FAILED'\n | 'TRANSACTION_FAILED'\n | 'ASSET_NOT_SUPPORTED'\n | 'INVALID_ASSET'\n | 'PROTOCOL_UNAVAILABLE'\n | 'RPC_ERROR'\n | 'RPC_UNREACHABLE'\n | 'PRICE_EXCEEDS_LIMIT'\n | 'UNSUPPORTED_NETWORK'\n | 'PAYMENT_EXPIRED'\n | 'DUPLICATE_PAYMENT'\n | 'FACILITATOR_REJECTION'\n | 'CONTACT_NOT_FOUND'\n | 'INVALID_CONTACT_NAME'\n | 'SUINS_NOT_REGISTERED'\n | 'FACILITATOR_TIMEOUT'\n | 'SAFEGUARD_BLOCKED'\n | 'SWAP_NO_ROUTE'\n | 'SWAP_FAILED'\n | 'DIALECT_UNSUPPORTED'\n | 'CHAIN_MODE_INVALID'\n | 'INFERENCE_FAILED'\n | 'UNKNOWN';\n\nexport interface T2000ErrorData {\n reason?: string;\n [key: string]: unknown;\n}\n\nexport class T2000Error extends Error {\n readonly code: T2000ErrorCode;\n readonly data?: T2000ErrorData;\n readonly retryable: boolean;\n\n constructor(code: T2000ErrorCode, message: string, data?: T2000ErrorData, retryable = false) {\n super(message);\n this.name = 'T2000Error';\n this.code = code;\n this.data = data;\n this.retryable = retryable;\n }\n\n toJSON() {\n return {\n error: this.code,\n message: this.message,\n ...(this.data && { data: this.data }),\n retryable: this.retryable,\n };\n }\n}\n\nexport function mapWalletError(error: unknown): T2000Error {\n const msg = error instanceof Error ? error.message : String(error);\n\n if (msg.includes('rejected') || msg.includes('cancelled')) {\n return new T2000Error('TRANSACTION_FAILED', 'Transaction cancelled');\n }\n if (msg.includes('Insufficient') || msg.includes('insufficient')) {\n return new T2000Error('INSUFFICIENT_BALANCE', 'Insufficient balance');\n }\n\n return new T2000Error('UNKNOWN', msg, undefined, true);\n}\n\nexport function mapMoveAbortCode(code: number): string {\n const abortMessages: Record<number, string> = {\n 1: 'Protocol is temporarily paused',\n 2: 'Amount must be greater than zero',\n 3: 'Invalid operation type',\n 4: 'Fee rate exceeds maximum',\n 5: 'Insufficient treasury balance',\n 6: 'Not authorized',\n 7: 'Package version mismatch — upgrade required',\n 8: 'Timelock is active — wait for expiry',\n 9: 'No pending change to execute',\n 10: 'Already at current version',\n // NAVI Protocol abort codes\n 1502: 'Oracle price is stale — try again in a moment',\n 1503: 'Withdrawal amount is invalid (zero or dust) — try a specific amount instead of \"all\"',\n 1600: 'Health factor too low — withdrawal would risk liquidation',\n 1605: 'Asset borrowing is disabled or at capacity on this protocol',\n // NAVI utils abort codes\n 46000: 'Insufficient balance to repay — withdraw some savings first to get cash',\n };\n return abortMessages[code] ?? `Move abort code: ${code}`;\n}\n\n/**\n * Check if an error message contains a MoveAbort — these are on-chain\n * failures that will fail no matter how many times you retry.\n */\nexport function isMoveAbort(msg: string): boolean {\n return msg.includes('MoveAbort') || msg.includes('MovePrimitiveRuntimeError');\n}\n\nexport function parseMoveAbortMessage(msg: string): string {\n const abortMatch = msg.match(/abort code:\\s*(\\d+)/i) ?? msg.match(/MoveAbort[^,]*,\\s*(\\d+)/);\n if (abortMatch) {\n const code = parseInt(abortMatch[1], 10);\n\n const moduleMatch = msg.match(/Identifier\\(\"([^\"]+)\"\\)/) ?? msg.match(/in '([^']+)'/);\n const fnMatch = msg.match(/function_name:\\s*Some\\(\"([^\"]+)\"\\)/);\n const context = `${moduleMatch?.[1] ?? ''}${fnMatch ? `::${fnMatch[1]}` : ''}`.toLowerCase();\n const suffix = moduleMatch\n ? ` [${moduleMatch[1]}${fnMatch ? `::${fnMatch[1]}` : ''}]`\n : '';\n\n if (context.includes('slippage')) {\n return `Slippage too high — price moved during execution${suffix}`;\n }\n if (context.includes('balance::split') || context.includes('balance::ENotEnough')) {\n return `Insufficient on-chain balance${suffix}`;\n }\n\n const mapped = mapMoveAbortCode(code);\n return `${mapped}${suffix}`;\n }\n return msg;\n}\n","// Builder-appropriate safety, layer 2 (SPEC_AUDRIC_V3 §7 / safeguards-defense-\n// in-depth.mdc). `preflight()` is CHEAP, PURE, SYNCHRONOUS input validation —\n// no network, no I/O, no context lookup. It runs BEFORE the LLM round-trip /\n// before the tap-to-confirm card, so a malformed intent is rejected without\n// the user ever seeing a confirm for it.\n//\n// Each write builder co-locates its own `preflight*` validator (send.ts →\n// `preflightSend`, pay.ts → `preflightPay`, cetus-swap.ts → `preflightSwap`).\n// This module owns ONLY the shared result type + the two pure primitives those\n// validators compose (amount sanity + sync address validity). The agent-loop\n// guards that read conversation/session state stay in the v3 HOST (they are\n// NOT builder-appropriate, S.442/S.443).\n\nimport { isValidSuiAddress, normalizeSuiAddress } from '@mysten/sui/utils';\nimport type { T2000ErrorCode } from './errors.js';\n\n/**\n * The result of a synchronous preflight check. `valid: false` carries a\n * `T2000ErrorCode` + human message so the host can surface a precise reason\n * (and the builder can rethrow it as a `T2000Error` verbatim).\n */\nexport type PreflightResult =\n | { valid: true }\n | { valid: false; code: T2000ErrorCode; error: string };\n\n/**\n * Fat-finger / overflow ceiling for an asset amount. NOT a spending policy\n * (that's the `@t2000/sdk/limits` module — USD-denominated, opt-in, stateful);\n * this is the \"obviously wrong number\" guard the safeguards rule prescribes\n * (`amount > 1_000_000` → unreasonable).\n */\nexport const PREFLIGHT_MAX_AMOUNT = 1_000_000;\n\nexport const PREFLIGHT_OK: PreflightResult = { valid: true };\n\nexport function preflightFail(code: T2000ErrorCode, error: string): PreflightResult {\n return { valid: false, code, error };\n}\n\n/**\n * Pure positive-finite-amount sanity check (no network). Rejects NaN/Infinity\n * and non-positive values. The absurd-value ceiling defaults to\n * {@link PREFLIGHT_MAX_AMOUNT} but callers can raise it — pass\n * `max: Number.POSITIVE_INFINITY` for swaps of low-unit-value tokens\n * (memecoins legitimately trade in millions/billions of units), where a fixed\n * display-amount ceiling would be a false positive.\n */\nexport function checkPositiveAmount(\n amount: number,\n label = 'Amount',\n max: number = PREFLIGHT_MAX_AMOUNT,\n): PreflightResult {\n if (typeof amount !== 'number' || !Number.isFinite(amount)) {\n return preflightFail('INVALID_AMOUNT', `${label} must be a finite number`);\n }\n if (amount <= 0) {\n return preflightFail('INVALID_AMOUNT', `${label} must be greater than zero`);\n }\n if (amount > max) {\n return preflightFail('INVALID_AMOUNT', `${label} ${amount} exceeds the sane maximum (${max})`);\n }\n return PREFLIGHT_OK;\n}\n\n/**\n * Pure, synchronous Sui-address validity (no throw, no network) — the\n * non-throwing sibling of `validateAddress`. Use in preflight; use\n * `validateAddress` when you need the normalized form.\n */\nexport function checkSuiAddress(address: string, label = 'recipient'): PreflightResult {\n try {\n // `normalizeSuiAddress('')` pads to the zero address (which is \"valid\"), so\n // guard empty / whitespace-only input before normalizing.\n if (typeof address === 'string' && address.trim() !== '' &&\n isValidSuiAddress(normalizeSuiAddress(address))) {\n return PREFLIGHT_OK;\n }\n } catch {\n // normalizeSuiAddress throws on malformed input → fall through to the fail.\n }\n return preflightFail('INVALID_ADDRESS', `Invalid ${label} address: ${address}`);\n}\n","/**\n * Unified token registry — single source of truth for coin types, decimals,\n * and symbols. ZERO heavy dependencies; safe to import anywhere (server,\n * browser, Edge).\n *\n * Used for swap-by-symbol resolution, amount formatting (decimals), and\n * history/balance display. USDC is the settlement stable (send / receive /\n * x402 pay); everything else is holdable / swappable. There is no curated\n * \"tier\" gate — swaps accept any coin type (Cetus routes); the registry just\n * makes the common tokens ergonomic to reference by symbol.\n *\n * To add a token: add ONE entry to COIN_REGISTRY below — everything derives\n * from it.\n */\n\nexport interface CoinMeta {\n type: string;\n decimals: number;\n symbol: string;\n}\n\n/**\n * Canonical coin registry.\n * Key = user-friendly name (used in swap, CLI, prompts).\n */\nexport const COIN_REGISTRY: Record<string, CoinMeta> = {\n // ── Settlement stable ─────────────────────────────────────────────────\n USDC: { type: '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC', decimals: 6, symbol: 'USDC' },\n\n // ── Common swap assets (symbol ergonomics — any coin type still swaps) ─\n SUI: { type: '0x2::sui::SUI', decimals: 9, symbol: 'SUI' },\n wBTC: { type: '0x0041f9f9344cac094454cd574e333c4fdb132d7bcc9379bcd4aab485b2a63942::wbtc::WBTC', decimals: 8, symbol: 'wBTC' },\n ETH: { type: '0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH', decimals: 8, symbol: 'ETH' },\n GOLD: { type: '0x9d297676e7a4b771ab023291377b2adfaa4938fb9080b8d12430e4b108b836a9::xaum::XAUM', decimals: 9, symbol: 'GOLD' },\n DEEP: { type: '0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP', decimals: 6, symbol: 'DEEP' },\n WAL: { type: '0x356a26eb9e012a68958082340d4c4116e7f55615cf27affcff209cf0ae544f59::wal::WAL', decimals: 9, symbol: 'WAL' },\n NS: { type: '0x5145494a5f5100e645e4b0aa950fa6b68f614e8c59e17bc5ded3495123a79178::ns::NS', decimals: 6, symbol: 'NS' },\n IKA: { type: '0x7262fb2f7a3a14c888c438a3cd9b912469a58cf60f367352c46584262e8299aa::ika::IKA', decimals: 9, symbol: 'IKA' },\n CETUS: { type: '0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS', decimals: 9, symbol: 'CETUS' },\n NAVX: { type: '0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX', decimals: 9, symbol: 'NAVX' },\n vSUI: { type: '0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT', decimals: 9, symbol: 'vSUI' },\n haSUI: { type: '0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI', decimals: 9, symbol: 'haSUI' },\n afSUI: { type: '0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc::afsui::AFSUI', decimals: 9, symbol: 'afSUI' },\n LOFI: { type: '0xf22da9a24ad027cccb5f2d496cbe91de953d363513db08a3a734d361c7c17503::LOFI::LOFI', decimals: 9, symbol: 'LOFI' },\n MANIFEST: { type: '0xc466c28d87b3d5cd34f3d5c088751532d71a38d93a8aae4551dd56272cfb4355::manifest::MANIFEST', decimals: 9, symbol: 'MANIFEST' },\n\n // ── Other stables (display / classification) ──────────────────────────\n USDT: { type: '0x375f70cf2ae4c00bf37117d0c85a2c71545e6ee05c4a5c7d282cd66a4504b068::usdt::USDT', decimals: 6, symbol: 'USDT' },\n USDe: { type: '0x41d587e5336f1c86cad50d38a7136db99333bb9bda91cea4ba69115defeb1402::sui_usde::SUI_USDE', decimals: 6, symbol: 'USDe' },\n USDSUI: { type: '0x44f838219cf67b058f3b37907b655f226153c18e33dfcd0da559a844fea9b1c1::usdsui::USDSUI', decimals: 6, symbol: 'USDsui' },\n};\n\n/** Reverse lookup: coin type → CoinMeta. Built once at import time. */\nconst BY_TYPE = new Map<string, CoinMeta>();\nfor (const meta of Object.values(COIN_REGISTRY)) {\n BY_TYPE.set(meta.type, meta);\n}\n\n// ── Lookup helpers ───────────────────────────────────────────────────────\n\n/**\n * Returns the registry metadata for a coin type, or `undefined` if the coin\n * is not in the registry. Used for canonical-symbol + decimal resolution.\n */\nexport function getCoinMeta(coinType: string): CoinMeta | undefined {\n return BY_TYPE.get(coinType);\n}\n\n/**\n * Returns true if the coin type appears in COIN_REGISTRY. Useful as a\n * canonical-symbol gate — e.g. so the registry's mixed-case `USDsui` wins\n * over a vendor feed's uppercase `USDSUI`.\n */\nexport function isInRegistry(coinType: string): boolean {\n return BY_TYPE.has(coinType);\n}\n\n// ── Lookup helpers ───────────────────────────────────────────────────────\n\n/**\n * Get decimals for any coin type. Checks full type match, then suffix match,\n * then defaults to 9. Works for any token, registered or not.\n */\nexport function getDecimalsForCoinType(coinType: string): number {\n const direct = BY_TYPE.get(coinType);\n if (direct) return direct.decimals;\n\n const suffix = coinType.split('::').slice(1).join('::').toUpperCase();\n if (suffix) {\n for (const meta of BY_TYPE.values()) {\n const metaSuffix = meta.type.split('::').slice(1).join('::').toUpperCase();\n if (metaSuffix === suffix) return meta.decimals;\n }\n }\n\n return 9;\n}\n\n/** Minimal structural client — just the coin-metadata read this needs. */\ninterface CoinMetadataClient {\n core: { getCoinMetadata: (opts: { coinType: string }) => Promise<unknown> };\n}\n\n/**\n * [2.11] Decimals for any coin type, resolved correctly for arbitrary tokens.\n * Registry tokens return their known decimals (no network). A coin type NOT in\n * the registry is read ON-CHAIN via coin metadata — never the 9-default guess,\n * because a wrong `from` decimal would corrupt a swap's input amount\n * (financial-amounts rule). Falls back to the registry heuristic only if the\n * on-chain read fails or returns no usable decimals.\n */\nexport async function resolveCoinDecimals(\n client: CoinMetadataClient,\n coinType: string,\n): Promise<number> {\n if (isInRegistry(coinType)) return getDecimalsForCoinType(coinType);\n try {\n const res = (await client.core.getCoinMetadata({ coinType })) as {\n metadata?: { decimals?: number };\n decimals?: number;\n };\n const d = res?.metadata?.decimals ?? res?.decimals;\n if (typeof d === 'number' && Number.isFinite(d)) return d;\n } catch {\n /* on-chain read failed — fall through to the registry heuristic */\n }\n return getDecimalsForCoinType(coinType);\n}\n\n/**\n * Resolve a full coin type to a user-friendly symbol.\n * Returns the last `::` segment if not in the registry.\n */\nexport function resolveSymbol(coinType: string): string {\n const direct = BY_TYPE.get(coinType);\n if (direct) return direct.symbol;\n\n const suffix = coinType.split('::').slice(1).join('::').toUpperCase();\n if (suffix) {\n for (const meta of BY_TYPE.values()) {\n const metaSuffix = meta.type.split('::').slice(1).join('::').toUpperCase();\n if (metaSuffix === suffix) return meta.symbol;\n }\n }\n\n return coinType.split('::').pop() ?? coinType;\n}\n\n/**\n * Name → type map for swap resolution. Derived from COIN_REGISTRY.\n * Contains BOTH original-case and UPPERCASE keys for case-insensitive lookup.\n */\nexport const TOKEN_MAP: Record<string, string> = (() => {\n const map: Record<string, string> = {};\n for (const [name, meta] of Object.entries(COIN_REGISTRY)) {\n map[name] = meta.type;\n map[name.toUpperCase()] = meta.type;\n }\n return map;\n})();\n\n/**\n * Resolve a user-friendly token name to its full coin type.\n * Returns the input unchanged if already a full coin type (contains \"::\").\n * Case-insensitive: 'usde', 'USDe', 'USDE' all resolve correctly.\n */\nexport function resolveTokenType(nameOrType: string): string | null {\n if (nameOrType.includes('::')) return nameOrType;\n return TOKEN_MAP[nameOrType] ?? TOKEN_MAP[nameOrType.toUpperCase()] ?? null;\n}\n\n/** Common type constants for direct import. */\nexport const SUI_TYPE = COIN_REGISTRY.SUI.type;\nexport const USDC_TYPE = COIN_REGISTRY.USDC.type;\nexport const USDT_TYPE = COIN_REGISTRY.USDT.type;\nexport const USDSUI_TYPE = COIN_REGISTRY.USDSUI.type;\nexport const USDE_TYPE = COIN_REGISTRY.USDe.type;\nexport const ETH_TYPE = COIN_REGISTRY.ETH.type;\nexport const WBTC_TYPE = COIN_REGISTRY.wBTC.type;\nexport const WAL_TYPE = COIN_REGISTRY.WAL.type;\nexport const NAVX_TYPE = COIN_REGISTRY.NAVX.type;\nexport const IKA_TYPE = COIN_REGISTRY.IKA.type;\nexport const LOFI_TYPE = COIN_REGISTRY.LOFI.type;\nexport const MANIFEST_TYPE = COIN_REGISTRY.MANIFEST.type;\n","/**\n * Wallet-side coin selection helpers — single source of truth for the\n * \"produce a `Coin<T>` argument holding `amount` raw units of `coinType`,\n * owned by `address`\" pattern. Used by every wallet-mode appender that\n * needs a coin input (save, send, swap, repay, stake, etc.).\n *\n * **2026-05-22 — address-balance migration.** Sui mainnet's address-balance\n * feature ships funds account-style instead of as discrete `Coin<T>` objects.\n * After a payment via `0x2::balance::send_funds`, the leftover lands in the\n * sender's address balance with a synthetic \"coin reservation\" representing\n * the deposit. `client.getCoins()` correctly filters those reservations out\n * (they aren't real owned objects), so the old fetch+merge+split pattern\n * threw `INSUFFICIENT_BALANCE` for users whose stables had drifted into\n * address balance — even when `getBalance().totalBalance` showed plenty.\n *\n * The fix is structural: hand the work to `coinWithBalance({ type, balance })`\n * from `@mysten/sui/transactions`. Its build-time resolver inspects coins +\n * address balance together (`getBalance` + `listCoins`), then emits the\n * right shape — direct `redeem_funds` from address balance when AB ≥\n * required, or merge-and-split across coins + AB withdrawal when not. Multi\n * intents per coin type get batched into a single merge in one PTB, so the\n * old per-PTB merge cache is no longer needed.\n *\n * Pre-flight uses `client.getBalance().totalBalance` (sums coins + AB)\n * instead of summing the paginated `getCoins` page. That's the OTHER half\n * of the migration — the legacy path could see `0` from `getCoins` and\n * mistakenly throw before `coinWithBalance` ever ran.\n */\nimport {\n Transaction,\n coinWithBalance,\n type TransactionObjectArgument,\n} from '@mysten/sui/transactions';\nimport type { SuiCoreClient } from '../utils/sui.js';\nimport { T2000Error } from '../errors.js';\n\nexport interface CoinPage {\n ids: string[];\n totalBalance: bigint;\n}\n\n/**\n * Sum every coin of `coinType` owned by `owner`, INCLUDING address balance.\n * Returns the IDs of any discrete coin objects that exist (callers\n * occasionally need this for non-`coinWithBalance` paths, e.g. SUIns name\n * registration which expects raw object IDs).\n *\n * Pre-2026-05-22 this function paginated `client.getCoins` and summed\n * the page balances. That misses address-balance funds (the SDK filters\n * them out of `getCoins` for back-compat). The new implementation calls\n * `getBalance` for the canonical total and `getCoins` for the optional\n * ID list — both round-trips, but they happen in parallel.\n */\nexport async function fetchAllCoins(\n client: SuiCoreClient,\n owner: string,\n coinType: string,\n): Promise<CoinPage> {\n const [balance, ids] = await Promise.all([\n client.core.getBalance({ owner, coinType }),\n (async () => {\n const out: string[] = [];\n let cursor: string | null | undefined;\n let hasNext = true;\n while (hasNext) {\n const page = await client.core.listCoins({ owner, coinType, cursor: cursor ?? undefined });\n for (const c of page.objects) out.push(c.objectId);\n cursor = page.cursor;\n hasNext = page.hasNextPage;\n }\n return out;\n })(),\n ]);\n return { ids, totalBalance: BigInt(balance.balance.balance) };\n}\n\nexport interface SelectAndSplitResult {\n /** TransactionObjectArgument for a coin holding `effectiveAmount` raw units. */\n coin: TransactionObjectArgument;\n /** Actual raw amount the returned coin holds. May be < requested if `swapAll` is true. */\n effectiveAmount: bigint;\n /** True iff the request consumed the entire wallet balance (no split needed). */\n swapAll: boolean;\n}\n\n/**\n * Wallet-mode coin selection prelude. Pre-flights against\n * `getBalance().totalBalance` (coins + address balance combined), then\n * returns a `coinWithBalance({ type, balance })` argument that the\n * `@mysten/sui` resolver fulfills at build time.\n *\n * Throws `T2000Error` (`INSUFFICIENT_BALANCE`) when:\n * - `amount` is bigger than the total balance AND the caller did NOT\n * opt into `swapAll: true` clipping.\n * - `amount === 'all'` AND total balance is zero.\n *\n * @param tx — PTB to register the `coinWithBalance` intent against.\n * @param client — Sui RPC client for the pre-flight `getBalance` lookup.\n * @param owner — wallet address whose coins to source from.\n * @param coinType — fully-qualified Sui coin type (e.g. `\"0x...::usdc::USDC\"`).\n * @param amount — raw amount to source (in MIST / smallest unit). Pass\n * `'all'` to consume the entire balance.\n * @param options.allowSwapAll — if true (default), `amount` >= totalBalance\n * auto-clips to total. If false, throws when the request would over-consume.\n * @param options.sponsoredContext — when true, source ONLY from discrete coin\n * objects (never the address balance). See the long note below — this exists\n * because Enoki's gas station can't yet deserialize a `TransactionData` that\n * contains the address-balance `FundsWithdrawal` reservation that\n * `coinWithBalance` emits. Self-funded callers leave this false: the fullnode\n * handles `FundsWithdrawal` fine, so the address-balance path is preferred\n * (it can reach funds that aren't held as coin objects).\n *\n * @returns\n * - `coin` — `TransactionObjectArgument` ready for downstream consumption.\n * - `effectiveAmount` — the raw amount the returned coin holds (handles\n * swapAll clipping).\n * - `swapAll` — true iff the entire balance was consumed.\n */\nexport async function selectAndSplitCoin(\n tx: Transaction,\n client: SuiCoreClient,\n owner: string,\n coinType: string,\n amount: bigint | 'all',\n options: {\n allowSwapAll?: boolean;\n sponsoredContext?: boolean;\n mergeCache?: SponsoredCoinMergeCache;\n } = {},\n): Promise<SelectAndSplitResult> {\n // [2026-05-30] Sponsored Enoki path — coin objects only. `coinWithBalance`\n // reaches into the address balance (mysten Address Balances feature) when\n // `addressBalance >= required`, emitting `0x2::coin::redeem_funds` + a\n // `FundsWithdrawal` reservation input. That input is a newer `TransactionData`\n // field; Enoki's sponsor endpoint accepts the kind bytes (200) but its gas\n // station rejects the assembled `TransactionData` at execute with\n // \"Invalid bcs bytes for TransactionData\". The fullnode parses it fine — only\n // Enoki can't (yet). So under sponsorship we source from discrete coin objects\n // and surface a clear error when the user's funds are address-balance-only.\n // See github.com/mission69b/t2000 issue #93.\n if (options.sponsoredContext) {\n return selectCoinObjectsOnly(\n tx,\n client,\n owner,\n coinType,\n amount,\n options.allowSwapAll ?? true,\n options.mergeCache,\n );\n }\n\n const balanceResp = await client.core.getBalance({ owner, coinType });\n const totalBalance = BigInt(balanceResp.balance.balance);\n\n if (totalBalance === 0n) {\n throw new T2000Error('INSUFFICIENT_BALANCE', `No balance found for ${coinType}`);\n }\n\n const allowSwapAll = options.allowSwapAll ?? true;\n\n if (amount !== 'all' && amount > totalBalance && !allowSwapAll) {\n throw new T2000Error('INSUFFICIENT_BALANCE', `Insufficient balance for ${coinType}`, {\n available: totalBalance.toString(),\n required: amount.toString(),\n });\n }\n\n const requested = amount === 'all' ? totalBalance : amount;\n const swapAll = amount === 'all' || requested >= totalBalance;\n const effectiveAmount = swapAll ? totalBalance : requested;\n\n const coin = coinWithBalance({ type: coinType, balance: effectiveAmount })(tx);\n\n return { coin, effectiveAmount, swapAll };\n}\n\n/**\n * Coin-object-only selection for sponsored (Enoki) transactions. Fetches the\n * owner's discrete `Coin<T>` objects (NOT the address balance — `getCoins`\n * excludes it), merges them, and splits the requested amount. Never emits a\n * `FundsWithdrawal` reservation, so the resulting `TransactionData` stays on\n * the shape Enoki's gas station can serialize.\n *\n * Throws `ADDRESS_BALANCE_UNSPONSORABLE` when the coin objects don't cover the\n * request — which, for a user whose `getBalance().totalBalance` shows funds,\n * means those funds live in the address balance (e.g. received via a gasless\n * stablecoin transfer) and can't be moved through a sponsored transaction yet.\n */\n/**\n * Per-PTB cache of merged sponsored coin-object primaries, keyed by coin\n * type. The FIRST `selectCoinObjectsOnly` call for a given coin type in a\n * PTB fetches the owner's discrete `Coin<T>` objects, merges them into one\n * `primary`, and records it here alongside the remaining (unspent) balance.\n * EVERY subsequent leg sourcing the same coin type splits from that cached\n * `primary` instead of re-fetching + re-merging.\n *\n * Why this exists (S.xxx, 2026-06-02): a sponsored bundle with 2+ legs\n * sourcing the same coin (e.g. `SUI→WAL` + `SUI→DEEP`, or `swap USDC` +\n * `save USDC`) called `selectCoinObjectsOnly` once per leg. Each call\n * emitted its own `mergeCoins` over the SAME coin objects, so the second\n * leg's merge referenced coins the first leg already consumed → Enoki\n * dry-run failed with `CommandArgumentError { ArgumentWithoutValue }`.\n *\n * This is NOT SUI-specific. Under sponsorship, `selectAndSplitCoin` routes\n * EVERY asset through `selectCoinObjectsOnly` (the `coinWithBalance`\n * batching that would otherwise dedup these merges only runs for\n * non-sponsored CLI/direct flows — its address-balance `FundsWithdrawal`\n * reservation is what Enoki can't deserialize, issue #93). So the cache is\n * the dedup layer for ALL coin types in a sponsored multi-leg PTB, keyed\n * by coin type. SUI was simply the first asset observed failing in the\n * wild because it's the most common swap source.\n */\nexport type SponsoredCoinMergeCache = Map<\n string,\n { primary: TransactionObjectArgument; remaining: bigint }\n>;\n\nasync function selectCoinObjectsOnly(\n tx: Transaction,\n client: SuiCoreClient,\n owner: string,\n coinType: string,\n amount: bigint | 'all',\n allowSwapAll: boolean,\n mergeCache?: SponsoredCoinMergeCache,\n): Promise<SelectAndSplitResult> {\n // Cache hit — a prior leg in THIS PTB already merged this coin type's\n // objects into `cached.primary`. Re-running the fetch+merge below would\n // emit a second `mergeCoins` over already-consumed coins → dry-run\n // `ArgumentWithoutValue`. Split from the cached primary instead.\n const cached = mergeCache?.get(coinType);\n if (cached) {\n const requested = amount === 'all' ? cached.remaining : amount;\n if (cached.remaining === 0n || requested > cached.remaining) {\n throw new T2000Error(\n 'ADDRESS_BALANCE_UNSPONSORABLE',\n `Not enough ${coinType} in coin objects to cover all legs of this ` +\n `sponsored bundle. The remaining funds are in your address balance, ` +\n `which sponsored transactions can't access yet.`,\n { remaining: cached.remaining.toString(), requested: requested.toString(), coinType },\n );\n }\n const swapAll = amount === 'all' || requested >= cached.remaining;\n const effectiveAmount = swapAll ? cached.remaining : requested;\n const coin = swapAll\n ? cached.primary\n : tx.splitCoins(cached.primary, [effectiveAmount])[0];\n cached.remaining -= effectiveAmount;\n return { coin, effectiveAmount, swapAll };\n }\n\n const objects: { objectId: string; balance: bigint }[] = [];\n let coinObjectTotal = 0n;\n let cursor: string | null | undefined;\n let hasNext = true;\n while (hasNext) {\n const page = await client.core.listCoins({ owner, coinType, cursor: cursor ?? undefined });\n for (const c of page.objects) {\n objects.push({ objectId: c.objectId, balance: BigInt(c.balance) });\n coinObjectTotal += BigInt(c.balance);\n }\n cursor = page.cursor;\n hasNext = page.hasNextPage;\n }\n\n const unsponsorable = (): T2000Error =>\n new T2000Error(\n 'ADDRESS_BALANCE_UNSPONSORABLE',\n `These funds are in your address balance, which sponsored transactions ` +\n `can't access yet. (Funds received via gasless transfers land there.) ` +\n `This will work once the gas sponsor adds address-balance support.`,\n { coinObjectTotal: coinObjectTotal.toString(), coinType },\n );\n\n if (coinObjectTotal === 0n) {\n throw unsponsorable();\n }\n\n const requested = amount === 'all' ? coinObjectTotal : amount;\n if (requested > coinObjectTotal) {\n // Not enough in coin objects. If the caller allows clipping to the\n // available coin-object total (\"swap all\"), do so; otherwise the shortfall\n // is sitting in the address balance → unsponsorable.\n if (allowSwapAll && amount === 'all') {\n // unreachable (requested === coinObjectTotal here) — kept for clarity.\n } else {\n throw unsponsorable();\n }\n }\n\n const swapAll = amount === 'all' || requested >= coinObjectTotal;\n const effectiveAmount = swapAll ? coinObjectTotal : requested;\n\n const [first, ...rest] = objects;\n const primary = tx.object(first.objectId);\n if (rest.length > 0) {\n tx.mergeCoins(\n primary,\n rest.map((o) => tx.object(o.objectId)),\n );\n }\n\n // Consume the whole merged coin when taking everything; otherwise split the\n // exact amount and leave the remainder on the (sender-owned) primary coin.\n const coin = swapAll ? primary : tx.splitCoins(primary, [effectiveAmount])[0];\n\n // Record the merged primary so later legs in the same PTB reuse it\n // rather than re-fetching + re-merging the same (now-consumed) coins.\n // When `swapAll`, the primary was consumed (remaining 0) — a later leg\n // hitting the cache then throws the unsponsorable shortfall above.\n mergeCache?.set(coinType, {\n primary,\n remaining: coinObjectTotal - effectiveAmount,\n });\n\n return { coin, effectiveAmount, swapAll };\n}\n\n/**\n * Build a GASLESS coin→address-balance migration.\n *\n * Sends WHOLE `Coin<T>` objects to `owner`'s OWN SIP-58 address balance via\n * `0x2::coin::send_funds(coin, owner)` — one allowlisted framework MoveCall\n * per coin, with NO native `SplitCoins` / `MergeCoins` commands. That shape is\n * what makes it gasless: the gRPC build resolver only zeros gas for PTBs whose\n * every command is a MoveCall into the `0x2` gasless allowlist (`send_funds` /\n * `redeem_funds` / `withdrawal_split` / `into_balance`). The same eligibility\n * the gasless `balance::send_funds` send + the x402 `redeem_funds`+`send_funds`\n * withdrawal rely on. (The old migration merged+split first → native commands →\n * fell outside the allowlist → needed SUI. See `pay.ts ensureAddressBalanceCovers`.)\n *\n * Selects the FEWEST coins (largest first) whose combined balance covers\n * `minAmount`, minimizing the MoveCall count. Over-migration is harmless — the\n * surplus just lands in the address balance. Pure / network-free: callers pass\n * coins they've already fetched, so this is unit-testable offline.\n *\n * Throws `INSUFFICIENT_BALANCE` when the supplied coin objects can't cover\n * `minAmount`.\n */\nexport function buildCoinToAddressBalanceMigration(args: {\n coins: { objectId: string; balance: bigint }[];\n coinType: string;\n owner: string;\n minAmount: bigint;\n}): { tx: Transaction; migratedRaw: bigint } {\n const { coins, coinType, owner, minAmount } = args;\n\n // Largest first → fewest whole-coin sends to cover the shortfall.\n const sorted = [...coins]\n .filter((c) => c.balance > 0n)\n .sort((a, b) => (b.balance > a.balance ? 1 : b.balance < a.balance ? -1 : 0));\n\n const selected: { objectId: string; balance: bigint }[] = [];\n let migratedRaw = 0n;\n for (const c of sorted) {\n if (migratedRaw >= minAmount) break;\n selected.push(c);\n migratedRaw += c.balance;\n }\n\n if (migratedRaw < minAmount) {\n throw new T2000Error('INSUFFICIENT_BALANCE', `Insufficient ${coinType} coin objects to migrate`, {\n available: migratedRaw.toString(),\n required: minAmount.toString(),\n });\n }\n\n const tx = new Transaction();\n for (const c of selected) {\n tx.moveCall({\n target: '0x2::coin::send_funds',\n typeArguments: [coinType],\n arguments: [tx.object(c.objectId), tx.pure.address(owner)],\n });\n }\n return { tx, migratedRaw };\n}\n\n/**\n * SUI-specific coin selection. Branches on sponsorship context:\n *\n * - **Self-funded (`sponsoredContext: false`)** — splits from `tx.gas`\n * directly (the user's gas coin IS their SUI). More efficient — no\n * `getBalance` RTT.\n *\n * - **Sponsored (`sponsoredContext: true`)** — sources from the user's\n * discrete SUI coin objects (`selectCoinObjectsOnly`). This both (a) avoids\n * `tx.gas`, which belongs to the Enoki sponsor — NOT the user — under\n * sponsored flows (the original S.260 reason for `useGasCoin: false`), AND\n * (b) avoids `coinWithBalance`'s address-balance `FundsWithdrawal`, which\n * Enoki's gas station can't deserialize (issue #93). If the user's SUI is\n * address-balance-only, it raises `ADDRESS_BALANCE_UNSPONSORABLE`.\n */\nexport async function selectSuiCoin(\n tx: Transaction,\n client: SuiCoreClient,\n owner: string,\n amountMist: bigint,\n sponsoredContext: boolean,\n mergeCache?: SponsoredCoinMergeCache,\n): Promise<SelectAndSplitResult> {\n if (sponsoredContext) {\n const { SUI_TYPE } = await import('../token-registry.js');\n return selectCoinObjectsOnly(tx, client, owner, SUI_TYPE, amountMist, false, mergeCache);\n }\n\n const [coin] = tx.splitCoins(tx.gas, [amountMist]);\n return { coin, effectiveAmount: amountMist, swapAll: false };\n}\n","/**\n * Cetus Aggregator V3 SDK wrapper — the ONLY file that imports @cetusprotocol/aggregator-sdk.\n * Documented CLAUDE.md exception: multi-DEX routing cannot be feasibly replaced by thin tx builders.\n *\n * [B5 v2 / @t2000/sdk@1.1.0 / 2026-04-30]\n * Overlay fee config is now per-call instead of a module-level singleton. CLI / direct\n * SDK callers (`T2000.swap()`) DON'T pass `overlayFee` → fee-free swap. Audric's\n * prepare/route.ts ALWAYS passes `overlayFee = { rate: OVERLAY_FEE_RATE, receiver:\n * T2000_OVERLAY_FEE_WALLET }` → fee charged. Structural inclusion (Audric's code can't\n * forget to pass it because it IS the code), not a toggle that defaults to safe.\n *\n * Pre-1.1.0: a module-level `OVERLAY_FEE_RECEIVER` constant defaulted to a Move object\n * ID. USDC sent there became OwnedObjects keyed to the object and was inaccessible.\n * Fixed by making the receiver a regular wallet address (T2000_OVERLAY_FEE_WALLET) AND\n * by removing the singleton pattern that hid the misconfig.\n */\nimport { AggregatorClient, Env, type FindRouterParams, type RouterDataV3 } from '@cetusprotocol/aggregator-sdk';\nimport { Transaction, type TransactionObjectArgument } from '@mysten/sui/transactions';\nimport BN from 'bn.js';\nimport { resolveTokenType, getDecimalsForCoinType } from '../token-registry.js';\nimport type { SuiCoreClient } from '../utils/sui.js';\nimport type { SponsoredCoinMergeCache } from '../wallet/coinSelection.js';\nimport {\n type PreflightResult,\n PREFLIGHT_OK,\n preflightFail,\n checkPositiveAmount,\n} from '../preflight.js';\n\n/**\n * Synchronous, network-free preflight for `swap`. Validates the from/to token\n * args + amount sanity, and rejects an identity swap — the cheap checks the\n * host runs before routing. Returns a `PreflightResult`; never throws.\n * Route-finding, liquidity, slippage + decimals resolution stay in the async\n * path (`findSwapRoute`/`buildSwapTx`/`getSwapQuote`).\n *\n * v3 drops the swap *tool*, but `swap` survives as an SDK/CLI builder (§8) so\n * it gets the same builder-appropriate preflight as send/pay.\n */\nexport function preflightSwap(input: {\n from: string;\n to: string;\n amount: number;\n}): PreflightResult {\n if (typeof input.from !== 'string' || input.from.trim() === '') {\n return preflightFail('INVALID_ASSET', 'A `from` token is required to swap');\n }\n if (typeof input.to !== 'string' || input.to.trim() === '') {\n return preflightFail('INVALID_ASSET', 'A `to` token is required to swap');\n }\n\n // No upper ceiling — swaps route arbitrary tokens, and low-unit-value tokens\n // legitimately trade in millions/billions of units.\n const amountCheck = checkPositiveAmount(input.amount, 'Amount', Number.POSITIVE_INFINITY);\n if (!amountCheck.valid) return amountCheck;\n\n // Identity swap is a no-op the router can't route — catch it cheaply.\n // Resolve symbol → coin type so \"USDC\" and the USDC coin type compare equal.\n // Guard the null===null case (two unknown symbols both resolve to null) by\n // also requiring the resolved value to be non-null, falling back to a raw\n // string compare.\n const resolvedFrom = resolveTokenType(input.from);\n const resolvedTo = resolveTokenType(input.to);\n const sameToken =\n input.from.trim() === input.to.trim() ||\n (resolvedFrom !== null && resolvedFrom === resolvedTo);\n if (sameToken) {\n return preflightFail('INVALID_ASSET', `Cannot swap ${input.from} to itself`);\n }\n\n return PREFLIGHT_OK;\n}\n\nexport interface OverlayFeeConfig {\n /** Fee rate as a fraction (e.g. 0.001 = 0.1%). Pass 0 to disable. */\n rate: number;\n /** Wallet address that receives the overlay fee. */\n receiver: string;\n}\n\nexport interface SwapRouteResult {\n routerData: RouterDataV3;\n amountIn: string;\n amountOut: string;\n byAmountIn: boolean;\n priceImpact: number;\n insufficientLiquidity: boolean;\n}\n\n// [SPEC 20.2 / D-1 (a)] Typed JSON-friendly representation of a Cetus\n// `RouterDataV3` for cross-process / cross-network transport. The native\n// shape contains `BN` instances (`bn.js`) and a `Map<string, string>`\n// (`packages`) that don't survive JSON.stringify / JSON.parse cleanly:\n// - `BN.toJSON()` returns the internal `{negative,words,length,red}` blob\n// - `Map.toJSON()` returns `{}`\n// Round-tripping via `serializeCetusRoute` + `deserializeCetusRoute`\n// converts BN ↔ decimal string and Map ↔ Record. Engine + audric both\n// reference fields by path (`route.routerData.paths[i].provider`) without\n// needing to know about the underlying BN/Map types.\nexport interface SerializedCetusRoutePath {\n id: string;\n direction: boolean;\n provider: string;\n from: string;\n target: string;\n feeRate: number;\n amountIn: string;\n amountOut: string;\n version?: string;\n publishedAt?: string;\n extendedDetails?: Record<string, unknown>;\n}\n\nexport interface SerializedRouterDataV3 {\n quoteID?: string;\n /** RouterDataV3.amountIn (BN) → decimal string */\n amountIn: string;\n /** RouterDataV3.amountOut (BN) → decimal string */\n amountOut: string;\n byAmountIn: boolean;\n paths: SerializedCetusRoutePath[];\n insufficientLiquidity: boolean;\n deviationRatio: number;\n /** RouterDataV3.packages (Map) → Record */\n packages?: Record<string, string>;\n totalDeepFee?: number;\n error?: { code: number; msg: string };\n overlayFee?: number;\n}\n\nexport interface SerializedCetusRoute {\n routerData: SerializedRouterDataV3;\n amountIn: string;\n amountOut: string;\n byAmountIn: boolean;\n priceImpact: number;\n insufficientLiquidity: boolean;\n /**\n * Wall-clock timestamp (ms since epoch) at which the route was discovered.\n * Used by audric's prepare-route for SPEC 20.2 D-3 TTL re-validation: if\n * the route is older than the threshold AND price impact has shifted\n * beyond tolerance, fall back to a fresh `findSwapRoute()` call.\n */\n discoveredAt: number;\n /**\n * Snapshot of the input/output coin types the route was discovered for.\n * SPEC 20.2 D-2 (b) structural verification: prepare-route asserts\n * input/output coins match before using the fast-path; mismatch falls\n * back to fresh discovery (defense against client-side tampering and\n * against legitimate token-type drift in the request).\n */\n fromCoinType: string;\n toCoinType: string;\n}\n\nexport function serializeCetusRoute(\n route: SwapRouteResult,\n context: { fromCoinType: string; toCoinType: string },\n): SerializedCetusRoute {\n return {\n routerData: serializeRouterDataV3(route.routerData),\n amountIn: route.amountIn,\n amountOut: route.amountOut,\n byAmountIn: route.byAmountIn,\n priceImpact: route.priceImpact,\n insufficientLiquidity: route.insufficientLiquidity,\n discoveredAt: Date.now(),\n fromCoinType: context.fromCoinType,\n toCoinType: context.toCoinType,\n };\n}\n\nexport function deserializeCetusRoute(serialized: SerializedCetusRoute): SwapRouteResult {\n return {\n routerData: deserializeRouterDataV3(serialized.routerData),\n amountIn: serialized.amountIn,\n amountOut: serialized.amountOut,\n byAmountIn: serialized.byAmountIn,\n priceImpact: serialized.priceImpact,\n insufficientLiquidity: serialized.insufficientLiquidity,\n };\n}\n\nfunction serializeRouterDataV3(rd: RouterDataV3): SerializedRouterDataV3 {\n const out: SerializedRouterDataV3 = {\n amountIn: rd.amountIn.toString(),\n amountOut: rd.amountOut.toString(),\n byAmountIn: rd.byAmountIn,\n paths: rd.paths.map(serializeCetusRoutePath),\n insufficientLiquidity: rd.insufficientLiquidity,\n deviationRatio: rd.deviationRatio,\n };\n if (rd.quoteID !== undefined) out.quoteID = rd.quoteID;\n if (rd.packages) {\n const obj: Record<string, string> = {};\n for (const [k, v] of rd.packages) obj[k] = v;\n out.packages = obj;\n }\n if (rd.totalDeepFee !== undefined) out.totalDeepFee = rd.totalDeepFee;\n if (rd.error) out.error = { code: rd.error.code, msg: rd.error.msg };\n if (rd.overlayFee !== undefined) out.overlayFee = rd.overlayFee;\n return out;\n}\n\nfunction deserializeRouterDataV3(s: SerializedRouterDataV3): RouterDataV3 {\n const out: RouterDataV3 = {\n amountIn: new BN(s.amountIn),\n amountOut: new BN(s.amountOut),\n byAmountIn: s.byAmountIn,\n paths: s.paths.map(deserializeCetusRoutePath),\n insufficientLiquidity: s.insufficientLiquidity,\n deviationRatio: s.deviationRatio,\n };\n if (s.quoteID !== undefined) out.quoteID = s.quoteID;\n if (s.packages) out.packages = new Map(Object.entries(s.packages));\n if (s.totalDeepFee !== undefined) out.totalDeepFee = s.totalDeepFee;\n if (s.error) out.error = { code: s.error.code, msg: s.error.msg };\n if (s.overlayFee !== undefined) out.overlayFee = s.overlayFee;\n return out;\n}\n\nfunction serializeCetusRoutePath(p: RouterDataV3['paths'][number]): SerializedCetusRoutePath {\n const out: SerializedCetusRoutePath = {\n id: p.id,\n direction: p.direction,\n provider: p.provider,\n from: p.from,\n target: p.target,\n feeRate: p.feeRate,\n amountIn: p.amountIn,\n amountOut: p.amountOut,\n };\n if (p.version !== undefined) out.version = p.version;\n if (p.publishedAt !== undefined) out.publishedAt = p.publishedAt;\n if (p.extendedDetails) out.extendedDetails = { ...p.extendedDetails };\n return out;\n}\n\nfunction deserializeCetusRoutePath(p: SerializedCetusRoutePath): RouterDataV3['paths'][number] {\n const out: RouterDataV3['paths'][number] = {\n id: p.id,\n direction: p.direction,\n provider: p.provider,\n from: p.from,\n target: p.target,\n feeRate: p.feeRate,\n amountIn: p.amountIn,\n amountOut: p.amountOut,\n };\n if (p.version !== undefined) out.version = p.version;\n if (p.publishedAt !== undefined) out.publishedAt = p.publishedAt;\n if (p.extendedDetails) out.extendedDetails = { ...p.extendedDetails };\n return out;\n}\n\n/**\n * SPEC 20.2 D-2 (b) structural verification helper. Returns true when the\n * serialized route matches the requested coin types (i.e. it's safe to use\n * as the prepare-route fast-path), false otherwise (tampered, or input\n * mismatch from a legitimate but stale pending action). Caller falls back\n * to a fresh `findSwapRoute()` call when verification fails.\n */\nexport function verifyCetusRouteCoinMatch(\n serialized: SerializedCetusRoute,\n expected: { fromCoinType: string; toCoinType: string },\n): boolean {\n return serialized.fromCoinType === expected.fromCoinType && serialized.toCoinType === expected.toCoinType;\n}\n\n/**\n * SPEC 20.2 D-3 (b) TTL helper. Returns true when the serialized route is\n * fresh enough to use as the fast-path (< `maxAgeMs` old). Returns false\n * for stale routes — caller falls back to fresh `findSwapRoute()` to pick\n * up any pool-price drift since route discovery.\n *\n * Default 30s aligns with the existing quote-freshness contract surfaced\n * to users via `pending_action.quoteAge` (the PermissionCard \"QUOTE Ns OLD\"\n * badge starts warning the user past 30s).\n */\nexport function isCetusRouteFresh(serialized: SerializedCetusRoute, maxAgeMs: number = 30_000): boolean {\n return Date.now() - serialized.discoveredAt < maxAgeMs;\n}\n\n/**\n * Default Audric swap overlay fee — 0.1%. Exported for consumers that want to use\n * the canonical Audric rate (the Audric prepare-route does this). Changing this\n * rate requires a coordinated SDK + audric release.\n */\nexport const OVERLAY_FEE_RATE = 0.001;\n\n/**\n * Cache `AggregatorClient` instances by `(signer + overlay rate + overlay receiver)`.\n * Per-call instantiation is cheap (the client is mostly config), but caching avoids\n * pointless re-allocation when the same caller swaps multiple times in a loop.\n */\nconst clientCache = new Map<string, AggregatorClient>();\n\nfunction getClient(walletAddress: string, overlayFee?: OverlayFeeConfig): AggregatorClient {\n const rate = overlayFee?.rate ?? 0;\n const receiver = overlayFee?.receiver ?? '';\n const key = `${walletAddress}|${rate}|${receiver}`;\n\n const cached = clientCache.get(key);\n if (cached) return cached;\n\n const client = new AggregatorClient({\n signer: walletAddress,\n env: Env.Mainnet,\n ...(rate > 0 && receiver\n ? { overlayFeeRate: rate, overlayFeeReceiver: receiver }\n : {}),\n });\n clientCache.set(key, client);\n return client;\n}\n\n/**\n * [Bug A defense-in-depth / 2026-05-10] Returns true when every path\n * provider in `route.routerData.paths` is present in the active\n * `providers` allow-list. Cetus's `getProvidersExcluding(...)` returns\n * an inclusion list (the complement of the exclusion), so when a caller\n * passes `providers`, every walked provider must be IN that list to be\n * compatible.\n *\n * When `providers` is undefined (non-sponsored caller, e.g. CLI) every\n * route is compatible — same semantics as `findSwapRoute` itself.\n *\n * Why per-path: a Cetus aggregator route can split across multiple DEXes\n * (e.g. 60% Cetus + 40% Bluefin). A single excluded provider in any path\n * triggers `tx.gas` usage in `routerSwap`. Reject the whole route if any\n * leg is excluded.\n */\nexport function isPrecomputedRouteCompatibleWithProviders(\n route: SwapRouteResult,\n providers: string[] | undefined,\n): boolean {\n if (!providers || providers.length === 0) return true;\n const allowed = new Set(providers);\n for (const path of route.routerData.paths) {\n if (!allowed.has(path.provider)) return false;\n }\n return true;\n}\n\n/**\n * Find the optimal swap route via Cetus Aggregator REST API.\n *\n * Pass `overlayFee` to charge an overlay fee on the output (Audric's pattern).\n * Omit it for a fee-free swap (CLI / direct SDK pattern).\n */\nexport async function findSwapRoute(params: {\n walletAddress: string;\n from: string;\n to: string;\n amount: bigint;\n byAmountIn: boolean;\n overlayFee?: OverlayFeeConfig;\n /**\n * Optional Cetus provider allow-list. When omitted, all 30+ DEXes\n * are eligible. Sponsored flows (Enoki) MUST pass an exclusion list\n * computed via `getProvidersExcluding([...])` from the Cetus SDK to\n * remove Pyth-dependent providers (HAEDALPMM, METASTABLE, OBRIC,\n * STEAMM_OMM, STEAMM_OMM_V2, SEVENK, HAEDALHMMV2) — those reference\n * `tx.gas` for oracle fees, which Enoki rejects in sponsored txs.\n * Non-sponsored callers (CLI, direct SDK) leave this undefined.\n */\n providers?: string[];\n}): Promise<SwapRouteResult | null> {\n const client = getClient(params.walletAddress, params.overlayFee);\n\n const findParams: FindRouterParams = {\n from: params.from,\n target: params.to,\n amount: params.amount.toString(),\n byAmountIn: params.byAmountIn,\n ...(params.providers ? { providers: params.providers } : {}),\n };\n\n const routerData = await client.findRouters(findParams);\n if (!routerData) return null;\n\n if (routerData.insufficientLiquidity) {\n return {\n routerData,\n amountIn: routerData.amountIn.toString(),\n amountOut: routerData.amountOut.toString(),\n byAmountIn: params.byAmountIn,\n priceImpact: normalizePriceImpact(routerData.deviationRatio),\n insufficientLiquidity: true,\n };\n }\n\n if (routerData.error) {\n const { T2000Error } = await import('../errors.js');\n throw new T2000Error('SWAP_FAILED', `Cetus routing error: ${routerData.error.msg} (code ${routerData.error.code})`);\n }\n\n return {\n routerData,\n amountIn: routerData.amountIn.toString(),\n amountOut: routerData.amountOut.toString(),\n byAmountIn: params.byAmountIn,\n priceImpact: normalizePriceImpact(routerData.deviationRatio),\n insufficientLiquidity: false,\n };\n}\n\n/**\n * Cetus' aggregator types `deviationRatio` as `number`, but in some routes\n * the router actually returns a string (\"0.001234\"). The SDK type lies, so we\n * always coerce to a finite number here (NaN/null/undefined → 0). Without\n * this every downstream consumer that calls `priceImpact.toFixed(...)` will\n * crash at runtime — including the Audric SwapQuoteCard, which takes the\n * whole chat UI down through its error boundary.\n */\nfunction normalizePriceImpact(value: unknown): number {\n const n = typeof value === 'number' ? value : Number(value);\n return Number.isFinite(n) ? n : 0;\n}\n\n/**\n * Build a swap PTB from a route result. The caller must provide an input coin\n * obtained by splitting/merging wallet coins.\n *\n * **Important:** Cetus's `routerSwap` reads the overlay-fee config from the\n * AggregatorClient instance. The `overlayFee` param here MUST match the one\n * passed to `findSwapRoute` for the same swap (otherwise you'll hit the cache\n * boundary and get a different client with different overlay config).\n */\nexport async function buildSwapTx(params: {\n walletAddress: string;\n route: SwapRouteResult;\n tx: Transaction;\n inputCoin: TransactionObjectArgument;\n slippage: number;\n overlayFee?: OverlayFeeConfig;\n}): Promise<TransactionObjectArgument> {\n const client = getClient(params.walletAddress, params.overlayFee);\n const clampedSlippage = Math.max(0.001, Math.min(params.slippage, 0.05));\n\n const outputCoin = await client.routerSwap({\n router: params.route.routerData,\n inputCoin: params.inputCoin,\n slippage: clampedSlippage,\n txb: params.tx,\n });\n\n return outputCoin;\n}\n\n/**\n * Append a swap fragment to an existing PTB. SPEC 7 § \"Layer 1\" Cetus\n * appender. Two modes, dispatched by the presence of `input.inputCoin`:\n *\n * - **Wallet mode** (`inputCoin` omitted) — sources `from`-asset funds\n * via `coinWithBalance({ type, balance })` (resolves coin objects +\n * address balance at build time), runs the swap. Mirrors the audric\n * host's `transactions/prepare/route.ts` swap branch (P2.2c will\n * retire that branch in favor of this appender via `composeTx`).\n *\n * - **Chain mode** (`inputCoin` provided) — consumes the passed-in coin\n * reference (typically produced by an upstream appender like\n * `addWithdrawToTx`) directly, no wallet fetch / no merge / no\n * split. This is the SPEC 7 multi-write enabler (\"withdraw → swap →\n * save\" without intermediate wallet materialization).\n *\n * **SUI in wallet mode:** ALWAYS sources through `selectSuiCoin` (which\n * routes via `coinWithBalance({ type: SUI, useGasCoin: false })` under\n * sponsored flows, OR `tx.splitCoins(tx.gas, ...)` under self-funded\n * flows). The caller MUST set `sponsoredContext` correctly — otherwise\n * sponsored swaps with SUI source fail with `Cannot use GasCoin as a\n * transaction argument` (Enoki owns `tx.gas`, the PTB body referencing\n * it as an argument is invalid for sponsorship). 2.14.0 shipped without\n * this branch and broke audric/web-v2 SUI→USDC swaps; restored in 2.14.1\n * (S.260). For non-sponsored flows (CLI), `T2000.swap()` pre-builds the\n * inputCoin via `tx.splitCoins(tx.gas, [rawAmount])[0]` and uses chain\n * mode, sidestepping wallet-mode entirely — this branch is a defensive\n * safety net for future direct SDK users who pass SUI in wallet mode.\n *\n * **`swapAll` semantics (wallet mode):** if the requested raw amount\n * is >= the wallet's total `from` balance, the appender consumes the\n * entire merged primary coin (not a split), matching audric's host\n * route's `swapAll` clipping. The returned `effectiveAmountIn` reflects\n * the actual consumed amount in display units.\n *\n * **Slippage:** clamped to [0.001, 0.05] (0.1% – 5%). Defaults to 0.01.\n *\n * @returns\n * - `coin` — output coin reference, ready for downstream consumption\n * (e.g. `addSaveToTx`) or wallet transfer (`tx.transferObjects`).\n * - `effectiveAmountIn` — display-units input amount the swap actually\n * consumes (handles `swapAll` clipping in wallet mode; in chain mode\n * echoes the requested `input.amount`).\n * - `expectedAmountOut` — display-units output amount per the route\n * quote. Actual on-chain output may differ within slippage.\n * - `route` — raw `SwapRouteResult` for downstream telemetry / logging.\n */\nexport async function addSwapToTx(\n tx: Transaction,\n client: SuiCoreClient,\n address: string,\n input: {\n from: string;\n to: string;\n amount: number;\n slippage?: number;\n byAmountIn?: boolean;\n overlayFee?: OverlayFeeConfig;\n inputCoin?: TransactionObjectArgument;\n /**\n * Optional Cetus provider allow-list. Forwarded to `findSwapRoute`.\n * Sponsored flows (Enoki) MUST pass `getProvidersExcluding([...])`\n * to remove Pyth-dependent providers — see `findSwapRoute`'s JSDoc\n * for the exclusion list. Non-sponsored callers omit this.\n */\n providers?: string[];\n /**\n * [SPEC 20.2 D-3 (b)] Precomputed route from a prior `findSwapRoute()`\n * call (typically captured by `swap_quote` and threaded through\n * `pending_action.cetusRoute`). When present AND not stale (per\n * `isCetusRouteFresh`) AND the input/output coins match, this skips\n * the ~400-500ms `findSwapRoute()` discovery call. Stale routes are\n * silently ignored (caller falls back to fresh discovery).\n *\n * Caller responsibility: pass the SAME `overlayFee` / `providers` /\n * `byAmountIn` that produced the precomputed route. Mismatch will\n * still produce a working swap but may use the wrong overlay-fee\n * config (the route data already encodes the chosen DEX path).\n */\n precomputedRoute?: SwapRouteResult;\n /**\n * Whether this swap is being built inside a sponsored-tx flow (Enoki)\n * vs self-funded (CLI / direct sign). Load-bearing for SUI-source\n * swaps in wallet mode: under sponsored flows, `tx.gas` belongs to\n * the sponsor and CANNOT be referenced as a transaction argument\n * (Sui protocol rejects with `Cannot use GasCoin as a transaction\n * argument`). When `true`, SUI source routes through `selectSuiCoin`\n * with `useGasCoin: false` so the resolver sources from the user's\n * SUI coin objects + address balance instead. Defaults to `false`\n * (back-compat — pre-2.14.1 behavior). Audric/web-v2's compose path\n * threads this through via `composeTx({ sponsoredContext: true })`.\n */\n sponsoredContext?: boolean;\n /**\n * Per-PTB merge cache for sponsored coin-object sourcing (any coin\n * type — SUI in the dedicated branch, USDC/USDsui/etc. in the wallet\n * branch). Provided by `composeTx`'s orchestration loop so multiple\n * legs sourcing the same coin in one bundle share a single merged\n * primary coin instead of each emitting its own `mergeCoins` (the\n * second of which references already-consumed coins → Enoki dry-run\n * `ArgumentWithoutValue`). Single swaps don't need it; omit. See\n * `SponsoredCoinMergeCache` JSDoc.\n */\n coinMergeCache?: SponsoredCoinMergeCache;\n },\n): Promise<{\n coin: TransactionObjectArgument;\n effectiveAmountIn: number;\n expectedAmountOut: number;\n route: SwapRouteResult;\n /** True when `precomputedRoute` was used (no `findSwapRoute()` call). */\n usedPrecomputedRoute: boolean;\n}> {\n const { T2000Error } = await import('../errors.js');\n\n const fromType = resolveTokenType(input.from);\n const toType = resolveTokenType(input.to);\n if (!fromType) throw new T2000Error('ASSET_NOT_SUPPORTED', `Unknown token: ${input.from}. Provide the symbol (USDC, SUI, ...) or full coin type.`);\n if (!toType) throw new T2000Error('ASSET_NOT_SUPPORTED', `Unknown token: ${input.to}. Provide the symbol (USDC, SUI, ...) or full coin type.`);\n if (fromType === toType) throw new T2000Error('SWAP_FAILED', 'Cannot swap a token to itself');\n if (!Number.isFinite(input.amount) || input.amount <= 0) {\n throw new T2000Error('INVALID_AMOUNT', 'Amount must be greater than zero');\n }\n\n const fromDecimals = getDecimalsForCoinType(fromType);\n const toDecimals = getDecimalsForCoinType(toType);\n const requestedRaw = BigInt(Math.floor(input.amount * 10 ** fromDecimals));\n\n const slippage = Math.max(0.001, Math.min(input.slippage ?? 0.01, 0.05));\n const byAmountIn = input.byAmountIn ?? true;\n\n let inputCoin: TransactionObjectArgument;\n let effectiveRaw: bigint;\n\n if (input.inputCoin) {\n inputCoin = input.inputCoin;\n effectiveRaw = requestedRaw;\n } else if (fromType === '0x2::sui::SUI') {\n // SUI source needs special handling: under sponsored flows (Enoki),\n // referencing `tx.gas` as a transaction argument is forbidden (sponsor\n // owns the gas coin). `selectSuiCoin` does the right thing for both\n // sponsored (uses `coinWithBalance({ useGasCoin: false })`) and\n // self-funded (splits from `tx.gas` directly). The 2.14.0 release\n // shipped without this branch and broke audric/web-v2 SUI→USDC swaps\n // (\"Cannot use GasCoin as a transaction argument\" from Enoki); fixed\n // in 2.14.1 (S.260).\n const { selectSuiCoin } = await import('../wallet/coinSelection.js');\n const result = await selectSuiCoin(\n tx,\n client,\n address,\n requestedRaw,\n input.sponsoredContext ?? false,\n input.coinMergeCache,\n );\n inputCoin = result.coin;\n effectiveRaw = result.effectiveAmount;\n } else {\n // Non-SUI wallet-mode source — delegate to the canonical prelude.\n // NON-sponsored: pre-flights against `getBalance().totalBalance` and\n // returns a `coinWithBalance({ type, balance })` arg, whose `@mysten/sui`\n // resolver batches all intents for a coin type into a single build-time\n // merge — so same-asset multi-leg bundles dedup automatically.\n //\n // SPONSORED: routes through `selectCoinObjectsOnly` instead (coinWithBalance's\n // address-balance `FundsWithdrawal` reservation is what Enoki can't\n // deserialize, issue #93). That manual path has NO build-time batching, so\n // two legs sourcing the same coin would each emit their own `mergeCoins`\n // over the SAME objects → second merge references consumed coins → Enoki\n // dry-run `ArgumentWithoutValue`. The `coinMergeCache` supplies the dedup:\n // first leg merges once + caches the primary, later legs split from it.\n const { selectAndSplitCoin } = await import('../wallet/coinSelection.js');\n const result = await selectAndSplitCoin(tx, client, address, fromType, requestedRaw, {\n sponsoredContext: input.sponsoredContext ?? false,\n mergeCache: input.coinMergeCache,\n });\n inputCoin = result.coin;\n effectiveRaw = result.effectiveAmount;\n }\n\n // [SPEC 20.2 D-3 (b)] Use the precomputed route when available + valid.\n // Validity = same input/output coin types AND the requested raw amount\n // matches what the route was discovered for (mismatch indicates the user\n // edited the amount post-quote, in which case we must re-discover at the\n // new amount because price impact is amount-dependent). The caller\n // (`audric prepare-route`) owns the staleness check (`isCetusRouteFresh`)\n // and only forwards `precomputedRoute` when fresh.\n //\n // [Bug A defense-in-depth / 2026-05-10] Even with the engine fix that\n // makes `swap_quote` discover sponsor-safe routes, this layer also\n // validates the precomputed route against the active providers\n // allow-list. If the route walks any excluded provider (e.g. a stale\n // `pending_action.cetusRoute` from before the engine fix shipped, or a\n // provider list that drifted between quote and execute), fall back to\n // fresh discovery. Better to eat 400ms than to let a Pyth-dependent\n // route reach Enoki and revert with HTTP 400.\n let route: SwapRouteResult | null;\n let usedPrecomputedRoute = false;\n if (\n input.precomputedRoute &&\n input.precomputedRoute.amountIn === effectiveRaw.toString() &&\n input.precomputedRoute.byAmountIn === byAmountIn &&\n isPrecomputedRouteCompatibleWithProviders(input.precomputedRoute, input.providers)\n ) {\n route = input.precomputedRoute;\n usedPrecomputedRoute = true;\n } else {\n route = await findSwapRoute({\n walletAddress: address,\n from: fromType,\n to: toType,\n amount: effectiveRaw,\n byAmountIn,\n overlayFee: input.overlayFee,\n providers: input.providers,\n });\n }\n\n if (!route) {\n throw new T2000Error('SWAP_NO_ROUTE', `No swap route found for ${input.from} → ${input.to}`);\n }\n if (route.insufficientLiquidity) {\n throw new T2000Error('SWAP_NO_ROUTE', `Insufficient liquidity for ${input.from} → ${input.to}`);\n }\n\n const outputCoin = await buildSwapTx({\n walletAddress: address,\n route,\n tx,\n inputCoin,\n slippage,\n overlayFee: input.overlayFee,\n });\n\n return {\n coin: outputCoin,\n effectiveAmountIn: Number(effectiveRaw) / 10 ** fromDecimals,\n expectedAmountOut: Number(route.amountOut) / 10 ** toDecimals,\n route,\n usedPrecomputedRoute,\n };\n}\n\n// Re-export from the canonical token registry for backward-compat.\nexport { TOKEN_MAP, resolveTokenType } from '../token-registry.js';\n","/**\n * Standalone swap quote — no T2000 agent instance required.\n * Only needs a wallet address for Cetus Aggregator routing.\n */\nimport { T2000Error } from './errors.js';\nimport { getDecimalsForCoinType } from './token-registry.js';\nimport type { SwapQuoteResult } from './types.js';\n\nexport async function getSwapQuote(params: {\n walletAddress: string;\n from: string;\n to: string;\n amount: number;\n byAmountIn?: boolean;\n /**\n * [Bug A fix / 2026-05-10] Optional Cetus provider allow-list, forwarded to\n * `findSwapRoute`. Sponsored callers (Enoki) MUST pass\n * `getSponsoredSwapProviders()` to remove Pyth-dependent providers\n * (HAEDALPMM, METASTABLE, OBRIC, STEAMM_OMM/_V2, SEVENK, HAEDALHMMV2).\n * Those providers cause the Cetus aggregator's internal `routerSwap` to\n * insert a `tx.splitCoins(tx.gas, ...)` call for the Pyth update fee,\n * which Enoki rejects with HTTP 400 \"Cannot use GasCoin as a transaction\n * argument\" (3-step bundle smoke 2026-05-10).\n *\n * Pre-fix: `getSwapQuote` discovered routes against the FULL provider set,\n * stashed Pyth-dependent routes onto `pending_action.cetusRoute` (SPEC\n * 20.2 fast-path), and the audric `prepare` route's `swap_execute`\n * appender used the precomputed route AS-IS — bypassing the providers\n * filter that `composeTx` correctly applied. Result: every swap whose\n * best route happened to include a Pyth-dependent provider failed at\n * Enoki sponsorship.\n *\n * Non-sponsored callers (e.g. CLI direct swap) leave this undefined to\n * keep access to the full provider set including Pyth-dependent pools.\n */\n providers?: string[];\n /**\n * [2.11] On-chain-resolved decimals for `from` / `to`, supplied by callers\n * that hold a client (e.g. `T2000.swapQuote`). When omitted (standalone /\n * sponsored callers), falls back to the registry — correct for registry\n * tokens, a 9-decimal guess for an unknown coin type.\n */\n fromDecimals?: number;\n toDecimals?: number;\n}): Promise<SwapQuoteResult> {\n const { findSwapRoute, resolveTokenType } = await import('./protocols/cetus-swap.js');\n\n const fromType = resolveTokenType(params.from);\n const toType = resolveTokenType(params.to);\n // [S.123 v1.24.7] Use T2000Error('ASSET_NOT_SUPPORTED') consistently with the\n // other 4 throw sites in t2000.ts / cetus-swap.ts. Allows tools to branch\n // on `err.code === 'ASSET_NOT_SUPPORTED'` and return a structured recovery\n // hint to the LLM instead of re-throwing a generic error string.\n if (!fromType) {\n throw new T2000Error(\n 'ASSET_NOT_SUPPORTED',\n `Unknown token: ${params.from}. Provide the symbol (USDC, SUI, ...) or full coin type.`,\n );\n }\n if (!toType) {\n throw new T2000Error(\n 'ASSET_NOT_SUPPORTED',\n `Unknown token: ${params.to}. Provide the symbol (USDC, SUI, ...) or full coin type.`,\n );\n }\n\n const byAmountIn = params.byAmountIn ?? true;\n\n const fromDecimals = params.fromDecimals ?? getDecimalsForCoinType(fromType);\n const rawAmount = BigInt(Math.floor(params.amount * 10 ** fromDecimals));\n\n const route = await findSwapRoute({\n walletAddress: params.walletAddress,\n from: fromType,\n to: toType,\n amount: rawAmount,\n byAmountIn,\n providers: params.providers,\n });\n\n if (!route) throw new T2000Error('SWAP_FAILED', `No swap route found for ${params.from} -> ${params.to}.`);\n if (route.insufficientLiquidity) {\n throw new T2000Error('SWAP_FAILED', `Insufficient liquidity for ${params.from} -> ${params.to}.`);\n }\n\n const toDecimals = params.toDecimals ?? getDecimalsForCoinType(toType);\n const fromAmount = Number(route.amountIn) / 10 ** fromDecimals;\n const toAmount = Number(route.amountOut) / 10 ** toDecimals;\n\n const routeDesc = route.routerData.paths\n ?.map((p: { provider?: string }) => p.provider)\n .filter(Boolean)\n .slice(0, 3)\n .join(' + ') ?? 'Cetus Aggregator';\n\n // [SPEC 20.2 / D-1 (a)] Serialize the Cetus route at quote time so the\n // engine can attach it to `pending_action.cetusRoute`. The serialized\n // form survives the SSE → client → POST → prepare-route hop without losing\n // BN/Map fidelity (raw RouterDataV3 doesn't JSON-stringify cleanly).\n const { serializeCetusRoute } = await import('./protocols/cetus-swap.js');\n const serializedRoute = serializeCetusRoute(route, { fromCoinType: fromType, toCoinType: toType });\n\n return {\n fromToken: params.from,\n toToken: params.to,\n fromAmount,\n toAmount,\n priceImpact: route.priceImpact,\n route: routeDesc,\n serializedRoute,\n };\n}\n","import { T2000Error } from './errors.js';\n\nexport const MIST_PER_SUI = 1_000_000_000n;\nexport const SUI_DECIMALS = 9;\nexport const USDC_DECIMALS = 6;\n\nexport const PRECISION = 1_000_000_000_000_000_000n;\n\nexport const MIN_DEPOSIT = 1_000_000n; // 1 USDC (6 decimals)\n\nexport const CLOCK_ID = '0x6';\n\nexport const SUPPORTED_ASSETS = {\n USDC: {\n type: '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC',\n decimals: 6,\n symbol: 'USDC',\n displayName: 'USDC',\n },\n USDT: {\n type: '0x375f70cf2ae4c00bf37117d0c85a2c71545e6ee05c4a5c7d282cd66a4504b068::usdt::USDT',\n decimals: 6,\n symbol: 'USDT',\n displayName: 'suiUSDT',\n },\n USDe: {\n type: '0x41d587e5336f1c86cad50d38a7136db99333bb9bda91cea4ba69115defeb1402::sui_usde::SUI_USDE',\n decimals: 6,\n symbol: 'USDe',\n displayName: 'suiUSDe',\n },\n USDsui: {\n type: '0x44f838219cf67b058f3b37907b655f226153c18e33dfcd0da559a844fea9b1c1::usdsui::USDSUI',\n decimals: 6,\n symbol: 'USDsui',\n displayName: 'USDsui',\n },\n SUI: {\n type: '0x2::sui::SUI',\n decimals: 9,\n symbol: 'SUI',\n displayName: 'SUI',\n },\n WAL: {\n type: '0x356a26eb9e012a68958082340d4c4116e7f55615cf27affcff209cf0ae544f59::wal::WAL',\n decimals: 9,\n symbol: 'WAL',\n displayName: 'WAL',\n },\n ETH: {\n type: '0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH',\n decimals: 8,\n symbol: 'ETH',\n displayName: 'suiETH',\n },\n NAVX: {\n type: '0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX',\n decimals: 9,\n symbol: 'NAVX',\n displayName: 'NAVX',\n },\n GOLD: {\n type: '0x9d297676e7a4b771ab023291377b2adfaa4938fb9080b8d12430e4b108b836a9::xaum::XAUM',\n decimals: 6,\n symbol: 'GOLD',\n displayName: 'XAUM',\n },\n} as const;\n\nexport type SupportedAsset = keyof typeof SUPPORTED_ASSETS;\n\n// [SPEC_AGENTIC_STACK P1 / SDK F3 — 2026-05-25]\n// `StableAsset` = \"what we treat as worth $1 for wallet pricing and balance roll-up\".\n// Pre-Phase 1: USDC only — left USDsui wallet holdings invisible to balance.ts.\n// Phase 1: widened to USDC + USDsui (both are NAVI-native stables with $1 peg).\n// USDT / USDe stay OUT of this set deliberately — they are stables, but the\n// codebase has never priced them at $1, and adding them here would require\n// auditing balance.ts callers downstream. Keep the carve minimal.\nexport type StableAsset = 'USDC' | 'USDsui';\nexport const STABLE_ASSETS: readonly StableAsset[] = ['USDC', 'USDsui'] as const;\n\n// ---------------------------------------------------------------------------\n// Operation → allowed asset rules (single source of truth)\n// ---------------------------------------------------------------------------\n\n// [v4.0 Phase A Day 2 — 2026-05-26] `send` is constrained to\n// `['USDC', 'USDsui', 'SUI']`. Rationale (SPEC_AGENT_WALLET_GREENFIELD §A):\n// - USDC + USDsui are gasless via `0x2::balance::send_funds` (Sui mainnet\n// protocol allowlist) — the two foundation stables.\n// - SUI is the only non-stable kept on the allowlist so users with no\n// stablecoin balance can still pay gas-native SUI transfers.\n// - USDT, USDe, WAL, ETH, NAVX, GOLD are NOT sendable — users must swap to\n// USDC/USDsui first (one-step) or hold SUI and use a manual Move call.\n// `swap` is unrestricted (Cetus routes any pair). The DeFi operations\n// (save/borrow/withdraw/repay) were removed with NAVI.\nexport const OPERATION_ASSETS = {\n send: ['USDC', 'USDsui', 'SUI'],\n swap: '*',\n} as const;\n\nexport type Operation = keyof typeof OPERATION_ASSETS;\n\nexport function isAllowedAsset(op: Operation, asset: string): boolean {\n const allowed = OPERATION_ASSETS[op];\n if (allowed === '*') return true;\n // [v0.51.0] Mixed-case canonical keys (USDsui, suiUSDT) need case-insensitive\n // membership. Pre-v0.51 we only had USDC ↔ USDC (uppercase identity), so\n // a one-sided uppercase compare looked correct. Now that USDsui is in the\n // set, normalize both sides.\n const target = asset.toLowerCase();\n return (allowed as readonly string[]).some((a) => a.toLowerCase() === target);\n}\n\n/**\n * Throws if the asset is not permitted for the given operation.\n *\n * [v4.0 Phase A Day 2] Pre-v4 this allowed `undefined` as a silent default\n * to USDC. Removed because every write path now requires explicit asset\n * (see `T2000.send` + `buildSendTx` + `composeTx.send_transfer`). The\n * `undefined → no-op` branch is kept defensively; the `send_transfer` flow\n * validates non-undefined.\n */\nexport function assertAllowedAsset(op: Operation, asset: string | undefined): void {\n if (!asset) return;\n if (!isAllowedAsset(op, asset)) {\n const allowed = OPERATION_ASSETS[op];\n const list = Array.isArray(allowed) ? allowed.join(', ') : 'any';\n const swapHint =\n op === 'send' ? ' Swap to USDC or USDsui first, or send SUI.' : '';\n throw new T2000Error(\n 'INVALID_ASSET',\n `${op} only supports ${list}. Cannot use ${asset}.${swapHint}`,\n );\n }\n}\n\n/**\n * [v4.0 Phase A Day 2] Narrow type alias for assets sendable through the\n * Agent Wallet. Matches `OPERATION_ASSETS.send` exactly. Exported so the\n * CLI / SDK / composeTx can share one type without re-declaring it.\n */\nexport type SendableAsset = 'USDC' | 'USDsui' | 'SUI';\nexport const SENDABLE_ASSETS: readonly SendableAsset[] = ['USDC', 'USDsui', 'SUI'] as const;\n\n/**\n * [v4.0 Phase A Day 2] Coin types for the two gasless-allowlisted stables.\n * Used by `wallet/send.ts` + `composeTx.send_transfer` to construct the\n * `0x2::balance::send_funds` Move call's `typeArguments`. SUI is excluded\n * because SUI transfers are NOT gasless (gas-native, uses `tx.gas` split +\n * `transferObjects` per the existing path).\n */\nexport const GASLESS_STABLE_TYPES: Record<'USDC' | 'USDsui', string> = {\n USDC: SUPPORTED_ASSETS.USDC.type,\n USDsui: SUPPORTED_ASSETS.USDsui.type,\n};\n\n// Swap overlay fees route here. Audric's prepare/route.ts passes\n// `overlayFee.receiver = T2000_OVERLAY_FEE_WALLET` to the Cetus aggregator. The\n// CLI/SDK never charge fees — this constant is exported for consumer apps only.\n//\n// Address corresponds to the treasury admin wallet. Override via env for local dev /\n// testnet only — production must use the canonical mainnet address below.\nexport const T2000_OVERLAY_FEE_WALLET = process.env.T2000_OVERLAY_FEE_WALLET\n ?? '0x5366efbf2b4fe5767fe2e78eb197aa5f5d138d88ac3333fbf3f80a1927da473a';\n\nexport const DEFAULT_NETWORK = 'mainnet' as const;\n// gRPC fullnode endpoint. Post-flip this is the canonical transport for the\n// whole SDK: `getSuiClient()` (reads + execution) AND `getSuiGrpcClient()`\n// (gasless stablecoin build detection) both target it. Override the read/exec\n// client with T2000_RPC_URL and the build client with T2000_GRPC_URL.\nexport const DEFAULT_RPC_URL = 'https://fullnode.mainnet.sui.io:443';\nexport const DEFAULT_GRPC_URL = 'https://fullnode.mainnet.sui.io:443';\n// [gRPC migration] GraphQL endpoint for the query surface that has NO gRPC\n// `core` equivalent — `transactionBlocks` (history). Used by\n// `getSuiGraphQLClient()`. The canonical mainnet host is `graphql.mainnet.sui.io`\n// (parallel to the gRPC fullnode); the older `sui-mainnet.mystenlabs.com/graphql`\n// host was dropped 2026-06-15 after it began resetting TLS connections (live\n// smoke). Public endpoint is rate-limited — production hosts override with\n// T2000_GRAPHQL_URL to a dedicated provider.\nexport const DEFAULT_GRAPHQL_URL = 'https://graphql.mainnet.sui.io/graphql';\nexport const DEFAULT_KEY_PATH = '~/.t2000/wallet.key';\nexport const DEFAULT_CONFIG_PATH = '~/.t2000/config.json';\n\n// [v4.0 Phase A Day 2] Minimum stablecoin amount for protocol-level gasless\n// transfers via `0x2::balance::send_funds`. The Sui mainnet allowlist enforces\n// this floor at the protocol level to prevent dust spam; we surface a clear\n// error before signing rather than letting the tx revert on-chain.\nexport const GASLESS_MIN_STABLE_AMOUNT = 0.01;\n\n// Cetus USDC/SUI pool — read-only for SUI price oracle (no SDK dependency)\nexport const CETUS_USDC_SUI_POOL = '0x51e883ba7c0b566a26cbc8a94cd33eb0abd418a77cc1e60ad22fd9b1f29cd2ab';\n\nexport const GAS_RESERVE_MIN = 0.05; // minimum SUI to keep for gas\n","import { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';\nimport { SuiGrpcClient } from '@mysten/sui/grpc';\nimport { SuiGraphQLClient } from '@mysten/sui/graphql';\nimport { isValidSuiAddress, normalizeSuiAddress } from '@mysten/sui/utils';\nimport { DEFAULT_GRAPHQL_URL, DEFAULT_GRPC_URL, DEFAULT_RPC_URL } from '../constants.js';\nimport { T2000Error } from '../errors.js';\n\n/**\n * [gRPC migration / S.438] Transport-agnostic client type for the migration.\n *\n * Both `SuiJsonRpcClient` and `SuiGrpcClient` extend `BaseClient` and expose\n * an identical `.core.*` API. During the migration, call sites are rewritten\n * from legacy methods (`getBalance`, `getObject`, `executeTransactionBlock`)\n * to the unified `client.core.*` API and typed against this union — so the\n * rewrite is behavior-preserving while still on JSON-RPC, and the final\n * transport flip (gRPC) is a one-line change in `getSuiClient()`.\n *\n * The query surface that has no gRPC `core` equivalent (`queryTransactionBlocks`\n * / `queryEvents`, Stage 0 finding A) uses `getSuiGraphQLClient()` instead.\n */\nexport type SuiCoreClient = SuiJsonRpcClient | SuiGrpcClient;\n\n/**\n * Resolve the effective JSON-RPC URL: explicit arg > env var > default.\n * `T2000_RPC_URL` is an OPTIONAL override per the Greenfield SPEC's env\n * contract — no required vars, so we read inline (allowed by\n * `env-validation-gate.mdc` carve-out for packages with zero required\n * env vars).\n */\nfunction resolveRpcUrl(rpcUrl?: string): string {\n if (rpcUrl) return rpcUrl;\n const envUrl = process.env.T2000_RPC_URL?.trim();\n if (envUrl) return envUrl;\n return DEFAULT_RPC_URL;\n}\n\n/**\n * Same shape as `resolveRpcUrl` for the gRPC endpoint.\n */\nfunction resolveGrpcUrl(grpcUrl?: string): string {\n if (grpcUrl) return grpcUrl;\n const envUrl = process.env.T2000_GRPC_URL?.trim();\n if (envUrl) return envUrl;\n return DEFAULT_GRPC_URL;\n}\n\n/**\n * Same shape as `resolveRpcUrl` for the GraphQL endpoint.\n */\nfunction resolveGraphqlUrl(graphqlUrl?: string): string {\n if (graphqlUrl) return graphqlUrl;\n const envUrl = process.env.T2000_GRAPHQL_URL?.trim();\n if (envUrl) return envUrl;\n return DEFAULT_GRAPHQL_URL;\n}\n\n/**\n * Canonical agent client cache, keyed by URL. The earlier impl cached\n * unconditionally and ignored URL changes after the first call —\n * brittle for testnet smokes and custom-RPC test setups.\n */\nconst rpcClientCache = new Map<string, SuiGrpcClient>();\n\n/**\n * [gRPC cutover] The canonical agent client is now gRPC. Mysten deactivates\n * the JSON-RPC fullnode interface on 2026-07-31, so reads (`.core.*`) and\n * execution route over gRPC — transaction *builds* already do\n * (`getSuiGrpcClient`). The whole SDK was first refactored onto the unified\n * `.core` API (behavior-preserving on JSON-RPC), then flipped here. The\n * `rpcUrl` arg / `T2000_RPC_URL` override now resolve a gRPC `baseUrl`\n * (`DEFAULT_RPC_URL` is the same host as `DEFAULT_GRPC_URL`). The historical\n * query surface stays on `getSuiGraphQLClient()`.\n */\nexport function getSuiClient(rpcUrl?: string): SuiGrpcClient {\n const url = resolveRpcUrl(rpcUrl);\n const cached = rpcClientCache.get(url);\n if (cached) return cached;\n const client = new SuiGrpcClient({ baseUrl: url, network: 'mainnet' });\n rpcClientCache.set(url, client);\n return client;\n}\n\n/**\n * gRPC client cache, keyed by URL. Same rationale as the JSON-RPC cache:\n * different URLs must produce different clients.\n */\nconst grpcClientCache = new Map<string, SuiGrpcClient>();\n\n/**\n * Cached `SuiGrpcClient` for gasless stablecoin transfer builds.\n *\n * [v4.0 Phase A Day 2 — SPEC_AGENT_WALLET_GREENFIELD §A]\n *\n * Why this exists: Sui mainnet's protocol-level gasless stablecoin transfers\n * (`0x2::balance::send_funds` on the USDC + USDsui allowlist) are detected\n * ONLY when the transaction is built through a `SuiGrpcClient`. The gRPC\n * client's build resolver inspects the PTB at `tx.build()` time and, if it\n * matches the gasless pattern, sets `gasPrice=0` + `gasBudget=0` automatically.\n * Building the SAME PTB through `SuiJsonRpcClient` produces the same bytes\n * but with non-zero gas — the tx still works, but the user pays SUI gas.\n *\n * Execution stays on JSON-RPC (`SuiJsonRpcClient.executeTransactionBlock`)\n * because (a) the rest of the SDK expects JSON-RPC and (b) Sui's docs\n * explicitly support a \"build via gRPC, execute via JSON-RPC\" hybrid:\n * https://docs.sui.io/develop/transaction-payment/gasless-stablecoin-transfers\n *\n * Override the endpoint with the `T2000_GRPC_URL` env var or the\n * `grpcUrl` arg. Cache is keyed by URL so multiple endpoints can\n * co-exist (e.g., the rare testnet smoke + production usage from the\n * same process).\n */\nexport function getSuiGrpcClient(grpcUrl?: string): SuiGrpcClient {\n const baseUrl = resolveGrpcUrl(grpcUrl);\n const cached = grpcClientCache.get(baseUrl);\n if (cached) return cached;\n const client = new SuiGrpcClient({ baseUrl, network: 'mainnet' });\n grpcClientCache.set(baseUrl, client);\n return client;\n}\n\n/**\n * GraphQL client cache, keyed by URL. Same rationale as the other caches.\n */\nconst graphqlClientCache = new Map<string, SuiGraphQLClient>();\n\n/**\n * Cached `SuiGraphQLClient` for the query surface that has NO gRPC `core`\n * equivalent: `queryTransactionBlocks` + `queryEvents` (Stage 0 finding A —\n * `SPEC_FULL_GRPC_MIGRATION.md`). Mysten's gRPC successor doesn't cover the\n * historical query/event API; GraphQL is its documented home. Consumers:\n * `wallet/history.ts` + the swap-event read in `protocols/cetus-swap.ts`.\n *\n * Override the endpoint with `T2000_GRAPHQL_URL` or the `graphqlUrl` arg.\n */\nexport function getSuiGraphQLClient(graphqlUrl?: string): SuiGraphQLClient {\n const url = resolveGraphqlUrl(graphqlUrl);\n const cached = graphqlClientCache.get(url);\n if (cached) return cached;\n const client = new SuiGraphQLClient({ url, network: 'mainnet' });\n graphqlClientCache.set(url, client);\n return client;\n}\n\nexport function validateAddress(address: string): string {\n const normalized = normalizeSuiAddress(address);\n if (!isValidSuiAddress(normalized)) {\n throw new T2000Error('INVALID_ADDRESS', `Invalid Sui address: ${address}`);\n }\n return normalized;\n}\n\nexport function truncateAddress(address: string): string {\n if (address.length <= 10) return address;\n return `${address.slice(0, 6)}...${address.slice(-4)}`;\n}\n\n/**\n * Normalize a Sui coin type to its canonical long-form 64-hex address.\n * `0x2::sui::SUI` → `0x0000…0002::sui::SUI`. Idempotent on already-long\n * forms. Returns the input unchanged if it doesn't look like a coin type\n * (`<address>::<module>::<name>`) so callers can pass arbitrary strings\n * without crashing.\n *\n * Why this exists: BlockVision's `/v2/sui/coin/price/list` endpoint\n * silently returns an empty `prices` map for short-form coin types\n * (notably `0x2::sui::SUI` — the native gas coin). Internal callers must\n * pass the long form, but external callers (LLM tool args, cached\n * coin-type strings, audit logs) commonly use the short form. Normalize\n * before the network call, denormalize back to the caller's input shape\n * after, and short/long become interchangeable.\n */\nexport function normalizeCoinType(coinType: string): string {\n const parts = coinType.split('::');\n if (parts.length !== 3) return coinType;\n const [addr, mod, name] = parts;\n if (!addr.startsWith('0x')) return coinType;\n return `${normalizeSuiAddress(addr)}::${mod}::${name}`;\n}\n","// v4.0 wallet auth model: plain Bech32 secret in a versioned JSON file,\n// 0o600 perms. Matches the Sui CLI convention. No AES, no PIN, no scrypt.\n// Anything that isn't `{ version: 2, secret: \"suiprivkey1...\" }` throws\n// `WALLET_CORRUPT` — the user moves/deletes the file and runs `t2 init`.\n\nimport { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';\nimport { decodeSuiPrivateKey } from '@mysten/sui/cryptography';\nimport { readFile, writeFile, mkdir, access } from 'node:fs/promises';\nimport { dirname, resolve } from 'node:path';\nimport { homedir } from 'node:os';\nimport { T2000Error } from '../errors.js';\nimport { DEFAULT_KEY_PATH } from '../constants.js';\n\ninterface PlainKey {\n version: 2;\n secret: string;\n}\n\nfunction expandPath(p: string): string {\n if (p.startsWith('~')) return resolve(homedir(), p.slice(2));\n return resolve(p);\n}\n\nexport function generateKeypair(): Ed25519Keypair {\n return Ed25519Keypair.generate();\n}\n\nexport function keypairFromPrivateKey(privateKey: string): Ed25519Keypair {\n if (privateKey.startsWith('suiprivkey')) {\n const decoded = decodeSuiPrivateKey(privateKey);\n return Ed25519Keypair.fromSecretKey(decoded.secretKey);\n }\n const bytes = Buffer.from(privateKey.replace(/^0x/, ''), 'hex');\n return Ed25519Keypair.fromSecretKey(bytes);\n}\n\n/**\n * Save a keypair as a v2 plain Bech32 JSON file with `0o600` perms.\n *\n * `_passphrase` is accepted but IGNORED — kept in the signature for\n * back-compat with v3.x callers. Will be removed when all callers\n * are off PIN (Phase A Day 5+).\n */\nexport async function saveKey(\n keypair: Ed25519Keypair,\n _passphrase: string | undefined,\n keyPath?: string,\n): Promise<string> {\n const filePath = expandPath(keyPath ?? DEFAULT_KEY_PATH);\n\n try {\n await access(filePath);\n throw new T2000Error('WALLET_EXISTS', `Wallet already exists at ${filePath}`);\n } catch (error) {\n if (error instanceof T2000Error) throw error;\n }\n\n await mkdir(dirname(filePath), { recursive: true });\n\n const payload: PlainKey = {\n version: 2,\n secret: keypair.getSecretKey(),\n };\n\n await writeFile(filePath, JSON.stringify(payload, null, 2), { mode: 0o600 });\n\n return filePath;\n}\n\n/**\n * Save a Bech32 secret directly as a v2 plain wallet file. Used by any\n * path where the secret is supplied externally rather than freshly\n * generated. Kept exported because external tooling may still want it\n * even though the CLI no longer ships an `--import` flag.\n */\nexport async function saveBech32(secret: string, keyPath?: string): Promise<string> {\n if (!secret.startsWith('suiprivkey')) {\n throw new T2000Error(\n 'INVALID_KEY',\n `Secret must be a Bech32 suiprivkey1... string. Got: ${secret.slice(0, 12)}...`,\n );\n }\n decodeSuiPrivateKey(secret);\n\n const filePath = expandPath(keyPath ?? DEFAULT_KEY_PATH);\n\n try {\n await access(filePath);\n throw new T2000Error('WALLET_EXISTS', `Wallet already exists at ${filePath}`);\n } catch (error) {\n if (error instanceof T2000Error) throw error;\n }\n\n await mkdir(dirname(filePath), { recursive: true });\n\n const payload: PlainKey = { version: 2, secret };\n\n await writeFile(filePath, JSON.stringify(payload, null, 2), { mode: 0o600 });\n\n return filePath;\n}\n\n/**\n * Load a keypair from disk.\n *\n * `_passphrase` is accepted but IGNORED — kept for back-compat. The\n * actual file format determines the load path:\n *\n * - **v2 plain JSON** (`{ version: 2, secret: \"suiprivkey1...\" }`) →\n * decode + return keypair.\n * - **Anything else** → throw `WALLET_CORRUPT`. The user moves or\n * deletes the file and runs `t2 init` to create a fresh wallet.\n */\nexport async function loadKey(\n _passphrase?: string,\n keyPath?: string,\n): Promise<Ed25519Keypair> {\n const filePath = expandPath(keyPath ?? DEFAULT_KEY_PATH);\n\n let content: string;\n try {\n content = await readFile(filePath, 'utf-8');\n } catch {\n throw new T2000Error('WALLET_NOT_FOUND', `No wallet found at ${filePath}`);\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch {\n throw new T2000Error(\n 'WALLET_CORRUPT',\n `Wallet file at ${filePath} is not a valid v4 wallet. Move or delete the file, then run \\`t2 init\\`.`,\n );\n }\n\n if (!isPlainKey(parsed)) {\n throw new T2000Error(\n 'WALLET_CORRUPT',\n `Wallet file at ${filePath} is not a valid v4 wallet. Expected { version: 2, secret: \"suiprivkey1...\" }. Move or delete the file, then run \\`t2 init\\`.`,\n );\n }\n\n const decoded = decodeSuiPrivateKey(parsed.secret);\n return Ed25519Keypair.fromSecretKey(decoded.secretKey);\n}\n\nexport async function walletExists(keyPath?: string): Promise<boolean> {\n const filePath = expandPath(keyPath ?? DEFAULT_KEY_PATH);\n try {\n await access(filePath);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function exportPrivateKey(keypair: Ed25519Keypair): string {\n return keypair.getSecretKey();\n}\n\nexport function getAddress(keypair: Ed25519Keypair): string {\n return keypair.getPublicKey().toSuiAddress();\n}\n\nfunction isPlainKey(value: unknown): value is PlainKey {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { version?: unknown }).version === 2 &&\n typeof (value as { secret?: unknown }).secret === 'string'\n );\n}\n","import type { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';\nimport type { TransactionSigner } from '../signer.js';\n\nexport class KeypairSigner implements TransactionSigner {\n readonly kind = 'keypair' as const;\n\n constructor(private readonly keypair: Ed25519Keypair) {}\n\n getAddress(): string {\n return this.keypair.getPublicKey().toSuiAddress();\n }\n\n async signTransaction(txBytes: Uint8Array): Promise<{ signature: string }> {\n return this.keypair.signTransaction(txBytes);\n }\n\n async signPersonalMessage(messageBytes: Uint8Array): Promise<{ signature: string; bytes: string }> {\n return this.keypair.signPersonalMessage(messageBytes);\n }\n\n /** Access the underlying keypair for APIs that still require it directly. */\n getKeypair(): Ed25519Keypair {\n return this.keypair;\n }\n}\n","import type { SuiClientTypes } from '@mysten/sui/client';\nimport type { Transaction } from '@mysten/sui/transactions';\nimport type { TransactionSigner } from '../signer.js';\nimport type { SuiCoreClient } from '../utils/sui.js';\n\n// ---------------------------------------------------------------------------\n// executeTx — build + sign + submit + wait, the SDK's one tx-execution helper.\n//\n// Browser-safe (no fs / keyManager imports) so it can back\n// both the Node-side `T2000` methods AND the browser-side `payWithMpp`\n// (gasless MPP runs client-side on the zkLogin session key). Moved out of\n// `t2000.ts` so `wallet/pay.ts` can share it without pulling the Node-only\n// `T2000` module graph into the browser bundle.\n//\n// [gRPC migration] Submit + wait go through the unified `client.core.*`\n// API (`executeTransaction` + `waitForTransaction`), which is transport-\n// agnostic across the JSON-RPC and gRPC clients.\n// ---------------------------------------------------------------------------\n\nexport type SuiTransactionEffects = SuiClientTypes.TransactionEffects;\nexport type BuildClient = NonNullable<Parameters<Transaction['build']>[0]>['client'];\n\nexport async function executeTx(\n client: SuiCoreClient,\n signer: TransactionSigner,\n buildTx: () => Promise<Transaction> | Transaction,\n options: { buildClient?: BuildClient } = {},\n): Promise<{ digest: string; gasCostSui: number; effects: SuiTransactionEffects | undefined }> {\n const tx = await buildTx();\n tx.setSender(signer.getAddress());\n // [2026-05-22] Optional buildClient. When set, `tx.build()` uses it to\n // resolve the PTB — relevant for gasless stablecoin transfers where the\n // SuiGrpcClient build path auto-detects allowlisted ops and zeros out\n // gasPrice/gasBudget/gasPayment. See `payWithMpp`.\n const txBytes = await tx.build({ client: options.buildClient ?? client });\n const { signature } = await signer.signTransaction(txBytes);\n const result = await client.core.executeTransaction({\n transaction: txBytes,\n signatures: [signature],\n include: { effects: true },\n });\n const txn = result.$kind === 'Transaction' ? result.Transaction : result.FailedTransaction;\n try {\n await client.core.waitForTransaction({ digest: txn.digest });\n } catch (err) {\n // A successful executeTransaction already returned the certified effects —\n // the wait only provides read-your-write index visibility. On a lagging\n // fullnode it can time out AFTER the tx landed; propagating that turns a\n // SUCCESSFUL on-chain payment into a reported failure, which bait-invites\n // a double-pay retry (S.453 JMPR e2e: two 0.02 USDC charges for one call).\n // Effects in hand = executed + certified → proceed. No effects = nothing\n // proves execution → rethrow.\n if (!txn.effects) throw err;\n }\n const effects = txn.effects ?? undefined;\n const gasUsed = effects?.gasUsed;\n let gasCostSui = 0;\n if (gasUsed) {\n const total = BigInt(gasUsed.computationCost) + BigInt(gasUsed.storageCost) - BigInt(gasUsed.storageRebate);\n gasCostSui = Number(total) / 1e9;\n }\n return { digest: txn.digest, gasCostSui, effects };\n}\n","import type { SuiGrpcClient } from '@mysten/sui/grpc';\nimport { fromBase64 } from '@mysten/sui/utils';\nimport type { X402Requirements } from '@suimpp/mpp/x402';\nimport type { TransactionSigner } from '../signer.js';\nimport type { PayOptions, PayResult } from '../types.js';\nimport { T2000Error } from '../errors.js';\nimport { parseChallengeAmount } from '../mpp-cost.js';\nimport { executeTx } from './executeTx.js';\nimport {\n type PreflightResult,\n PREFLIGHT_OK,\n preflightFail,\n checkPositiveAmount,\n} from '../preflight.js';\n\n/**\n * Synchronous, network-free preflight for `pay` (x402 Service call). Validates\n * the target URL shape and the `maxPrice` ceiling when present — the cheap\n * checks the v3 host runs before dispatching the paid tool / showing the\n * tap-to-confirm card. Returns a `PreflightResult`; never throws. The probe +\n * 402 handshake + balance migration stay in `payWithMpp` (network).\n */\nexport function preflightPay(input: { url: string; maxPrice?: number }): PreflightResult {\n if (typeof input.url !== 'string' || input.url.trim() === '') {\n return preflightFail('FACILITATOR_REJECTION', 'A target URL is required to pay');\n }\n let parsed: URL;\n try {\n parsed = new URL(input.url);\n } catch {\n return preflightFail('FACILITATOR_REJECTION', `Invalid URL: ${input.url}`);\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n return preflightFail(\n 'FACILITATOR_REJECTION',\n `URL must be http(s): got ${parsed.protocol}//`,\n );\n }\n // `maxPrice` is optional (no ceiling = pay whatever the 402 asks). Validate\n // only when the caller set one — a malformed ceiling is a fat-finger.\n if (input.maxPrice !== undefined) {\n const priceCheck = checkPositiveAmount(input.maxPrice, 'maxPrice');\n if (!priceCheck.valid) return priceCheck;\n }\n return PREFLIGHT_OK;\n}\n\n// ---------------------------------------------------------------------------\n// payWithMpp — the SDK's single source of truth for the pay loop. Browser-safe\n// (no fs / keyManager / SafeguardEnforcer), so the Audric client can run it\n// in-browser on the zkLogin session key. `T2000.pay()` delegates here.\n//\n// TWO dialects, ONE preference order (both ride the SAME gasless\n// `send_funds<USDC>` rail; the only difference is who submits):\n//\n// 1. x402 `sui-exact` (preferred — SPEC_AGENT_PAYMENTS_X402 1.2; scheme =\n// SUIMPP_X402_SCHEME.md v0.3): the 402 body carries `accepts[]`; the\n// client signs an authorization, the SERVER settles (settle-then-serve,\n// so a failed upstream is never charged). The withdrawal form draws from\n// the SIP-58 address balance, so coin-object funds are migrated in first\n// when needed (S.414 finding).\n//\n// 2. MPP header dialect (fallback — suimpp.dev/spec): the 402 carries only a\n// `WWW-Authenticate: Payment … method=\"sui\"` challenge, no x402 body. The\n// CLIENT broadcasts the gasless USDC transfer and retries with the digest\n// credential. S.452 retired this path assuming all sellers were our\n// gateway (which dual-serves); the first EXTERNAL seller (JMPR, S.453)\n// shipped header-only — the client must speak everything the gateway and\n// suimpp spec serve, so the fallback is back. Trade-off vs x402: the\n// client pays BEFORE the server proves it can deliver, so a broken seller\n// can charge without serving — x402 stays preferred whenever offered.\n// ---------------------------------------------------------------------------\n\nexport async function payWithMpp(args: {\n signer: TransactionSigner;\n client: SuiGrpcClient;\n options: PayOptions;\n}): Promise<PayResult> {\n const { signer, client } = args;\n let options = args.options;\n\n // Layer 2 — cheap synchronous preflight (URL shape + maxPrice sanity) before\n // any network round-trip. Rethrow the precise code+message verbatim.\n const pf = preflightPay({ url: options.url, maxPrice: options.maxPrice });\n if (!pf.valid) throw new T2000Error(pf.code, pf.error);\n\n const method = (options.method ?? 'GET').toUpperCase();\n const canHaveBody = method !== 'GET' && method !== 'HEAD';\n\n // Default `content-type: application/json` when the body IS JSON and the\n // caller didn't say otherwise. Without it, fetch stamps `text/plain` and\n // strict servers (FastAPI et al.) receive the body as a string — a 422\n // before the 402 ever fires (live finding vs JMPR, the first external\n // seller). Every retry below reads from the normalized `options`.\n if (\n canHaveBody &&\n typeof options.body === 'string' &&\n isJsonText(options.body) &&\n !hasContentType(options.headers)\n ) {\n options = {\n ...options,\n headers: { ...(options.headers ?? {}), 'content-type': 'application/json' },\n };\n }\n\n const reqInit: RequestInit = {\n method,\n headers: options.headers,\n body: canHaveBody ? options.body : undefined,\n };\n\n // Probe (no payment). A paid endpoint answers 402; a free/cached one serves.\n const probe = await fetch(options.url, reqInit);\n if (probe.status !== 402) {\n return finalize(probe, { paid: false });\n }\n\n const requirements = await pickSuiExactRequirements(probe, client.network);\n if (requirements) {\n const result = await payViaX402({ signer, client, options, reqInit, requirements });\n await reportDirectPayment(result, options.url);\n return result;\n }\n\n // No x402 envelope — fall back to the MPP header dialect when the 402\n // advertises a `sui` method challenge.\n const headerChallenge = await parseMppSuiChallenge(probe);\n if (headerChallenge) {\n // Fail CLOSED before any money moves: the header dialect pays first and\n // proves identity with a personal-message signature the SELLER verifies.\n // zkLogin signatures are ZK constructs external sellers can't check —\n // the payment settles on-chain, then the retry 402s and the buyer ate\n // the charge (live: JMPR × Audric Passport, 2026-07-17). x402 is immune\n // (the tx itself carries the zkLogin sig; the CHAIN verifies it), so\n // zkLogin payers require sellers that offer x402.\n if (signer.kind === 'zklogin') {\n throw new T2000Error(\n 'DIALECT_UNSUPPORTED',\n 'This seller only offers the MPP header dialect, which zkLogin (Passport) wallets ' +\n 'cannot safely pay: the seller cannot verify zkLogin signatures, so the payment ' +\n 'would settle on-chain without the service delivering. No payment was made. ' +\n 'Use an x402-capable service, or pay from a keypair wallet (t2 CLI / MCP).',\n { dialect: 'mpp-header', signerKind: 'zklogin' },\n );\n }\n const result = await payViaMppHeader({ signer, client, options });\n await reportDirectPayment(result, options.url);\n return result;\n }\n\n throw new T2000Error(\n 'FACILITATOR_REJECTION',\n `Endpoint returned 402 without an x402 'exact' / sui:${client.network} requirement in the body ` +\n `or an MPP 'sui' challenge in WWW-Authenticate. Nothing this SDK can pay.`,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Direct-seller activity reporting (S.743). Gateway-proxied payments are\n// logged server-side by the gateway itself; DIRECT payments (catalog\n// federation — seller's own origin) never touch it, leaving the activity\n// feed blind. After a paid call to a non-gateway origin, tell the gateway\n// \"look at this digest for this url\" — it verifies on-chain (USDC inflow to\n// the cataloged seller's pinned payTo) before recording, so the report\n// carries no trusted data. Best-effort by construction: timeout-capped and\n// error-swallowed, a lost report never fails or delays the payment. Awaited\n// (not fire-and-forget) so short-lived CLI processes don't drop it on exit.\n// ---------------------------------------------------------------------------\n\nconst MPP_REPORT_URL = 'https://mpp.t2000.ai/api/mpp/report';\nconst REPORT_TIMEOUT_MS = 2_000;\n\nasync function reportDirectPayment(result: PayResult, url: string): Promise<void> {\n if (!result.paid || !result.receipt?.reference) return;\n try {\n if (new URL(url).origin === new URL(MPP_REPORT_URL).origin) return;\n await fetch(MPP_REPORT_URL, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ digest: result.receipt.reference, url }),\n signal: AbortSignal.timeout(REPORT_TIMEOUT_MS),\n });\n } catch {\n // Best-effort: the payment already succeeded; the feed row is analytics.\n }\n}\n\n/**\n * Parse the MPP header dialect from a 402 response: the\n * `WWW-Authenticate: Payment …` challenge(s), looking for `method=\"sui\"`.\n * Returns the decoded `{ amount, currency, recipient }` request (amount is a\n * decimal string, e.g. \"0.02\") or `undefined` when the response carries no\n * sui challenge. Exported for the CLI's `t2 pay --estimate`.\n */\nexport async function parseMppSuiChallenge(\n response: Response,\n): Promise<{ amount: string; currency: string; recipient: string; description?: string } | undefined> {\n try {\n const { Challenge } = await import('mppx');\n const challenges = Challenge.fromResponseList(response);\n const suiChallenge = challenges.find((c) => c.method === 'sui' && c.intent === 'charge');\n if (!suiChallenge) return undefined;\n const req = suiChallenge.request as Record<string, unknown>;\n if (typeof req?.amount !== 'string' || typeof req?.recipient !== 'string') return undefined;\n return {\n amount: req.amount,\n currency: typeof req.currency === 'string' ? req.currency : '',\n recipient: req.recipient,\n description: suiChallenge.description,\n };\n } catch {\n return undefined;\n }\n}\n\n// ---------------------------------------------------------------------------\n// x402 `sui-exact` — sign-then-settle\n// ---------------------------------------------------------------------------\n\nasync function pickSuiExactRequirements(\n response: Response,\n network: string,\n): Promise<X402Requirements | undefined> {\n try {\n const body = (await response.clone().json()) as { accepts?: X402Requirements[] };\n const want = `sui:${network === 'testnet' ? 'testnet' : 'mainnet'}`;\n return body.accepts?.find((a) => a.scheme === 'exact' && a.network === want);\n } catch {\n return undefined;\n }\n}\n\nasync function payViaX402(args: {\n signer: TransactionSigner;\n client: SuiGrpcClient;\n options: PayOptions;\n reqInit: RequestInit;\n requirements: X402Requirements;\n}): Promise<PayResult> {\n const { signer, client, options, reqInit, requirements } = args;\n const { buildX402SignedPayment, X402_PAYMENT_HEADER, X402_PAYMENT_RESPONSE_HEADER } = await import(\n '@suimpp/mpp/x402'\n );\n\n const amountRaw = BigInt(requirements.maxAmountRequired);\n assertWithinMaxPrice(atomicToHuman(amountRaw, await assetDecimals(requirements.asset)), options.maxPrice);\n\n // The x402 withdrawal form spends ONLY the SIP-58 address balance. A wallet\n // funded by ordinary coin transfers (or swap output) holds Coin<USDC>\n // objects → migrate enough in first (S.414 finding; SUIMPP_X402_SCHEME §4).\n const migrationGasSui = await ensureAddressBalanceCovers({\n signer,\n client,\n asset: requirements.asset,\n amountRaw,\n });\n\n // Build + sign — NEVER submitted client-side; the gateway settles. The\n // builder only reads toSuiAddress() + signTransaction(), both of which every\n // TransactionSigner (keypair AND zkLogin) provides.\n const signerAdapter = {\n toSuiAddress: () => signer.getAddress(),\n signTransaction: (bytes: Uint8Array) => signer.signTransaction(bytes),\n } as unknown as Parameters<typeof buildX402SignedPayment>[0]['signer'];\n\n const { header } = await buildX402SignedPayment({ requirements, signer: signerAdapter });\n\n const res = await fetch(options.url, {\n ...reqInit,\n headers: { ...(options.headers ?? {}), [X402_PAYMENT_HEADER]: header },\n });\n\n // Settled iff the gateway returned the x402 receipt header.\n const settleHeader = res.headers.get(X402_PAYMENT_RESPONSE_HEADER);\n const paid = !!settleHeader;\n let digest: string | undefined;\n if (settleHeader) {\n try {\n digest = (JSON.parse(new TextDecoder().decode(fromBase64(settleHeader))) as { transaction?: string })\n .transaction;\n } catch {\n digest = undefined;\n }\n }\n\n const result = await finalize(res, { paid });\n if (!paid) return { ...result, dialect: 'x402' };\n return {\n ...result,\n dialect: 'x402',\n cost: atomicToHuman(amountRaw, await assetDecimals(requirements.asset)),\n gasCostSui: migrationGasSui,\n receipt: digest\n ? { reference: digest, timestamp: new Date().toISOString() }\n : result.receipt,\n };\n}\n\n// ---------------------------------------------------------------------------\n// MPP header dialect — client broadcasts, retries with the digest credential.\n// The pre-S.452 `payViaLegacy`, restored (S.453) for header-only external\n// sellers. mppx's client handles the 402 → pay → retry loop; we plug in the\n// Sui charge method with an `execute` override that routes the on-chain leg\n// through `executeTx` (gRPC build → gasless resolver → the same\n// `send_funds<USDC>` rail as x402).\n// ---------------------------------------------------------------------------\n\nasync function payViaMppHeader(args: {\n signer: TransactionSigner;\n client: SuiGrpcClient;\n options: PayOptions;\n}): Promise<PayResult> {\n const { signer, client, options } = args;\n\n const { Mppx } = await import('mppx/client');\n const { sui, USDC, USDC_TESTNET } = await import('@suimpp/mpp/client');\n\n const signerAddress = signer.getAddress();\n const network: 'mainnet' | 'testnet' = client.network === 'testnet' ? 'testnet' : 'mainnet';\n const grpcClient = await makeGrpcBuildClient(client);\n\n let paymentDigest: string | undefined;\n let gasCostSui = 0;\n // The real amount charged on-chain is the 402 challenge price (a decimal\n // USDC string like \"0.01\"), NOT the caller's `maxPrice` ceiling (Bug 1,\n // dogfood 2026-05-31). Capture it in `onChallenge` — and enforce the\n // ceiling THERE, before any credential is created: the header dialect pays\n // client-side, so this hook is the last stop before money moves.\n let chargedAmount: number | undefined;\n\n const mppx = Mppx.create({\n polyfill: false,\n onChallenge: async (challenge: { request?: { amount?: unknown } }) => {\n const parsed = parseChallengeAmount(challenge);\n if (parsed !== undefined) {\n chargedAmount = parsed;\n assertWithinMaxPrice(parsed, options.maxPrice);\n }\n return undefined;\n },\n methods: [\n sui({\n client,\n currency: network === 'testnet' ? USDC_TESTNET : USDC,\n signer: {\n toSuiAddress: () => signerAddress,\n signPersonalMessage: (bytes: Uint8Array) => signer.signPersonalMessage(bytes),\n } as unknown as Parameters<typeof sui>[0]['signer'],\n execute: async (tx) => {\n const result = await executeTx(client, signer, () => tx, { buildClient: grpcClient });\n paymentDigest = result.digest;\n gasCostSui = result.gasCostSui;\n return { digest: result.digest };\n },\n }),\n ],\n });\n\n const method = (options.method ?? 'GET').toUpperCase();\n const canHaveBody = method !== 'GET' && method !== 'HEAD';\n\n const response = await mppx.fetch(options.url, {\n method,\n headers: options.headers,\n body: canHaveBody ? options.body : undefined,\n });\n\n const paid = !!paymentDigest;\n const result = await finalize(response, { paid });\n if (!paid) return { ...result, dialect: 'legacy' };\n return {\n ...result,\n dialect: 'legacy',\n cost: chargedAmount ?? options.maxPrice ?? undefined,\n gasCostSui,\n receipt: paymentDigest\n ? { reference: paymentDigest, timestamp: new Date().toISOString() }\n : undefined,\n };\n}\n\n/** Throw `PRICE_EXCEEDS_LIMIT` when the challenge price exceeds the caller's\n * `maxPrice` ceiling (no ceiling = pay whatever the 402 asks). */\nfunction assertWithinMaxPrice(price: number, maxPrice: number | undefined): void {\n if (maxPrice !== undefined && price > maxPrice) {\n throw new T2000Error(\n 'PRICE_EXCEEDS_LIMIT',\n `Service price $${price} exceeds maxPrice ceiling $${maxPrice}`,\n { price, maxPrice },\n );\n }\n}\n\n/**\n * Ensure the sender's SIP-58 address balance covers `amountRaw` of `asset`.\n * Returns the SUI gas spent migrating (0 when no migration was needed or the\n * migration was gasless). Throws `INSUFFICIENT_BALANCE` when the wallet\n * doesn't hold enough of the asset at all (coins + address balance combined).\n */\nasync function ensureAddressBalanceCovers(args: {\n signer: TransactionSigner;\n client: SuiGrpcClient;\n asset: string;\n amountRaw: bigint;\n}): Promise<number> {\n const { signer, client, asset, amountRaw } = args;\n const owner = signer.getAddress();\n\n // total = coins + address balance (the canonical combined read)\n const balanceResp = await client.core.getBalance({ owner, coinType: asset });\n const total = BigInt(balanceResp.balance.balance);\n if (total < amountRaw) {\n throw new T2000Error('INSUFFICIENT_BALANCE', `Insufficient ${asset} to pay`, {\n available: total.toString(),\n required: amountRaw.toString(),\n });\n }\n\n // address balance = total − discrete coin-object sum (listCoins excludes AB).\n // Collect the coin objects too — we reuse them to build the migration.\n const coins: { objectId: string; balance: bigint }[] = [];\n let coinSum = 0n;\n let cursor: string | null | undefined;\n let hasNext = true;\n while (hasNext) {\n const page = await client.core.listCoins({ owner, coinType: asset, cursor: cursor ?? undefined });\n for (const c of page.objects) {\n coins.push({ objectId: c.objectId, balance: BigInt(c.balance) });\n coinSum += BigInt(c.balance);\n }\n cursor = page.cursor;\n hasNext = page.hasNextPage;\n }\n const addressBalance = total - coinSum;\n if (addressBalance >= amountRaw) return 0; // address balance already covers it\n\n // Move the shortfall from coin objects into the address balance by sending\n // WHOLE coin objects to self via `0x2::coin::send_funds` — one allowlisted\n // framework MoveCall per coin, NO native merge/split. Built on the gRPC\n // client so its resolver detects the all-allowlisted-MoveCall shape and zeros\n // gas: the migration itself is gasless (the same eligibility the x402\n // withdrawal + the gasless send rely on). The old merge+split+send shape had\n // native `SplitCoins`/`MergeCoins` commands → fell outside the allowlist →\n // forced SUI gas, breaking coin-object holders with 0 SUI.\n const shortfall = amountRaw - addressBalance;\n const { buildCoinToAddressBalanceMigration } = await import('./coinSelection.js');\n const grpcClient = await makeGrpcBuildClient(client);\n const { tx } = buildCoinToAddressBalanceMigration({ coins, coinType: asset, owner, minAmount: shortfall });\n const migration = await executeTx(client, signer, () => tx, { buildClient: grpcClient });\n return migration.gasCostSui;\n}\n\n// ---------------------------------------------------------------------------\n// Shared helpers\n// ---------------------------------------------------------------------------\n\n/** Cheap \"is this JSON?\" check — parse, don't guess from the first char. */\nfunction isJsonText(text: string): boolean {\n try {\n JSON.parse(text);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Case-insensitive content-type presence check on a plain header record. */\nfunction hasContentType(headers: Record<string, string> | undefined): boolean {\n if (!headers) return false;\n return Object.keys(headers).some((k) => k.toLowerCase() === 'content-type');\n}\n\n/** Read the response body (json or text) and assemble the base PayResult. */\nasync function finalize(response: Response, opts: { paid: boolean }): Promise<PayResult> {\n const contentType = response.headers.get('content-type') ?? '';\n let body: unknown;\n try {\n body = contentType.includes('application/json') ? await response.json() : await response.text();\n } catch {\n body = null;\n }\n return { status: response.status, body, paid: opts.paid };\n}\n\n/** A gRPC client for tx BUILD — its resolver auto-detects the gasless\n * stablecoin shape (gasPrice/gasBudget/gasPayment zeroed). */\nasync function makeGrpcBuildClient(client: SuiGrpcClient): Promise<SuiGrpcClient> {\n const { SuiGrpcClient } = await import('@mysten/sui/grpc');\n const network: 'mainnet' | 'testnet' = client.network === 'testnet' ? 'testnet' : 'mainnet';\n const baseUrl =\n network === 'testnet' ? 'https://fullnode.testnet.sui.io' : 'https://fullnode.mainnet.sui.io';\n return new SuiGrpcClient({ baseUrl, network });\n}\n\nfunction atomicToHuman(raw: bigint, decimals: number): number {\n return Number(raw) / 10 ** decimals;\n}\n\nasync function assetDecimals(coinType: string): Promise<number> {\n try {\n const { getDecimalsForCoinType } = await import('../token-registry.js');\n const d = getDecimalsForCoinType(coinType);\n return typeof d === 'number' ? d : 6;\n } catch {\n return 6;\n }\n}\n","/**\n * MPP cost extraction — the truthful-`cost` fix (Bug 1, dogfood 2026-05-31).\n *\n * `T2000.pay()` used to report `options.maxPrice` (the caller's ceiling, default\n * 1.0 in MCP) as the `cost`, wildly overstating the real charge. The real\n * amount is the 402 challenge price, a decimal USDC string like \"0.01\" carried\n * on `challenge.request.amount`. mppx surfaces the parsed challenge via its\n * `onChallenge` hook; this pure helper pulls the amount out so the extraction\n * is unit-testable in isolation (the ordering/format invariant can't silently\n * regress).\n */\n\n/** Minimal structural view of an mppx payment challenge. */\nexport type MppChallenge = { request?: { amount?: unknown } } | null | undefined;\n\n/**\n * Parse the charged amount (USD) from a payment challenge. Returns `undefined`\n * when the challenge has no usable numeric amount, so callers can fall back to\n * the `maxPrice` ceiling rather than reporting a wrong number.\n */\nexport function parseChallengeAmount(challenge: MppChallenge): number | undefined {\n const raw = challenge?.request?.amount;\n const n =\n typeof raw === 'string' ? Number(raw) : typeof raw === 'number' ? raw : Number.NaN;\n return Number.isFinite(n) ? n : undefined;\n}\n","import type { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';\nimport type { TransactionSigner } from '../signer.js';\n\nexport interface ZkLoginProof {\n proofPoints: {\n a: string[];\n b: string[][];\n c: string[];\n };\n issBase64Details: {\n indexMod4: number;\n value: string;\n };\n headerBase64: string;\n addressSeed: string;\n}\n\nexport class ZkLoginSigner implements TransactionSigner {\n readonly kind = 'zklogin' as const;\n\n constructor(\n private readonly ephemeralKeypair: Ed25519Keypair,\n private readonly zkProof: ZkLoginProof,\n private readonly userAddress: string,\n private readonly maxEpoch: number,\n ) {}\n\n getAddress(): string {\n return this.userAddress;\n }\n\n async signTransaction(txBytes: Uint8Array): Promise<{ signature: string }> {\n const { getZkLoginSignature } = await import('@mysten/zklogin');\n const ephSig = await this.ephemeralKeypair.signTransaction(txBytes);\n return {\n signature: getZkLoginSignature({\n inputs: this.zkProof,\n maxEpoch: this.maxEpoch,\n userSignature: ephSig.signature,\n }),\n };\n }\n\n async signPersonalMessage(messageBytes: Uint8Array): Promise<{ signature: string; bytes: string }> {\n const { getZkLoginSignature } = await import('@mysten/zklogin');\n const { signature: ephSig, bytes } = await this.ephemeralKeypair.signPersonalMessage(messageBytes);\n return {\n signature: getZkLoginSignature({\n inputs: this.zkProof,\n maxEpoch: this.maxEpoch,\n userSignature: ephSig,\n }),\n bytes,\n };\n }\n\n isExpired(currentEpoch: number): boolean {\n return currentEpoch >= this.maxEpoch;\n }\n}\n","import {\n Transaction,\n type TransactionObjectArgument,\n} from '@mysten/sui/transactions';\nimport {\n GASLESS_MIN_STABLE_AMOUNT,\n GASLESS_STABLE_TYPES,\n SUPPORTED_ASSETS,\n assertAllowedAsset,\n type SendableAsset,\n} from '../constants.js';\nimport { T2000Error } from '../errors.js';\nimport { validateAddress, type SuiCoreClient } from '../utils/sui.js';\nimport { displayToRaw } from '../utils/format.js';\nimport {\n type PreflightResult,\n PREFLIGHT_OK,\n preflightFail,\n checkPositiveAmount,\n checkSuiAddress,\n} from '../preflight.js';\n\n/**\n * Synchronous, network-free preflight for `send`. Validates asset membership,\n * amount sanity, the gasless stable floor, and recipient address shape — the\n * cheap checks the v3 host runs before the LLM round-trip / tap-to-confirm.\n * Returns a `PreflightResult`; never throws. `buildSendTx` calls this first,\n * then layers the network balance read on top.\n */\nexport function preflightSend(input: {\n to: string;\n amount: number;\n asset: string;\n}): PreflightResult {\n // Asset membership — reuse the canonical message (single source of truth).\n try {\n assertAllowedAsset('send', input.asset);\n } catch (e) {\n return preflightFail('INVALID_ASSET', (e as T2000Error).message);\n }\n\n const amountCheck = checkPositiveAmount(input.amount);\n if (!amountCheck.valid) return amountCheck;\n\n // Gasless protocol allowlist enforces a 0.01 minimum on the stables.\n if (\n (input.asset === 'USDC' || input.asset === 'USDsui') &&\n input.amount < GASLESS_MIN_STABLE_AMOUNT\n ) {\n return preflightFail(\n 'INVALID_AMOUNT',\n `Minimum gasless transfer is ${GASLESS_MIN_STABLE_AMOUNT} ${input.asset}. Got ${input.amount}.`,\n );\n }\n\n const addressCheck = checkSuiAddress(input.to);\n if (!addressCheck.valid) return addressCheck;\n\n return PREFLIGHT_OK;\n}\n\n/**\n * Build a PTB that sends `amount` of `asset` from `address` to `to`.\n *\n * [v4.0 Phase A Day 2 — SPEC_AGENT_WALLET_GREENFIELD §A]\n *\n * Asset constraint: `'USDC' | 'USDsui' | 'SUI'` only. Other assets throw\n * `INVALID_ASSET` via `assertAllowedAsset('send', asset)`. The constrained\n * set matches Sui mainnet's gasless allowlist (USDC + USDsui) plus SUI\n * for users who want a gas-native transfer.\n *\n * Build paths:\n * - **USDC / USDsui** — `0x2::balance::send_funds` Move call with a\n * `tx.balance({ type, balance })` input. When built via `SuiGrpcClient`,\n * the gRPC resolver auto-detects gasless eligibility and zeros gas.\n * When built via `SuiJsonRpcClient`, the same PTB still executes but\n * the caller pays normal gas. Minimum 0.01 (protocol allowlist floor).\n * - **SUI** — `tx.splitCoins(tx.gas, [amount]) → tx.transferObjects()`.\n * Standard gas-native transfer. No minimum.\n *\n * Pre-flight balance check stays on JSON-RPC (`client.getBalance`) — it\n * sums coin objects + address balance so the legacy `getCoins` page miss\n * doesn't break for users whose stables landed via gasless deposits.\n *\n * `asset` is REQUIRED (no implicit USDC default — pre-v4 hid LLM intent\n * errors). Callers passing the wrong asset get an explicit error rather\n * than a silent currency substitution.\n */\nexport async function buildSendTx({\n client,\n address,\n to,\n amount,\n asset,\n}: {\n client: SuiCoreClient;\n address: string;\n to: string;\n amount: number;\n asset: SendableAsset;\n}): Promise<Transaction> {\n // Layer 2 — cheap synchronous preflight (asset / amount / gasless floor /\n // recipient shape). Rethrow the precise code+message verbatim.\n const pf = preflightSend({ to, amount, asset });\n if (!pf.valid) throw new T2000Error(pf.code, pf.error);\n\n const recipient = validateAddress(to);\n const assetInfo = SUPPORTED_ASSETS[asset];\n if (!assetInfo) throw new T2000Error('ASSET_NOT_SUPPORTED', `Asset ${asset} is not supported`);\n\n const rawAmount = displayToRaw(amount, assetInfo.decimals);\n const tx = new Transaction();\n tx.setSender(address);\n\n // Balance pre-flight against `core.getBalance().balance.balance` (sums\n // coins + address balance). The legacy `getCoins` page miss broke for\n // users whose stables had drifted into address balance via @suimpp/mpp 0.7+.\n const balanceResp = await client.core.getBalance({ owner: address, coinType: assetInfo.type });\n const totalBalance = BigInt(balanceResp.balance.balance);\n if (totalBalance < rawAmount) {\n throw new T2000Error('INSUFFICIENT_BALANCE', `Insufficient ${asset} balance`, {\n available: Number(totalBalance) / 10 ** assetInfo.decimals,\n required: amount,\n });\n }\n\n if (asset === 'SUI') {\n // Standard gas-native transfer — split from the gas coin, transfer\n // the resulting object. NOT gasless (SUI is not on the protocol\n // allowlist for `balance::send_funds`).\n const [sendCoin] = tx.splitCoins(tx.gas, [rawAmount]);\n tx.transferObjects([sendCoin], recipient);\n return tx;\n }\n\n // USDC / USDsui — gasless via `0x2::balance::send_funds`. The gRPC\n // build resolver inspects this PTB shape at `tx.build()` time and,\n // when it matches the protocol allowlist, sets gasPrice=0/gasBudget=0\n // automatically. The Move signature is:\n // public fun send_funds<T>(balance: Balance<T>, recipient: address)\n // `tx.balance({ type, balance })` produces a Balance<T> input sourced\n // from the sender's address balance + coin objects (auto-merged).\n const coinType = GASLESS_STABLE_TYPES[asset];\n tx.moveCall({\n target: '0x2::balance::send_funds',\n typeArguments: [coinType],\n arguments: [\n tx.balance({ type: coinType, balance: rawAmount }),\n tx.pure.address(recipient),\n ],\n });\n return tx;\n}\n\n/**\n * Fragment-appender for the chain-mode send leg of SPEC 7 multi-write\n * Payment Intents. Consumes a coin reference produced by a previous\n * appender (e.g. `addWithdrawToTx`, `addSwapToTx`) and transfers it to\n * `recipient` within the same Payment Intent — no intermediate wallet\n * materialization.\n *\n * Codifies the hand-built send leg from\n * `scripts/smoke-spec7-withdraw-then-send.ts` (P2.1) into a typed\n * appender. SPEC 7 § \"Layer 1\" — P2.2b will register this in the\n * `WRITE_APPENDER_REGISTRY` under `send_transfer` for chain-mode\n * dispatch; the registry adapter will handle the wallet-fetch fallback\n * by delegating to `buildSendTx` when no upstream coin is available.\n *\n * For single-step send_transfer flows (no chained predecessor), use\n * `buildSendTx` directly — it builds a complete tx including the\n * wallet-coin selection / merge / split prelude.\n *\n * [v4.0 Phase A Day 2] Stays on the legacy `transferObjects` path\n * because chain-mode bundles are NEVER gasless — by definition they\n * combine multiple Move calls (`withdraw → send`, `swap → send`) which\n * fail the protocol allowlist check (only `balance::send_funds` and\n * a few related helpers are eligible). The bundled flow still works,\n * the user just pays gas (or has it sponsored by audric via Enoki).\n *\n * @returns void — the coin is consumed by `tx.transferObjects`. Callers\n * that need the post-transfer \"effective amount\" should rely on the\n * upstream appender's `effectiveAmount` (e.g. `addWithdrawToTx`'s\n * return), not on this appender.\n */\nexport function addSendToTx(\n tx: Transaction,\n coin: TransactionObjectArgument,\n recipient: string,\n): void {\n const validRecipient = validateAddress(recipient);\n tx.transferObjects([coin], validRecipient);\n}\n","import { MIST_PER_SUI, USDC_DECIMALS, SUPPORTED_ASSETS } from '../constants.js';\nimport type { SupportedAsset } from '../constants.js';\n\nexport function mistToSui(mist: bigint): number {\n return Number(mist) / Number(MIST_PER_SUI);\n}\n\nexport function suiToMist(sui: number): bigint {\n return BigInt(Math.round(sui * Number(MIST_PER_SUI)));\n}\n\nexport function usdcToRaw(amount: number): bigint {\n return BigInt(Math.round(amount * 10 ** USDC_DECIMALS));\n}\n\nexport function rawToUsdc(raw: bigint): number {\n return Number(raw) / 10 ** USDC_DECIMALS;\n}\n\nexport function stableToRaw(amount: number, decimals: number): bigint {\n return BigInt(Math.round(amount * 10 ** decimals));\n}\n\nexport function rawToStable(raw: bigint, decimals: number): number {\n return Number(raw) / 10 ** decimals;\n}\n\nexport function getDecimals(asset: SupportedAsset): number {\n return SUPPORTED_ASSETS[asset].decimals;\n}\n\nexport function rawToDisplay(raw: bigint, decimals: number): number {\n return Number(raw) / 10 ** decimals;\n}\n\nexport function displayToRaw(amount: number, decimals: number): bigint {\n return BigInt(Math.round(amount * 10 ** decimals));\n}\n\nexport function formatUsd(amount: number): string {\n return `$${amount.toFixed(2)}`;\n}\n\nexport function formatSui(amount: number): string {\n if (amount < 0.001) return `${amount.toFixed(6)} SUI`;\n return `${amount.toFixed(3)} SUI`;\n}\n\nexport function formatLargeNumber(n: number): string {\n if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;\n if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;\n return n.toFixed(2);\n}\n\nexport function formatAssetAmount(amount: number, asset: string): string {\n if (asset === 'BTC') return amount.toFixed(8);\n if (asset === 'GOLD') return amount.toFixed(6);\n if (asset === 'ETH') return amount.toFixed(6);\n return amount.toFixed(4);\n}\n\nconst ASSET_LOOKUP: Map<string, string> = new Map();\nfor (const [key, info] of Object.entries(SUPPORTED_ASSETS)) {\n ASSET_LOOKUP.set(key.toUpperCase(), key);\n if (info.displayName && info.displayName.toUpperCase() !== key.toUpperCase()) {\n ASSET_LOOKUP.set(info.displayName.toUpperCase(), key);\n }\n}\n\n/**\n * Case-insensitive lookup against SUPPORTED_ASSETS keys AND display names.\n * 'usde' → 'USDe', 'suiusde' → 'USDe', 'suiusdt' → 'USDT', 'usdsui' → 'USDsui'.\n * Returns the original input if not found so downstream validation can reject it.\n */\nexport function normalizeAsset(input: string): string {\n return ASSET_LOOKUP.get(input.toUpperCase()) ?? input;\n}\n","import { normalizeStructTag } from '@mysten/sui/utils';\nimport { SUPPORTED_ASSETS, STABLE_ASSETS, MIST_PER_SUI, CETUS_USDC_SUI_POOL } from '../constants.js';\nimport type { StableAsset } from '../constants.js';\nimport { resolveSymbol, resolveCoinDecimals } from '../token-registry.js';\nimport type { SuiCoreClient } from '../utils/sui.js';\nimport type { BalanceResponse, TokenHolding } from '../types.js';\n\nconst SUI_PRICE_FALLBACK = 1.0;\nlet _cachedSuiPrice = 0;\nlet _priceLastFetched = 0;\nconst PRICE_CACHE_TTL_MS = 60_000;\n\n/**\n * Fetch SUI price in USD from the Cetus USDC/SUI pool's sqrt_price.\n *\n * Pool is Pool<USDC, SUI> so coin_a = USDC (6 dec), coin_b = SUI (9 dec).\n * current_sqrt_price (Q64 fixed-point) encodes sqrt(raw_price) where\n * raw_price = SUI_raw / USDC_raw.\n *\n * USDC per SUI = 10^(decimals_a - decimals_b) / raw_price\n * = 10^(6-9) / raw_price\n * = 1 / (raw_price * 1000)\n *\n * Equivalently: 1000 / raw_price\n */\nasync function fetchSuiPrice(client: SuiCoreClient): Promise<number> {\n const now = Date.now();\n if (_cachedSuiPrice > 0 && now - _priceLastFetched < PRICE_CACHE_TTL_MS) {\n return _cachedSuiPrice;\n }\n\n try {\n // [gRPC migration] `core.getObject` returns BCS content; request `json`\n // to read parsed Move fields (the legacy `content.fields` path is gone).\n const pool = await client.core.getObject({\n objectId: CETUS_USDC_SUI_POOL,\n include: { json: true },\n });\n\n const fields = pool.object?.json as Record<string, unknown> | null | undefined;\n if (fields) {\n const currentSqrtPrice = BigInt(String(fields.current_sqrt_price ?? '0'));\n\n if (currentSqrtPrice > 0n) {\n const Q64 = 2n ** 64n;\n const sqrtPriceFloat = Number(currentSqrtPrice) / Number(Q64);\n const rawPrice = sqrtPriceFloat * sqrtPriceFloat;\n const price = 1000 / rawPrice;\n if (price > 0.01 && price < 1000) {\n _cachedSuiPrice = price;\n _priceLastFetched = now;\n }\n }\n }\n } catch {\n // Use cached/fallback price\n }\n\n return _cachedSuiPrice || SUI_PRICE_FALLBACK;\n}\n\nfunction safeNorm(coinType: string): string {\n try {\n return normalizeStructTag(coinType);\n } catch {\n return coinType;\n }\n}\n\nconst SUI_TYPE_NORM = safeNorm(SUPPORTED_ASSETS.SUI.type);\nconst STABLE_BY_NORM: Record<string, StableAsset> = (() => {\n const m: Record<string, StableAsset> = {};\n for (const asset of STABLE_ASSETS) m[safeNorm(SUPPORTED_ASSETS[asset].type)] = asset;\n return m;\n})();\n\n/**\n * Full wallet balance: **every** held coin, not just the curated stables + SUI.\n *\n * Uses one `listBalances` (paginated) instead of N `getBalance` calls, then\n * partitions: stables → priced $1, SUI → Cetus-oracle priced, **everything else\n * → `tokens[]` amount-only** (`usdValue: null` — no price oracle for arbitrary\n * tokens; we don't guess). Decimals for non-registry tokens are read on-chain\n * (the only added call, and only for tokens you actually hold — necessary for a\n * correct amount). `totalUsd` sums **priced holdings only** so it never\n * overstates; `tokens` surfaces the rest honestly.\n */\nexport async function queryBalance(\n client: SuiCoreClient,\n address: string,\n): Promise<BalanceResponse> {\n const held: Array<{ coinType: string; raw: bigint }> = [];\n let cursor: string | null | undefined;\n do {\n const page = await client.core.listBalances({ owner: address, cursor: cursor ?? undefined });\n for (const b of page.balances) {\n const raw = BigInt(b.balance);\n if (raw > 0n) held.push({ coinType: b.coinType, raw });\n }\n cursor = page.hasNextPage ? page.cursor : null;\n } while (cursor);\n\n const suiPriceUsd = await fetchSuiPrice(client);\n\n const stables = {} as Record<StableAsset, number>;\n for (const asset of STABLE_ASSETS) stables[asset] = 0;\n let totalStables = 0;\n let suiAmount = 0;\n const otherCoins: Array<{ coinType: string; raw: bigint }> = [];\n\n for (const { coinType, raw } of held) {\n const norm = safeNorm(coinType);\n if (norm === SUI_TYPE_NORM) {\n suiAmount = Number(raw) / Number(MIST_PER_SUI);\n } else if (STABLE_BY_NORM[norm]) {\n const asset = STABLE_BY_NORM[norm];\n const amount = Number(raw) / 10 ** SUPPORTED_ASSETS[asset].decimals;\n stables[asset] = amount;\n totalStables += amount;\n } else {\n otherCoins.push({ coinType, raw });\n }\n }\n\n // Non-stable, non-SUI holdings — amount-only (no price oracle). Decimals come\n // from the registry (no call) or on-chain coin metadata (unknown tokens only).\n const tokens: TokenHolding[] = await Promise.all(\n otherCoins.map(async ({ coinType, raw }) => {\n const decimals = await resolveCoinDecimals(client, coinType);\n return {\n coinType,\n symbol: resolveSymbol(coinType),\n amount: Number(raw) / 10 ** decimals,\n usdValue: null,\n };\n }),\n );\n tokens.sort((a, b) => a.symbol.localeCompare(b.symbol));\n\n const suiUsdValue = suiAmount * suiPriceUsd;\n\n return {\n stables,\n available: totalStables,\n sui: { amount: suiAmount, usdValue: suiUsdValue },\n tokens,\n totalUsd: totalStables + suiUsdValue,\n };\n}\n","/**\n * Shared transaction classifier.\n *\n * Consumed by both the SDK's `parseTxRecord` (production agent path) and\n * the engine's `transaction_history` tool (cold-start RPC path). Keeping\n * a single source of truth here prevents the two paths from drifting —\n * see v1.5.3 regression where the SDK path was emitting `action:\n * 'transaction'` (rendered as \"On-chain\") while the engine path was\n * already producing fine-grained labels.\n */\n\nimport { getDecimalsForCoinType, resolveSymbol, SUI_TYPE } from '../token-registry.js';\n\n/**\n * Coarse action bucket — one of `'send' | 'lending' | 'swap' |\n * 'transaction'`. Used by the ACI `action` filter on the\n * `transaction_history` tool. STABLE: downstream queries depend on\n * exactly these values.\n *\n * Order matters: more specific buckets first. Lending patterns precede\n * swap patterns so a NAVI `::swap` helper (if one ever existed) would\n * still bucket as lending.\n */\nexport const KNOWN_TARGETS: readonly [RegExp, string][] = [\n [/::suilend|::obligation/, 'lending'],\n [/::navi|::lending_core|::incentive_v\\d+|::oracle_pro/, 'lending'],\n /**\n * DEX modules — both direct calls and aggregator legs. The Cetus\n * aggregator dispatches through a per-DEX module (e.g.\n * `cetus::swap`, `flowx_amm::swap`, `aftermath::swap`, …) plus\n * router glue functions. We list every DEX module the aggregator\n * supports today so a single-DEX call still classifies cleanly.\n */\n [/::cetus(?:_dlmm)?::|::pool::|::deepbook|::flowx_(?:amm|clmm)::|::kriya_(?:amm|clmm)::|::turbos::|::aftermath::|::afsui::|::bluefin::|::bluemove::|::ferra_(?:clmm|dlmm)::|::haedal_hmm::|::hasui::|::hawal::|::magma::|::momentum::|::obric::|::springsui::|::steamm_cpmm::|::fullsail::|::alphafi::|::volo_swap::/, 'swap'],\n /**\n * Cetus aggregator router glue. These are the swap-context and\n * balance-handling helpers the aggregator emits around per-DEX\n * legs. Without this entry a tx that ONLY had router calls\n * (theoretically possible for setup/cleanup) would slip through;\n * in practice these always coexist with a DEX leg, but the entry\n * is cheap insurance.\n */\n [/::router::(?:new_swap_context(?:_v)?|confirm_swap|transfer_balance|take_balance|transfer_or_destroy_coin)/, 'swap'],\n [/::transfer::public_transfer/, 'send'],\n];\n\n/**\n * Finer-grained display labels — derived from MoveCall function names.\n * The card renders `label ?? action`, so when this map matches we get\n * \"Deposit\" / \"Withdraw\" / \"Borrow\" / \"Repay\" / \"Payment link\" instead\n * of the generic \"Lending\" or \"Transaction\".\n *\n * Order matters: more specific patterns first. Each entry is\n * (regex, label) where the regex is matched against the\n * fully-qualified MoveCall target `pkg::module::function`.\n */\nexport const LABEL_PATTERNS: readonly [RegExp, string][] = [\n [/::pay(?:ment_kit|_kit)?::|::create_payment_link|::pay_link/, 'payment_link'],\n [/::create_invoice|::invoice::/, 'invoice'],\n [/::deposit|::supply|::mint_ctokens/, 'deposit'],\n [/::withdraw|::redeem|::redeem_ctokens/, 'withdraw'],\n [/::borrow/, 'borrow'],\n [/::repay/, 'repay'],\n [/::claim_reward|::claim::|::claim_incentive/, 'claim'],\n [/::stake/, 'stake'],\n [/::unstake|::burn::/, 'unstake'],\n [/::liquidate/, 'liquidate'],\n];\n\nexport interface ClassifyBalanceChange {\n owner: { AddressOwner?: string } | string;\n coinType: string;\n amount: string;\n}\n\nfunction resolveOwner(owner: ClassifyBalanceChange['owner']): string | null {\n if (typeof owner === 'object' && owner.AddressOwner) return owner.AddressOwner;\n if (typeof owner === 'string') return owner;\n return null;\n}\n\nexport function classifyAction(targets: string[], commandTypes: string[]): string {\n for (const target of targets) {\n for (const [pattern, label] of KNOWN_TARGETS) {\n if (pattern.test(target)) return label;\n }\n }\n if (commandTypes.includes('TransferObjects') && !commandTypes.includes('MoveCall')) return 'send';\n return 'transaction';\n}\n\n/**\n * Last-resort fallback when neither `LABEL_PATTERNS` nor the action\n * bucket produces something useful.\n *\n * Returns the first MoveCall's *module* name (e.g. \"navi\", \"spam\") so\n * the card shows something better than the literal word \"transaction\".\n * When no MoveCall exists, returns 'on-chain'.\n *\n * Note: callers should prefer `classifyLabel` which now layers\n * pattern-match → coarse action → module name (see commentary there).\n */\nexport function fallbackLabel(targets: string[]): string {\n if (!targets.length) return 'on-chain';\n const first = targets[0];\n const parts = first.split('::');\n if (parts.length >= 2 && parts[1]) return parts[1].toLowerCase();\n return 'on-chain';\n}\n\n/**\n * Three-tier label resolution for the transaction history card:\n * 1. Specific keyword match in `LABEL_PATTERNS` (\"deposit\",\n * \"payment_link\", …).\n * 2. Coarse action bucket from `classifyAction` (\"swap\", \"send\",\n * \"lending\") — prevents leaking opaque internal module names like\n * \"router\" (Cetus aggregator) or \"cross_swap\" (third-party DEX\n * aggregators) for txs that we already classified as a swap.\n * 3. Module name from the first MoveCall (`fallbackLabel`) — only\n * used when the action bucket itself is the generic \"transaction\".\n *\n * Pre-v0.46.2 we skipped tier 2, so swaps showed labels like \"router\",\n * \"cross_swap\", \"scallop_router\", etc. instead of the clean \"swap\".\n */\nexport function classifyLabel(targets: string[], commandTypes: string[]): string {\n for (const target of targets) {\n for (const [pattern, label] of LABEL_PATTERNS) {\n if (pattern.test(target)) return label;\n }\n }\n if (commandTypes.includes('TransferObjects') && !commandTypes.includes('MoveCall')) return 'send';\n const action = classifyAction(targets, commandTypes);\n if (action !== 'transaction') return action;\n return fallbackLabel(targets);\n}\n\n/**\n * Balance-direction tiebreaker for ambiguous lending calls.\n *\n * Many lending modules expose generic entry points (NAVI's bundled\n * flash actions, `lending_core::*::entry_*`, etc.) that don't carry\n * a `deposit`/`withdraw`/`borrow`/`repay` keyword in the function\n * name. When `classifyLabel` falls back to a bare module name like\n * `\"lending\"` for a known lending tx, infer direction from the user's\n * non-SUI balance change:\n * - net outflow of the supplied asset → deposit (also covers repay,\n * but repay-without-keyword is essentially never emitted).\n * - net inflow of the supplied asset → withdraw (also covers borrow).\n * SUI is excluded so gas-only transactions don't get mislabeled.\n *\n * If `LABEL_PATTERNS` matched a specific keyword, the existing label is\n * returned unchanged.\n */\nexport function refineLendingLabel(\n currentAction: string,\n currentLabel: string,\n moveCallTargets: string[],\n changes: ClassifyBalanceChange[],\n address: string,\n): string {\n if (currentAction !== 'lending') return currentLabel;\n const labelMatchedSpecific = LABEL_PATTERNS.some(([p]) =>\n moveCallTargets.some((t) => p.test(t)),\n );\n if (labelMatchedSpecific) return currentLabel;\n\n const userNonSuiOutflow = changes.find(\n (c) => resolveOwner(c.owner) === address && c.coinType !== SUI_TYPE && BigInt(c.amount) < 0n,\n );\n if (userNonSuiOutflow) return 'deposit';\n\n const userNonSuiInflow = changes.find(\n (c) => resolveOwner(c.owner) === address && c.coinType !== SUI_TYPE && BigInt(c.amount) > 0n,\n );\n if (userNonSuiInflow) return 'withdraw';\n\n return currentLabel;\n}\n\nexport interface ClassifyResult {\n action: string;\n label: string;\n}\n\nexport function classifyTransaction(\n moveCallTargets: string[],\n commandTypes: string[],\n balanceChanges: ClassifyBalanceChange[],\n address: string,\n): ClassifyResult {\n const action = classifyAction(moveCallTargets, commandTypes);\n const baseLabel = classifyLabel(moveCallTargets, commandTypes);\n const label = refineLendingLabel(action, baseLabel, moveCallTargets, balanceChanges, address);\n return { action, label };\n}\n\n/**\n * Direction of the user's net non-gas movement for this transaction.\n *\n * - `'out'` — the user spent the asset (sends, deposits, repays,\n * swap-in, payment-link payouts).\n * - `'in'` — the user received the asset (withdraws, borrows,\n * swap-out, claims, deposits credited from another wallet).\n *\n * Used by the `TransactionHistoryCard` to choose the `+`/`−` sign and\n * color. Direction is computed from the actual on-chain balance change\n * — never from the textual label — so opaque action types (`'router'`,\n * `'cross_swap'`, …) still render the correct sign.\n */\nexport type TxDirection = 'in' | 'out';\n\nexport interface ExtractedTransfer {\n amount?: number;\n asset?: string;\n recipient?: string;\n direction?: TxDirection;\n}\n\n/**\n * Extracts the principal amount/asset/direction for a transaction\n * from its `balanceChanges`.\n *\n * Algorithm:\n * 1. Restrict to the user's *own* balance changes.\n * 2. Prefer non-SUI changes (gas-only SUI deltas are noise).\n * 3. Pick the change with the largest absolute value — the \"principal\".\n * 4. If no non-SUI change exists, fall back to the largest SUI change\n * so pure-SUI transfers (stake/unstake/native send) still render.\n * 5. Direction follows the sign of the principal.\n * 6. Recipient is set only on outflows, by finding a matching inflow\n * on a *non-user* address with the same coinType.\n *\n * Pre-v0.46.2 this function only inspected outflows, so withdraws,\n * borrows, claims, swap-receives and payment-link receives all\n * rendered with no amount on the rich card (and with a wrong sign,\n * because the card guessed direction from the label string).\n */\nexport function extractTransferDetails(\n changes: ClassifyBalanceChange[] | undefined,\n sender: string,\n): ExtractedTransfer {\n if (!changes || changes.length === 0) return {};\n\n const userChanges = changes.filter((c) => resolveOwner(c.owner) === sender);\n if (userChanges.length === 0) return {};\n\n const userNonSui = userChanges.filter((c) => c.coinType !== SUI_TYPE);\n const pool = userNonSui.length > 0 ? userNonSui : userChanges;\n\n let primary = pool[0];\n let primaryAbs = bigintAbs(BigInt(primary.amount));\n for (let i = 1; i < pool.length; i++) {\n const abs = bigintAbs(BigInt(pool[i].amount));\n if (abs > primaryAbs) {\n primary = pool[i];\n primaryAbs = abs;\n }\n }\n\n const raw = BigInt(primary.amount);\n if (raw === 0n) return {};\n\n const decimals = getDecimalsForCoinType(primary.coinType);\n const amount = Number(primaryAbs) / 10 ** decimals;\n const asset = resolveSymbol(primary.coinType);\n const direction: TxDirection = raw < 0n ? 'out' : 'in';\n\n let recipient: string | undefined;\n if (direction === 'out') {\n const recipientChange = changes.find(\n (c) =>\n resolveOwner(c.owner) !== sender &&\n c.coinType === primary.coinType &&\n BigInt(c.amount) > 0n,\n );\n recipient = recipientChange ? resolveOwner(recipientChange.owner) ?? undefined : undefined;\n }\n\n return { amount, asset, recipient, direction };\n}\n\nfunction bigintAbs(n: bigint): bigint {\n return n < 0n ? -n : n;\n}\n\n/**\n * Extract every non-zero user balance leg for a transaction — not\n * just the largest one. Order is RPC order; callers responsible for\n * any sorting (e.g. audric sorts by USD value once it's priced).\n *\n * Sui collapses balance changes by coin type, so a 3-step bundle\n * touching USDC three times surfaces as ONE leg of net USDC delta.\n * Distinguishing per-step legs would require parsing the PTB's\n * commands; this helper deliberately stops at the balance-change\n * granularity because that's what's reliably available across all\n * Sui RPC versions.\n *\n * Pre-v1.27.2 the only public API was `extractTransferDetails`,\n * which returned a single \"primary\" leg and made swap rows\n * unrenderable (showed `Swapped 987.60 MANIFEST` because MANIFEST\n * was the largest raw delta even though USDC was the value side).\n */\nexport function extractAllUserLegs(\n changes: ClassifyBalanceChange[] | undefined,\n sender: string,\n): import('../types.js').TransactionLeg[] {\n if (!changes || changes.length === 0) return [];\n\n const legs: import('../types.js').TransactionLeg[] = [];\n for (const c of changes) {\n if (resolveOwner(c.owner) !== sender) continue;\n const raw = BigInt(c.amount);\n if (raw === 0n) continue;\n const decimals = getDecimalsForCoinType(c.coinType);\n const absAmount = bigintAbs(raw);\n legs.push({\n coinType: c.coinType,\n asset: resolveSymbol(c.coinType),\n decimals,\n amount: Number(absAmount) / 10 ** decimals,\n rawAmount: raw.toString(),\n direction: raw < 0n ? 'out' : 'in',\n });\n }\n\n return legs;\n}\n","import type { TransactionRecord } from '../types.js';\nimport { getSuiGraphQLClient } from '../utils/sui.js';\nimport {\n classifyTransaction,\n extractAllUserLegs,\n extractTransferDetails,\n type ClassifyBalanceChange,\n} from './classify.js';\n\n// ---------------------------------------------------------------------------\n// [gRPC migration / S.447 + S.450] Transaction history is the one surface with\n// NO gRPC `core.*` equivalent (Stage 0 finding A): list-by-affected-address +\n// per-tx-by-digest live in the GraphQL RPC, not gRPC. Both go through the\n// Sui GraphQL endpoint (`getSuiGraphQLClient()`), share one node fragment +\n// one mapper, and feed the existing (tested) classifier in `classify.ts`.\n//\n// LIVE-VERIFIED 2026-06-15 (S.450) against `graphql.mainnet.sui.io` with a\n// real sender (send + Cetus swap digests). The live schema differs from the\n// older `transactionBlocks` one: the query is `transactions` / `transaction`\n// (filter `affectedAddress` — sender, sponsor, or recipient), the programmable kind is `ProgrammableTransaction`\n// (was `ProgrammableTransactionBlock`) with `commands { nodes }` (was\n// `transactions`), and a move call is `MoveCallCommand` with a nested\n// `function { name module { name package { address } } }` (was a flat\n// `MoveCallTransaction { package module functionName }`). GraphQL errors are\n// now SURFACED, not swallowed (the old `?? []` hid this schema drift as an\n// empty history for a whole session). Schema ref: https://docs.sui.io/references/sui-graphql\n// ---------------------------------------------------------------------------\n\nconst TX_NODE_FRAGMENT = `\n digest\n effects {\n timestamp\n gasEffects { gasSummary { computationCost storageCost storageRebate } }\n balanceChanges { nodes { amount coinType { repr } owner { address } } }\n }\n kind {\n __typename\n ... on ProgrammableTransaction {\n commands {\n nodes {\n __typename\n ... on MoveCallCommand { function { name module { name package { address } } } }\n }\n }\n }\n }\n`;\n\n// `affectedAddress` (not `sentAddress`) so history includes INCOMING transactions\n// — received payments, x402/MPP refunds, airdrops — not just ones the agent\n// signed. Per the Sui GraphQL schema: \"transactions that interacted with the\n// given address … as a sender, sponsor, or recipient.\" The shared classifier\n// already labels each leg's direction ('in' / 'out'), so inbound txns render\n// correctly downstream.\nconst HISTORY_QUERY = `query History($address: SuiAddress!, $last: Int!) {\n transactions(last: $last, filter: { affectedAddress: $address }) {\n nodes {${TX_NODE_FRAGMENT}}\n }\n}`;\n\nconst TX_BY_DIGEST_QUERY = `query TxByDigest($digest: String!) {\n transaction(digest: $digest) {${TX_NODE_FRAGMENT}}\n}`;\n\n/** Minimal shape of a Sui GraphQL transaction node we consume. */\ninterface GqlTxNode {\n digest?: string;\n effects?: {\n timestamp?: string;\n // Live schema returns gas as numbers; `Number()` in the mapper tolerates both.\n gasEffects?: { gasSummary?: { computationCost?: string | number; storageCost?: string | number; storageRebate?: string | number } };\n balanceChanges?: { nodes?: Array<{ amount?: string; coinType?: { repr?: string }; owner?: { address?: string } }> };\n };\n kind?: {\n __typename?: string;\n commands?: {\n nodes?: Array<{\n __typename?: string;\n function?: { name?: string; module?: { name?: string; package?: { address?: string } } };\n }>;\n };\n };\n}\n\n/** GraphQL transport result with the optional `errors` array surfaced. */\ninterface GqlResult<T> {\n data?: T;\n errors?: Array<{ message?: string }>;\n}\n\nfunction assertNoGqlErrors(res: GqlResult<unknown>, what: string): void {\n if (res.errors?.length) {\n throw new Error(\n `Sui GraphQL ${what} failed: ${res.errors.map((e) => e.message ?? 'unknown error').join('; ')}`,\n );\n }\n}\n\nexport async function queryHistory(\n address: string,\n limit = 20,\n): Promise<TransactionRecord[]> {\n const gql = getSuiGraphQLClient();\n const res = (await gql.query({ query: HISTORY_QUERY, variables: { address, last: limit } })) as GqlResult<{\n transactions?: { nodes?: GqlTxNode[] };\n }>;\n assertNoGqlErrors(res, 'history query');\n const nodes = res.data?.transactions?.nodes ?? [];\n // GraphQL `last` returns ascending; the legacy JSON-RPC path returned\n // descending (newest first) — reverse to preserve caller expectations.\n return nodes.map((n) => recordFromGqlNode(n, address)).reverse();\n}\n\nexport async function queryTransaction(\n digest: string,\n senderAddress: string,\n): Promise<TransactionRecord | null> {\n const gql = getSuiGraphQLClient();\n const res = (await gql.query({ query: TX_BY_DIGEST_QUERY, variables: { digest } })) as GqlResult<{\n transaction?: GqlTxNode | null;\n }>;\n assertNoGqlErrors(res, 'transaction query');\n const node = res.data?.transaction;\n if (!node) return null; // genuine not-found (distinct from a query error, which throws above)\n return recordFromGqlNode(node, senderAddress);\n}\n\n/**\n * Map a Sui GraphQL transactionBlock node → the primitives the shared\n * classifier consumes, then build the record. Isolated so the legacy\n * JSON-RPC `parseTxRecord` (back-compat, below) and this GraphQL path\n * converge on one classification routine.\n */\nfunction recordFromGqlNode(node: GqlTxNode, address: string): TransactionRecord {\n const gs = node.effects?.gasEffects?.gasSummary;\n const gasCost = gs\n ? (Number(gs.computationCost ?? 0) + Number(gs.storageCost ?? 0) - Number(gs.storageRebate ?? 0)) / 1e9\n : undefined;\n\n const balanceChanges: ClassifyBalanceChange[] = (node.effects?.balanceChanges?.nodes ?? [])\n .filter((b) => b.coinType?.repr && b.amount != null)\n .map((b) => ({ coinType: b.coinType!.repr!, amount: String(b.amount), owner: b.owner?.address ?? '' }));\n\n const moveCallTargets: string[] = [];\n const commandTypes: string[] = [];\n if (node.kind?.__typename === 'ProgrammableTransaction') {\n for (const cmd of node.kind.commands?.nodes ?? []) {\n if (cmd.__typename === 'MoveCallCommand') {\n commandTypes.push('MoveCall');\n const fn = cmd.function;\n const pkg = fn?.module?.package?.address;\n const mod = fn?.module?.name;\n const name = fn?.name;\n if (pkg && mod && name) {\n moveCallTargets.push(`${pkg}::${mod}::${name}`);\n }\n } else if (cmd.__typename === 'TransferObjectsCommand') {\n commandTypes.push('TransferObjects');\n }\n }\n }\n\n // GraphQL effects.timestamp is an ISO datetime; the record wants ms.\n const ts = node.effects?.timestamp ? Date.parse(node.effects.timestamp) : 0;\n\n return buildRecord({\n digest: node.digest ?? '',\n moveCallTargets,\n commandTypes,\n balanceChanges,\n timestampMs: Number.isFinite(ts) ? ts : 0,\n gasCost,\n address,\n });\n}\n\n/** Shared record builder — classification + leg/transfer extraction. */\nfunction buildRecord(args: {\n digest: string;\n moveCallTargets: string[];\n commandTypes: string[];\n balanceChanges: ClassifyBalanceChange[];\n timestampMs: number;\n gasCost: number | undefined;\n address: string;\n}): TransactionRecord {\n const { digest, moveCallTargets, commandTypes, balanceChanges, timestampMs, gasCost, address } = args;\n const legs = extractAllUserLegs(balanceChanges, address);\n const { amount, asset, recipient, direction } = extractTransferDetails(balanceChanges, address);\n const { action, label } = classifyTransaction(moveCallTargets, commandTypes, balanceChanges, address);\n return { digest, action, label, legs, amount, asset, recipient, direction, timestamp: timestampMs, gasCost };\n}\n\n/**\n * Shape of a transaction block as returned by `suix_queryTransactionBlocks`\n * with `showEffects | showInput | showBalanceChanges` enabled. Exported so\n * downstream consumers (audric dashboard `/api/history`, `/api/activity`,\n * etc.) can type their RPC calls without redeclaring the structure.\n */\nexport interface SuiRpcTxBlock {\n digest: string;\n timestampMs?: string;\n transaction?: unknown;\n effects?: { gasUsed?: { computationCost: string; storageCost: string; storageRebate: string } };\n balanceChanges?: ClassifyBalanceChange[];\n}\n\n/**\n * Convert a single Sui RPC transaction block to a {@link TransactionRecord}\n * using the canonical (shared) classifier and balance-change extractor.\n *\n * This is the single source of truth for transaction parsing across the\n * agent-tool path AND the dashboard-API path. Use it instead of writing\n * a bespoke parser per surface.\n *\n * @param tx Raw RPC tx block (must include `effects`, `input`, `balanceChanges`).\n * @param address Wallet address whose perspective we're parsing from.\n */\nexport function parseSuiRpcTx(tx: SuiRpcTxBlock, address: string): TransactionRecord {\n return parseTxRecord(tx, address);\n}\n\n/**\n * Extract the sender (signer) address from a raw RPC tx block.\n * Returns `null` if the block shape is unexpected.\n */\nexport function extractTxSender(txBlock: unknown): string | null {\n try {\n if (!txBlock || typeof txBlock !== 'object') return null;\n const data = 'data' in txBlock ? (txBlock as Record<string, unknown>).data : undefined;\n if (!data || typeof data !== 'object') return null;\n return ((data as Record<string, unknown>).sender as string) ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Extract MoveCall targets (`<pkg>::<module>::<function>`) and the\n * sequence of programmable-transaction command types (e.g. `MoveCall`,\n * `TransferObjects`) from a raw RPC tx block. Tolerates both the\n * legacy `inner.transactions` field and the newer `inner.commands`\n * field.\n */\nexport function extractTxCommands(txBlock: unknown): {\n moveCallTargets: string[];\n commandTypes: string[];\n} {\n return extractCommands(txBlock);\n}\n\n// [back-compat] Legacy JSON-RPC-shape parser. The live history path is now\n// GraphQL (above); this stays for external consumers that already hold a\n// JSON-RPC tx block (e.g. via `parseSuiRpcTx`). Routes through `buildRecord`\n// so classification is identical to the GraphQL path.\nfunction parseTxRecord(tx: SuiRpcTxBlock, address: string): TransactionRecord {\n const gasUsed = tx.effects?.gasUsed;\n const gasCost = gasUsed\n ? (Number(gasUsed.computationCost) +\n Number(gasUsed.storageCost) -\n Number(gasUsed.storageRebate)) /\n 1e9\n : undefined;\n\n const { moveCallTargets, commandTypes } = extractCommands(tx.transaction);\n return buildRecord({\n digest: tx.digest,\n moveCallTargets,\n commandTypes,\n balanceChanges: tx.balanceChanges ?? [],\n timestampMs: Number(tx.timestampMs ?? 0),\n gasCost,\n address,\n });\n}\n\ninterface CommandInfo {\n moveCallTargets: string[];\n commandTypes: string[];\n}\n\nfunction extractCommands(txBlock: unknown): CommandInfo {\n const result: CommandInfo = { moveCallTargets: [], commandTypes: [] };\n try {\n if (!txBlock || typeof txBlock !== 'object') return result;\n const data = 'data' in txBlock ? (txBlock as Record<string, unknown>).data : undefined;\n if (!data || typeof data !== 'object') return result;\n const inner = 'transaction' in (data as Record<string, unknown>)\n ? (data as Record<string, unknown>).transaction\n : undefined;\n if (!inner || typeof inner !== 'object') return result;\n const commands = 'commands' in (inner as Record<string, unknown>)\n ? (inner as Record<string, unknown>).commands\n : 'transactions' in (inner as Record<string, unknown>)\n ? (inner as Record<string, unknown>).transactions\n : undefined;\n if (!Array.isArray(commands)) return result;\n\n for (const cmd of commands as Record<string, unknown>[]) {\n if (cmd.MoveCall) {\n const mc = cmd.MoveCall as { package: string; module: string; function: string };\n result.moveCallTargets.push(`${mc.package}::${mc.module}::${mc.function}`);\n result.commandTypes.push('MoveCall');\n } else if (cmd.TransferObjects) {\n result.commandTypes.push('TransferObjects');\n }\n }\n } catch { /* best effort */ }\n return result;\n}\n","import { EventEmitter } from 'eventemitter3';\nimport type { SuiGrpcClient } from '@mysten/sui/grpc';\nimport type { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';\nimport { Transaction, coinWithBalance, type TransactionObjectArgument } from '@mysten/sui/transactions';\nimport { createPaymentTransactionUri } from '@mysten/payment-kit';\nimport { getSuiClient, getSuiGrpcClient } from './utils/sui.js';\nimport {\n generateKeypair,\n keypairFromPrivateKey,\n saveKey,\n loadKey,\n walletExists,\n exportPrivateKey,\n getAddress,\n} from './wallet/keyManager.js';\nimport type { TransactionSigner } from './signer.js';\nimport { KeypairSigner } from './wallet/keypairSigner.js';\nimport { executeTx } from './wallet/executeTx.js';\nimport { payWithMpp } from './wallet/pay.js';\nimport { ZkLoginSigner, type ZkLoginProof } from './wallet/zkLoginSigner.js';\nimport { buildSendTx } from './wallet/send.js';\nimport { queryBalance } from './wallet/balance.js';\nimport { queryHistory, queryTransaction } from './wallet/history.js';\nimport { resolveSymbol, resolveCoinDecimals } from './token-registry.js';\nimport {\n SUI_ADDRESS_REGEX,\n SuinsNotRegisteredError,\n looksLikeSuiNs,\n resolveSuinsViaRpc,\n} from './utils/suins.js';\n// [B5 v2 / 2026-04-30] No fee imports — CLI / direct SDK is fee-free. Consumer\n// apps (Audric) own fee policy (Cetus `overlayFee` on swaps → T2000_OVERLAY_FEE_WALLET).\nimport type {\n T2000Options,\n BalanceResponse,\n SendResult,\n TransactionRecord,\n DepositInfo,\n PaymentRequest,\n PayOptions,\n PayResult,\n SwapResult,\n SwapQuoteResult,\n} from './types.js';\nimport { T2000Error } from './errors.js';\nimport {\n chatCompletion,\n chatCompletionStream,\n listModels,\n type ApiModel,\n type ChatParams,\n type ChatResult,\n} from './inference.js';\nimport { verifyReceipt, type VerifyOptions, type VerifyResult } from './verify.js';\nimport { SUPPORTED_ASSETS, assertAllowedAsset, type SendableAsset, type SupportedAsset } from './constants.js';\n\nimport { truncateAddress } from './utils/sui.js';\nimport { LimitEnforcer, approxUsdValue } from './limits/index.js';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nconst DEFAULT_CONFIG_DIR = join(homedir(), '.t2000');\n\ninterface T2000Events {\n balanceChange: (event: { asset: string; previous: number; current: number; cause: string; tx?: string }) => void;\n healthWarning: (event: { healthFactor: number; threshold: number; severity: 'warning' }) => void;\n healthCritical: (event: { healthFactor: number; threshold: number; severity: 'critical' }) => void;\n yield: (event: { earned: number; total: number; apy: number; timestamp: number }) => void;\n error: (error: T2000Error) => void;\n}\n\n// Sign + execute a transaction with the agent's signer. Replaces the pre-v2 gas\n// manager — every transaction is now self-funded by the agent's wallet.\nexport class T2000 extends EventEmitter<T2000Events> {\n private readonly _signer: TransactionSigner;\n private readonly _keypair?: Ed25519Keypair;\n private readonly client: SuiGrpcClient;\n private readonly _address: string;\n /** Unified spending-limit gate (per-tx + cumulative daily, USD). Shared by\n * CLI + MCP + programmatic writes — one gate, no bypass (R-0 Finding 1). */\n readonly limits: LimitEnforcer;\n\n private constructor(keypair: Ed25519Keypair, client: SuiGrpcClient, configDir?: string);\n private constructor(signer: TransactionSigner, client: SuiGrpcClient, configDir: string | undefined, isSignerMode: true);\n private constructor(\n keypairOrSigner: Ed25519Keypair | TransactionSigner,\n client: SuiGrpcClient,\n configDir?: string,\n isSignerMode?: boolean,\n ) {\n super();\n if (isSignerMode) {\n this._signer = keypairOrSigner as TransactionSigner;\n this._keypair = undefined;\n this._address = this._signer.getAddress();\n } else {\n const kp = keypairOrSigner as Ed25519Keypair;\n this._keypair = kp;\n this._signer = new KeypairSigner(kp);\n this._address = getAddress(kp);\n }\n this.client = client;\n this.limits = new LimitEnforcer(configDir);\n }\n\n static async create(options: T2000Options = {}): Promise<T2000> {\n const { keyPath, rpcUrl } = options;\n\n const client = getSuiClient(rpcUrl);\n\n const exists = await walletExists(keyPath);\n if (!exists) {\n throw new T2000Error(\n 'WALLET_NOT_FOUND',\n 'No wallet found. Run `t2 init` to create one.',\n );\n }\n\n // [v4.0] loadKey reads v2 plain Bech32 JSON. Anything else throws\n // WALLET_CORRUPT. PIN/passphrase fields on T2000Options are accepted\n // for back-compat but IGNORED.\n const keypair = await loadKey(undefined, keyPath);\n return new T2000(keypair, client, DEFAULT_CONFIG_DIR);\n }\n\n static fromPrivateKey(privateKey: string, options: { network?: 'mainnet' | 'testnet'; rpcUrl?: string } = {}): T2000 {\n const keypair = keypairFromPrivateKey(privateKey);\n const client = getSuiClient(options.rpcUrl);\n return new T2000(keypair, client);\n }\n\n static async init(options: { pin?: string; passphrase?: string; keyPath?: string; name?: string } = {}): Promise<{ agent: T2000; address: string }> {\n // [v4.0] pin/passphrase accepted for back-compat but IGNORED.\n const keypair = generateKeypair();\n await saveKey(keypair, undefined, options.keyPath);\n\n const client = getSuiClient();\n const agent = new T2000(keypair, client, DEFAULT_CONFIG_DIR);\n const address = agent.address();\n\n return { agent, address };\n }\n\n // -- Gas --\n\n /** SuiGrpcClient used by this agent — exposed for integrations. */\n get suiClient(): SuiGrpcClient {\n return this.client;\n }\n\n /** Ed25519Keypair used by this agent — exposed for CLI/MCP integrations. */\n get keypair(): Ed25519Keypair {\n if (!this._keypair) {\n throw new T2000Error('WALLET_NOT_FOUND', 'Keypair not available — this instance uses zkLogin');\n }\n return this._keypair;\n }\n\n /** Transaction signer (works for both keypair and zkLogin). */\n get signer(): TransactionSigner {\n return this._signer;\n }\n\n // -- MPP Payments --\n\n async pay(options: PayOptions): Promise<PayResult> {\n // Gate on the maxPrice ceiling pre-flight (USD); record the ACTUAL cost\n // post-settle. `force` bypasses (caller owns consent).\n this.limits.assert({ operation: 'pay', amountUsd: options.maxPrice ?? 0, force: options.force });\n\n // Canonical gasless MPP pay loop lives in `wallet/pay.ts` (browser-safe,\n // shared with the Audric client's unified gasless write path). T2000\n // owns only the limit book-ends; the server budget ledger is the cap on\n // the browser side, so the browser caller skips the SDK limit gate.\n const result = await payWithMpp({ signer: this._signer, client: this.client, options });\n\n if (result.paid) {\n this.limits.record(result.cost ?? options.maxPrice ?? 0);\n }\n\n return result;\n }\n\n // [S.323 / 2026-05-25] VOLO vSUI staking surfaces removed (full cut).\n // Engine cut Volo in S.277; SDK + CLI + MCP followed in S.323 because the\n // product surface (five products: Passport / Intelligence / Finance / Pay\n // / Store) doesn't include a staking primitive. vSUI still appears in the\n // codebase as a passive token (NAVI reward rewards, Cetus swap routing),\n // but there is no longer any way to MINT or REDEEM vSUI through t2000.\n // History: see spec/archive/v07e/AUDIT_V07E_EARNS_ITS_KEEP_2026-05-23.md\n // and the S.323 build-tracker entry.\n\n // -- Private Inference API (SPEC_AUDRIC_API, S.575) --\n //\n // Inference as a wallet verb — the agent's brain + wallet in one package.\n // Key-based today (`apiKey` / `T2000_API_KEY`); the x402 no-key pay-per-call\n // path is a later add. The model runs on t2000 Private Inference (ZDR; a\n // `phala/*` confidential tier runs in a GPU-TEE).\n\n /** Non-streaming chat completion against Private Inference. */\n async chat(params: ChatParams): Promise<ChatResult> {\n return chatCompletion(params);\n }\n\n /** Streaming chat completion — async-iterate the assistant text deltas;\n * the generator returns `{ receiptId }` (confidential attestation) at the end. */\n chatStream(\n params: ChatParams\n ): AsyncGenerator<string, { receiptId?: string }, unknown> {\n return chatCompletionStream(params);\n }\n\n /** The Private Inference model catalog (`GET /v1/models`). */\n async models(opts?: { apiKey?: string; apiBase?: string }): Promise<ApiModel[]> {\n return listModels(opts);\n }\n\n /** Verify a confidential response by receipt id — checks the signed receipt\n * + its trustless on-chain Sui anchor. Fails closed on any mismatch. */\n async verify(receiptId: string, opts?: VerifyOptions): Promise<VerifyResult> {\n return verifyReceipt(receiptId, opts);\n }\n\n // -- Swap --\n\n async swap(params: {\n from: string;\n to: string;\n amount: number;\n byAmountIn?: boolean;\n slippage?: number;\n force?: boolean;\n }): Promise<SwapResult> {\n // Gate on the input-side USD value (stables 1:1; SUI/other → ungated).\n this.limits.assert({\n operation: 'swap',\n amountUsd: approxUsdValue(params.from, params.amount) ?? 0,\n force: params.force,\n });\n\n const { findSwapRoute, buildSwapTx, resolveTokenType, preflightSwap } = await import('./protocols/cetus-swap.js');\n\n // Layer 2 — cheap synchronous preflight (from/to/amount sanity, identity\n // swap). Runs before any route-finding network call.\n const pf = preflightSwap({ from: params.from, to: params.to, amount: params.amount });\n if (!pf.valid) throw new T2000Error(pf.code, pf.error);\n\n const fromType = resolveTokenType(params.from);\n const toType = resolveTokenType(params.to);\n if (!fromType) throw new T2000Error('ASSET_NOT_SUPPORTED', `Unknown token: ${params.from}. Provide the full coin type.`);\n if (!toType) throw new T2000Error('ASSET_NOT_SUPPORTED', `Unknown token: ${params.to}. Provide the full coin type.`);\n\n const byAmountIn = params.byAmountIn ?? true;\n const slippage = Math.min(params.slippage ?? 0.01, 0.05);\n\n const fromDecimals = await resolveCoinDecimals(this.client, fromType);\n const rawAmount = BigInt(Math.floor(params.amount * 10 ** fromDecimals));\n\n const route = await findSwapRoute({\n walletAddress: this._address,\n from: fromType,\n to: toType,\n amount: rawAmount,\n byAmountIn,\n });\n\n if (!route) throw new T2000Error('SWAP_NO_ROUTE', `No swap route found for ${params.from} -> ${params.to}.`);\n if (route.insufficientLiquidity) throw new T2000Error('SWAP_NO_ROUTE', `Insufficient liquidity for ${params.from} -> ${params.to}.`);\n if (route.priceImpact > 0.05) {\n console.warn(`[swap] High price impact: ${(route.priceImpact * 100).toFixed(2)}%`);\n }\n\n const toDecimals = await resolveCoinDecimals(this.client, toType);\n\n // Snapshot pre-swap balance for fallback diff calculation\n let preBalRaw = 0n;\n try {\n const preBal = await this.client.core.getBalance({ owner: this._address, coinType: toType });\n preBalRaw = BigInt(preBal.balance.balance);\n } catch { /* first time holding this token — balance is 0 */ }\n\n const gasResult = await executeTx(this.client, this._signer, async () => {\n const tx = new Transaction();\n tx.setSender(this._address);\n\n let inputCoin: TransactionObjectArgument;\n if (fromType === '0x2::sui::SUI') {\n [inputCoin] = tx.splitCoins(tx.gas, [rawAmount]);\n } else {\n const bal = await this.client.core.getBalance({ owner: this._address, coinType: fromType });\n if (BigInt(bal.balance.balance) < rawAmount) {\n throw new T2000Error('INSUFFICIENT_BALANCE', `Insufficient ${params.from} balance.`, {\n available: Number(bal.balance.balance) / 10 ** fromDecimals,\n required: params.amount,\n });\n }\n inputCoin = coinWithBalance({ type: fromType, balance: rawAmount })(tx);\n }\n\n const outputCoin = await buildSwapTx({\n walletAddress: this._address,\n route,\n tx,\n inputCoin,\n slippage,\n });\n\n tx.transferObjects([outputCoin], this._address);\n return tx;\n });\n\n const fromAmount = Number(route.amountIn) / 10 ** fromDecimals;\n let toAmount = Number(route.amountOut) / 10 ** toDecimals;\n\n // --- Primary: parse balance changes from the finalized transaction ---\n const toTypeSuffix = toType.split('::').slice(1).join('::');\n try {\n // [gRPC migration] core.waitForTransaction returns a discriminated union;\n // balanceChanges are `{ coinType, address, amount }` (signed string),\n // not the legacy `{ owner: { AddressOwner } }` shape.\n const fullTx = await this.client.core.waitForTransaction({\n digest: gasResult.digest,\n include: { balanceChanges: true },\n timeout: 8_000,\n });\n const txn = fullTx.$kind === 'Transaction' ? fullTx.Transaction : fullTx.FailedTransaction;\n const changes = txn.balanceChanges ?? [];\n const received = changes.find((c) => {\n if (BigInt(c.amount) <= 0n) return false;\n if (!c.address || c.address.toLowerCase() !== this._address.toLowerCase()) return false;\n if (c.coinType === toType) return true;\n return c.coinType.endsWith(toTypeSuffix);\n });\n if (received) {\n const actual = Number(BigInt(received.amount)) / 10 ** toDecimals;\n if (actual > 0) toAmount = actual;\n }\n } catch {\n // waitForTransaction timeout — fall through to balance diff\n }\n\n // --- Fallback: pre/post getBalance diff ---\n const cetusEstimate = Number(route.amountOut) / 10 ** toDecimals;\n if (Math.abs(toAmount - cetusEstimate) < 0.001) {\n try {\n await new Promise((r) => setTimeout(r, 2000));\n const postBal = await this.client.core.getBalance({ owner: this._address, coinType: toType });\n const postRaw = BigInt(postBal.balance.balance);\n const delta = Number(postRaw - preBalRaw) / 10 ** toDecimals;\n if (delta > 0) toAmount = delta;\n } catch {\n // Balance diff fallback failed — use Cetus estimate\n }\n }\n\n // Resolve full coin types to user-friendly token names\n const fromName = resolveSymbol(fromType);\n const toName = resolveSymbol(toType);\n\n const routeDesc = route.routerData.paths\n ?.map((p) => p.provider)\n .filter(Boolean)\n .slice(0, 3)\n .join(' + ') ?? 'Cetus Aggregator';\n\n // Record the settled input-side USD against the cumulative daily total.\n this.limits.record(approxUsdValue(params.from, params.amount) ?? 0);\n\n return {\n success: true,\n tx: gasResult.digest,\n fromToken: fromName,\n toToken: toName,\n fromAmount,\n toAmount,\n priceImpact: route.priceImpact,\n route: routeDesc,\n gasCost: gasResult.gasCostSui,\n };\n }\n\n /**\n * [SPEC_AGENTIC_STACK P1 / SDK F2 — 2026-05-25]\n * Thin wrapper around the standalone `getSwapQuote()`. Pre-Phase 1 this method\n * was ~50 LoC duplicating `swap-quote.ts` — missing `serializedRoute` (SPEC 20.2\n * fast-path) and the `providers` allow-list (Bug A fix / Pyth-dependent\n * provider filter for sponsored callers). Routing both API surfaces through\n * one implementation ensures fixes land for both.\n */\n async swapQuote(params: {\n from: string;\n to: string;\n amount: number;\n byAmountIn?: boolean;\n providers?: string[];\n }): Promise<SwapQuoteResult> {\n const { getSwapQuote } = await import('./swap-quote.js');\n const { resolveTokenType } = await import('./protocols/cetus-swap.js');\n // [2.11] Resolve decimals on-chain for non-registry coin types so the quote\n // matches what a real swap would compute (the standalone getSwapQuote can't\n // — it has no client). Falls back to its registry default if unresolved.\n const fromType = resolveTokenType(params.from);\n const toType = resolveTokenType(params.to);\n return getSwapQuote({\n walletAddress: this._address,\n from: params.from,\n to: params.to,\n amount: params.amount,\n byAmountIn: params.byAmountIn,\n providers: params.providers,\n fromDecimals: fromType ? await resolveCoinDecimals(this.client, fromType) : undefined,\n toDecimals: toType ? await resolveCoinDecimals(this.client, toType) : undefined,\n });\n }\n\n // -- Wallet --\n\n address(): string {\n return this._address;\n }\n\n /**\n * Send `amount` of `asset` to `to` (hex address or SuiNS name).\n *\n * [v4.0 Phase A Day 2 — SPEC_AGENT_WALLET_GREENFIELD §A]\n *\n * **Breaking changes from v3.x:**\n * - `asset` is now REQUIRED (no implicit `?? 'USDC'` default). Callers\n * must specify `'USDC' | 'USDsui' | 'SUI'`. Sending `'USDT'` /\n * `'USDe'` / `'WAL'` / `'ETH'` / `'NAVX'` / `'GOLD'` now errors\n * with `INVALID_ASSET` — swap to a stable first.\n * - USDC + USDsui builds go through `SuiGrpcClient` so the gRPC build\n * resolver auto-detects `0x2::balance::send_funds` eligibility and\n * zeros gas at simulate time. Result: **gasless USDC / USDsui sends\n * from a zero-SUI wallet.** SUI sends stay on the standard gas-paid\n * path.\n *\n * Submission stays on the JSON-RPC client (the rest of the SDK\n * expects JSON-RPC for read paths, and Sui's docs explicitly support\n * the \"build via gRPC, execute via JSON-RPC\" hybrid).\n */\n async send(params: { to: string; amount: number; asset: SupportedAsset; force?: boolean }): Promise<SendResult> {\n // [v4.0 Phase A Day 2] Asset is REQUIRED at runtime (no more silent\n // USDC default). The parameter type is `SupportedAsset` (the wider\n // SDK surface) rather than `SendableAsset` so callers that still\n // hand a wide-typed asset through — primarily the engine LLM tool\n // surface — compile without modification. Runtime narrowing happens\n // via `assertAllowedAsset('send', asset)`, which throws\n // `INVALID_ASSET` for anything outside `['USDC', 'USDsui', 'SUI']`.\n // This matches the SPEC verification gate `asset: 'USDY'` →\n // `INVALID_ASSET` (runtime check, not compile check).\n const asset = params.asset;\n if (!asset) {\n throw new T2000Error(\n 'INVALID_ASSET',\n \"send() requires an explicit asset. Use one of: USDC, USDsui, SUI.\",\n );\n }\n assertAllowedAsset('send', asset);\n // `assertAllowedAsset('send', asset)` narrows the runtime value to\n // one of `SendableAsset` (USDC / USDsui / SUI). Cast statically.\n const sendableAsset = asset as SendableAsset;\n\n // Spending-limit gate (USD; stables 1:1, SUI ungated). `force` bypasses.\n this.limits.assert({\n operation: 'send',\n amountUsd: approxUsdValue(sendableAsset, params.amount) ?? 0,\n force: params.force,\n });\n\n const resolved = await this.resolveRecipient(params.to);\n const sendAmount = params.amount;\n const sendTo = resolved.address;\n\n // Gasless-eligible stables (USDC / USDsui) build via the dedicated gRPC\n // client so the resolver can zero gas at simulate. SUI is not on the\n // `balance::send_funds` allowlist, so it builds via the default client\n // (also gRPC post-cutover) with normal gas — no separate build client.\n const useGrpc = sendableAsset === 'USDC' || sendableAsset === 'USDsui';\n const buildClient = useGrpc ? getSuiGrpcClient() : undefined;\n\n const gasResult = await executeTx(\n this.client,\n this._signer,\n () => buildSendTx({ client: this.client, address: this._address, to: sendTo, amount: sendAmount, asset: sendableAsset }),\n { buildClient },\n );\n\n this.limits.record(approxUsdValue(sendableAsset, sendAmount) ?? 0);\n const balance = await this.balance();\n\n this.emitBalanceChange(sendableAsset, sendAmount, 'send', gasResult.digest);\n\n return {\n success: true,\n tx: gasResult.digest,\n amount: sendAmount,\n to: resolved.address,\n suinsName: resolved.suinsName,\n gasCost: gasResult.gasCostSui,\n gasCostUnit: 'SUI',\n balance,\n };\n }\n\n /**\n * Resolve a recipient string into a canonical 0x address:\n * 1. **hex** — `0x…` is used directly (no RPC round-trip).\n * 2. **SuiNS** — `alex.sui` resolves via `suix_resolveNameServiceAddress`.\n *\n * Anything else is rejected. (The legacy `contacts.json` alias map was\n * removed — SuiNS supersedes local contacts.)\n *\n * Returns `{ address, suinsName? }` so `send()` can stamp the name source\n * on the receipt without re-resolving. Throws\n * `T2000Error('SUINS_NOT_REGISTERED', …)` for well-formed but unregistered\n * SuiNS names, keeping the SDK error surface `T2000Error`-only.\n *\n * Public so MCP's `t2000_send` dryRun preview shares one resolution path\n * with the live execute path (never resolve the same input two ways).\n */\n async resolveRecipient(\n input: string,\n ): Promise<{ address: string; suinsName?: string }> {\n const trimmed = input.trim();\n if (SUI_ADDRESS_REGEX.test(trimmed)) {\n return { address: trimmed.toLowerCase() };\n }\n if (looksLikeSuiNs(trimmed)) {\n try {\n const name = trimmed.toLowerCase();\n const address = await resolveSuinsViaRpc(name);\n if (!address) {\n throw new SuinsNotRegisteredError(name);\n }\n return { address: address.toLowerCase(), suinsName: name };\n } catch (err) {\n if (err instanceof SuinsNotRegisteredError) {\n throw new T2000Error(\n 'SUINS_NOT_REGISTERED',\n err.message,\n );\n }\n throw err;\n }\n }\n throw new T2000Error(\n 'INVALID_ADDRESS',\n `Cannot resolve recipient \"${input}\". Provide a 0x address or a .sui name.`,\n );\n }\n\n async balance(): Promise<BalanceResponse> {\n // [NAVI removed] Wallet-only balance: spendable stables + SUI gas reserve.\n return queryBalance(this.client, this._address);\n }\n\n async history(params?: { limit?: number }): Promise<TransactionRecord[]> {\n return queryHistory(this._address, params?.limit);\n }\n\n async transactionDetail(digest: string): Promise<TransactionRecord | null> {\n return queryTransaction(digest, this._address);\n }\n\n async deposit(): Promise<DepositInfo> {\n return {\n address: this._address,\n network: 'mainnet',\n supportedAssets: ['USDC', 'USDT', 'SUI'],\n instructions: [\n `Send USDC to: ${this._address}`,\n `Network: Sui Mainnet`,\n `Or buy USDC on an exchange and withdraw to this address.`,\n `USDC contract: ${SUPPORTED_ASSETS.USDC.type}`,\n ].join('\\n'),\n };\n }\n\n /**\n * [SPEC_AGENTIC_STACK P1 / SDK F2 — 2026-05-25; refreshed S.342 / 2026-05-26]\n * Preferred alias of `deposit()`. Was introduced to mirror the v3 `t2000 fund`\n * CLI command; the v4 CLI surface is `t2 fund` (renamed back from the\n * interim `t2 receive` in S.464). `deposit()` stays as the canonical method name for\n * back-compat; `fund()` stays as a programmatic alias for audric + other\n * SDK consumers that prefer the verb.\n */\n async fund(): Promise<DepositInfo> {\n return this.deposit();\n }\n\n receive(params?: { amount?: number; currency?: string; memo?: string; label?: string }): PaymentRequest {\n const amount = params?.amount ?? null;\n const currency = params?.currency ?? 'USDC';\n const memo = params?.memo ?? null;\n const label = params?.label ?? null;\n const nonce = crypto.randomUUID();\n\n let qrUri: string;\n if (amount != null && amount > 0) {\n const decimals = currency === 'SUI' ? 9 : 6;\n const coinType = currency === 'SUI'\n ? '0x2::sui::SUI'\n : SUPPORTED_ASSETS.USDC.type;\n const rawAmount = BigInt(Math.floor(amount * 10 ** decimals));\n qrUri = createPaymentTransactionUri({\n receiverAddress: this._address,\n amount: rawAmount,\n coinType,\n nonce,\n ...(label ? { label } : {}),\n ...(memo ? { message: memo } : {}),\n });\n } else {\n const qrParts = [`sui:${this._address}`];\n const queryParams: string[] = [];\n if (currency !== 'SUI') queryParams.push(`currency=${currency}`);\n if (memo) queryParams.push(`memo=${encodeURIComponent(memo)}`);\n if (label) queryParams.push(`label=${encodeURIComponent(label)}`);\n qrUri = queryParams.length > 0 ? `${qrParts[0]}?${queryParams.join('&')}` : qrParts[0];\n }\n\n const amountStr = amount != null ? `$${amount.toFixed(2)} ` : '';\n const displayParts = [`Send ${amountStr}${currency} to ${truncateAddress(this._address)}`];\n if (memo) displayParts.push(`Memo: ${memo}`);\n\n return {\n address: this._address,\n network: 'mainnet',\n amount,\n currency,\n memo,\n label,\n nonce,\n qrUri,\n displayText: displayParts.join('\\n'),\n };\n }\n\n exportKey(): string {\n return exportPrivateKey(this.keypair);\n }\n\n static fromZkLogin(opts: {\n ephemeralKeypair: Ed25519Keypair;\n zkProof: ZkLoginProof;\n userAddress: string;\n maxEpoch: number;\n rpcUrl?: string;\n }): T2000 {\n const signer = new ZkLoginSigner(opts.ephemeralKeypair, opts.zkProof, opts.userAddress, opts.maxEpoch);\n const client = getSuiClient(opts.rpcUrl);\n return new T2000(signer, client, undefined, true);\n }\n\n private emitBalanceChange(asset: string, amount: number, cause: string, tx?: string): void {\n this.emit('balanceChange', { asset, previous: 0, current: 0, cause, tx });\n }\n}\n\n","// ---------------------------------------------------------------------------\n// Sui address + SuiNS normalization — single source of truth.\n//\n// [S.279 / CLI-CONTACTS-CLEANUP — 2026-05-23] Promoted from the deleted\n// `@t2000/engine` package to the SDK so the CLI's `T2000.send()` can accept\n// SuiNS names (`alex.sui`) alongside hex addresses — one canonical resolver.\n//\n// Background. Host read tools accept an optional `address` parameter so the\n// LLM can inspect any public Sui wallet. Each calls `normalizeAddressInput()`\n// to accept either `0x...` or `alex.sui` and returns a structured\n// `{ address, suinsName, raw }` triple. The SDK's `T2000.send()` uses the\n// same primitive, so a CLI user can run\n// `t2000 send alex.sui 10 USDC` without looking up the hex address first.\n//\n// Single source of truth — see `.cursor/rules/single-source-of-truth.mdc`\n// and `.cursor/rules/engineering-principles.mdc` Principle 2.\n// ---------------------------------------------------------------------------\n\nimport { getSuiGraphQLClient } from './sui.js';\n\n// [gRPC migration] SuiNS resolution moved off JSON-RPC\n// (`suix_resolveNameServiceAddress` / `suix_resolveNameServiceNames`) onto the\n// Sui GraphQL endpoint — the last JSON-RPC caller in the SDK. Both directions\n// use the unified `address(...)` query: `address(name:)` for forward\n// (name → address) and `address(address:){ defaultNameRecord { domain } }` for\n// reverse (address → primary name).\nconst RESOLVE_NAME_QUERY = `query ResolveSuins($name: String!) {\n address(name: $name) { address }\n}`;\n\nconst REVERSE_NAME_QUERY = `query ReverseSuins($address: SuiAddress!) {\n address(address: $address) { defaultNameRecord { domain } }\n}`;\n\ninterface GqlResult<T> {\n data?: T;\n errors?: Array<{ message?: string }>;\n}\n\n/**\n * Canonical 0x-address shape. Loose lower bound (>= 1 hex char) so\n * pre-v1.0 short addresses still validate; tools that need a full 64-hex\n * address can additionally check `length === 66`. Case-insensitive on\n * the `0x` prefix because some upstream callers (and historic tests)\n * uppercase the prefix as part of address normalization tests; the\n * normalizer always returns the lowercased canonical form regardless.\n */\nexport const SUI_ADDRESS_REGEX = /^0x[a-fA-F0-9]{1,64}$/i;\n\n/**\n * Strict canonical 0x-address shape (66 chars total). Used by the\n * resolver's \"looks like\" check to disambiguate \"user pasted an\n * address\" vs \"user typed a SuiNS name\".\n */\nexport const SUI_ADDRESS_STRICT_REGEX = /^0x[a-fA-F0-9]{64}$/i;\n\n/**\n * Mirrors the pattern in `audric/apps/web-v2/lib/suins-cache.ts` so the\n * host-side send executor and the engine-side read normalizer agree on\n * what counts as a SuiNS name. SuiNS allows nested labels (`team.alex.sui`)\n * but every label must use only `[a-z0-9-]`.\n */\nexport const SUINS_NAME_REGEX = /^[a-z0-9-]+(\\.[a-z0-9-]+)*\\.sui$/;\n\nexport class InvalidAddressError extends Error {\n constructor(public readonly raw: string) {\n super(\n `\"${raw}\" isn't a valid Sui address or SuiNS name. ` +\n `Pass a 0x-prefixed hex address (e.g. 0x40cd…3e62) or a SuiNS name ending in .sui (e.g. alex.sui).`,\n );\n this.name = 'InvalidAddressError';\n }\n}\n\nexport class SuinsNotRegisteredError extends Error {\n constructor(public readonly name_: string) {\n super(\n `\"${name_}\" isn't a registered SuiNS name. Double-check the spelling, ` +\n `or paste the full Sui address (0x… 64 hex characters).`,\n );\n this.name = 'SuinsNotRegisteredError';\n }\n}\n\nexport class SuinsRpcError extends Error {\n constructor(public readonly name_: string, detail: string) {\n super(`SuiNS lookup failed for \"${name_}\" (${detail}). Try again, or paste the full Sui address.`);\n this.name = 'SuinsRpcError';\n }\n}\n\n/**\n * Returns true if `value` looks like a SuiNS name (case-insensitive).\n * Cheap synchronous check — use to avoid an unnecessary RPC round-trip\n * for inputs that obviously aren't names (0x addresses, contact handles).\n */\nexport function looksLikeSuiNs(value: string): boolean {\n if (!value) return false;\n return SUINS_NAME_REGEX.test(value.trim().toLowerCase());\n}\n\n/**\n * Resolve a SuiNS name to its on-chain Sui address via the Sui GraphQL\n * `address(name:)` query. Returns `null` if the name resolves to no address\n * (= not registered or expired). Throws `SuinsRpcError` on transport failure.\n *\n * `ctx.signal` is honored for cancellation. (`ctx.suiRpcUrl` is retained for\n * call-site back-compat but no longer used — resolution runs against the\n * canonical GraphQL endpoint via `getSuiGraphQLClient()`.)\n */\nexport async function resolveSuinsViaRpc(\n rawName: string,\n ctx: { suiRpcUrl?: string; signal?: AbortSignal } = {},\n): Promise<string | null> {\n const name = rawName.trim().toLowerCase();\n if (!SUINS_NAME_REGEX.test(name)) {\n throw new InvalidAddressError(rawName);\n }\n\n const gql = getSuiGraphQLClient();\n let res: GqlResult<{ address?: { address?: string } | null }>;\n try {\n res = (await gql.query({\n query: RESOLVE_NAME_QUERY,\n variables: { name },\n signal: ctx.signal,\n })) as typeof res;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new SuinsRpcError(name, msg);\n }\n\n if (res.errors?.length) {\n throw new SuinsRpcError(name, res.errors.map((e) => e.message ?? 'unknown error').join('; '));\n }\n\n // `address(name:)` returns the Address the name points to, or null when the\n // name has never been registered (or has expired and the record was reaped).\n return res.data?.address?.address ?? null;\n}\n\n/**\n * Reverse-resolve a 0x address to its SuiNS name via the Sui GraphQL\n * `address(address:){ defaultNameRecord { domain } }` query. Returns a\n * single-element array with the address's **default (primary)** name, or\n * `[]` when it has none. Throws `SuinsRpcError` on transport failure.\n *\n * Behavior note: the legacy JSON-RPC path returned *all* names for the\n * address; GraphQL exposes the explicitly-configured default record, which is\n * the one every consumer here actually uses (the LLM `resolve_suins` tool +\n * card titles only ever render the primary). Returning `[primary]` keeps the\n * `string[]` contract intact.\n *\n * Why this is its own helper (not folded into `normalizeAddressInput`): a\n * reverse lookup adds a second round-trip per tool call. We don't want every\n * read tool that takes an `address` to silently double its latency. The lookup\n * primitive is opt-in via the `resolve_suins` tool; normalizers stay\n * forward-only.\n */\nexport async function resolveAddressToSuinsViaRpc(\n rawAddress: string,\n ctx: { suiRpcUrl?: string; signal?: AbortSignal } = {},\n): Promise<string[]> {\n const address = rawAddress.trim().toLowerCase();\n if (!SUI_ADDRESS_REGEX.test(address)) {\n throw new InvalidAddressError(rawAddress);\n }\n\n const gql = getSuiGraphQLClient();\n let res: GqlResult<{ address?: { defaultNameRecord?: { domain?: string } | null } | null }>;\n try {\n res = (await gql.query({\n query: REVERSE_NAME_QUERY,\n variables: { address },\n signal: ctx.signal,\n })) as typeof res;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new SuinsRpcError(address, msg);\n }\n\n if (res.errors?.length) {\n throw new SuinsRpcError(address, res.errors.map((e) => e.message ?? 'unknown error').join('; '));\n }\n\n const domain = res.data?.address?.defaultNameRecord?.domain;\n return domain ? [domain] : [];\n}\n\nexport interface NormalizedAddress {\n /**\n * Canonical 0x-prefixed lowercase hex address. Always set on success.\n * Tools should use this for any downstream query (BlockVision, NAVI,\n * positionFetcher, etc.) and for cache keys.\n */\n address: string;\n /**\n * The user-facing name when the input was resolved via SuiNS, otherwise\n * `null`. Tools should stamp this on result data so card titles can\n * render \"Balance · obehi.sui\" instead of \"Balance · 0x1234…abcd\".\n */\n suinsName: string | null;\n /**\n * The original input (pre-normalization). Useful for error narration —\n * \"I tried to resolve `Obehi.Sui` and …\" reads better than the\n * post-trim/lowercase form.\n */\n raw: string;\n}\n\n/**\n * Canonical normalizer. Accepts a 0x address OR a SuiNS name; returns\n * a structured `NormalizedAddress`. Throws:\n * - `InvalidAddressError` if the input matches neither shape.\n * - `SuinsNotRegisteredError` if the SuiNS name is well-formed but\n * resolves to null (= not registered).\n * - `SuinsRpcError` if the RPC fails.\n *\n * Every read tool (engine) and write helper (SDK `T2000.send()`) that\n * accepts a user-supplied recipient MUST call this helper before any\n * downstream lookup. Doing the check inline (1) duplicates the regex,\n * (2) silently rejects SuiNS names, (3) makes cache keys inconsistent\n * across tools.\n */\nexport async function normalizeAddressInput(\n value: string,\n ctx: { suiRpcUrl?: string; signal?: AbortSignal } = {},\n): Promise<NormalizedAddress> {\n const trimmed = value.trim();\n if (SUI_ADDRESS_REGEX.test(trimmed)) {\n return { address: trimmed.toLowerCase(), suinsName: null, raw: value };\n }\n if (looksLikeSuiNs(trimmed)) {\n const name = trimmed.toLowerCase();\n const address = await resolveSuinsViaRpc(name, ctx);\n if (!address) {\n throw new SuinsNotRegisteredError(name);\n }\n return { address: address.toLowerCase(), suinsName: name, raw: value };\n }\n throw new InvalidAddressError(value);\n}\n","import { T2000Error } from './errors.js';\n\n// Private Inference API client (SPEC_AUDRIC_API — agent-native layer, S.575).\n// Key-based access to t2000 Private Inference (OpenAI-compatible) at\n// `api.t2000.ai/v1`. The x402 pay-per-call (no-key) path is a later add; this\n// is the key-based distribution surface used by `t2 chat` + the MCP `t2000_chat`\n// tool. Browser-safe (fetch + ReadableStream only — no wallet/Node deps).\n\nexport const DEFAULT_API_BASE = 'https://api.t2000.ai/v1';\n\nexport interface ChatMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n}\n\nexport interface ChatParams {\n model: string;\n messages: ChatMessage[];\n /** Private Inference key (`sk-…`). Falls back to `T2000_API_KEY` env. */\n apiKey?: string;\n /** Override the API base (default `api.t2000.ai/v1`; e.g. for testing). */\n apiBase?: string;\n maxTokens?: number;\n temperature?: number;\n}\n\nexport interface ChatUsage {\n promptTokens?: number;\n completionTokens?: number;\n totalTokens?: number;\n}\n\nexport interface ChatResult {\n content: string;\n model: string;\n usage?: ChatUsage;\n /** Confidential calls (`phala/*`) return a TEE attestation receipt id —\n * fetch + verify it at `/v1/aci/receipts/{id}`. Absent for ZDR models. */\n receiptId?: string;\n /** The verbatim OpenAI-shaped response body. */\n raw: unknown;\n}\n\nexport interface ApiModel {\n id: string;\n contextWindow?: number;\n inputPer1M?: number;\n outputPer1M?: number;\n /** Privacy tier surfaced by the API (e.g. `zdr`, `confidential`). */\n privacy?: string;\n /** True for reasoning models — deeper but slower (a hidden reasoning trace\n * before the answer). Surfaced so callers pick the speed/depth tradeoff. */\n reasoning?: boolean;\n}\n\nfunction envApiKey(): string | undefined {\n return typeof process !== 'undefined' ? process.env?.T2000_API_KEY : undefined;\n}\n\nfunction resolveApiKey(apiKey?: string): string {\n const key = apiKey ?? envApiKey();\n if (!key) {\n throw new T2000Error(\n 'INVALID_KEY',\n 'No Private Inference key. Pass `apiKey` or set T2000_API_KEY. Generate one at agents.t2000.ai/manage.',\n );\n }\n return key;\n}\n\nasync function failBody(res: Response): Promise<never> {\n const text = await res.text().catch(() => '');\n let msg = text.slice(0, 300);\n try {\n const j = JSON.parse(text) as { error?: { message?: string } | string };\n msg =\n (typeof j.error === 'object' ? j.error?.message : j.error) ?? msg;\n } catch {\n // keep the raw text\n }\n throw new T2000Error(\n 'INFERENCE_FAILED',\n `Inference request failed (${res.status}): ${msg}`,\n { status: res.status },\n res.status >= 500,\n );\n}\n\nfunction usageOf(raw: unknown): ChatUsage | undefined {\n const u = (raw as { usage?: Record<string, number> })?.usage;\n if (!u) {\n return;\n }\n return {\n promptTokens: u.prompt_tokens,\n completionTokens: u.completion_tokens,\n totalTokens: u.total_tokens,\n };\n}\n\nfunction body(params: ChatParams, stream: boolean): string {\n return JSON.stringify({\n model: params.model,\n messages: params.messages,\n // include_usage → the final stream chunk carries usage + x_receipt_id\n // (the confidential attestation receipt) so we can surface it after a stream.\n ...(stream ? { stream: true, stream_options: { include_usage: true } } : {}),\n ...(params.maxTokens != null ? { max_tokens: params.maxTokens } : {}),\n ...(params.temperature != null ? { temperature: params.temperature } : {}),\n });\n}\n\n/** Non-streaming chat completion. Returns the assistant text + usage + the\n * verbatim OpenAI response body. */\nexport async function chatCompletion(params: ChatParams): Promise<ChatResult> {\n const key = resolveApiKey(params.apiKey);\n const base = params.apiBase ?? DEFAULT_API_BASE;\n const res = await fetch(`${base}/chat/completions`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },\n body: body(params, false),\n });\n if (!res.ok) {\n await failBody(res);\n }\n const receiptId = res.headers.get('x-receipt-id') ?? undefined;\n const raw = await res.json();\n const content =\n (raw as { choices?: { message?: { content?: string } }[] })?.choices?.[0]\n ?.message?.content ?? '';\n return {\n content,\n model: (raw as { model?: string })?.model ?? params.model,\n usage: usageOf(raw),\n receiptId,\n raw,\n };\n}\n\n/** Streaming chat completion — yields assistant text deltas as they arrive\n * (parses the OpenAI SSE `data:` frames). */\nexport async function* chatCompletionStream(\n params: ChatParams,\n): AsyncGenerator<string, { receiptId?: string }, unknown> {\n const key = resolveApiKey(params.apiKey);\n const base = params.apiBase ?? DEFAULT_API_BASE;\n const res = await fetch(`${base}/chat/completions`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },\n body: body(params, true),\n });\n if (!(res.ok && res.body)) {\n await failBody(res);\n return {};\n }\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n let receiptId: string | undefined;\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed.startsWith('data:')) {\n continue;\n }\n const data = trimmed.slice(5).trim();\n if (data === '[DONE]') {\n return { receiptId };\n }\n try {\n const json = JSON.parse(data) as {\n choices?: { delta?: { content?: string } }[];\n x_receipt_id?: string;\n };\n // The confidential TEE receipt rides the final usage chunk.\n if (json.x_receipt_id) {\n receiptId = json.x_receipt_id;\n }\n const delta = json.choices?.[0]?.delta?.content;\n if (typeof delta === 'string' && delta) {\n yield delta;\n }\n } catch {\n // keep-alive or partial frame — ignore\n }\n }\n }\n return { receiptId };\n}\n\n/** List Private Inference model catalog (`GET /v1/models`). The key is sent when\n * available but not required (the catalog may be public). */\nexport async function listModels(opts?: {\n apiKey?: string;\n apiBase?: string;\n}): Promise<ApiModel[]> {\n const base = opts?.apiBase ?? DEFAULT_API_BASE;\n const key = opts?.apiKey ?? envApiKey();\n const res = await fetch(`${base}/models`, {\n headers: key ? { authorization: `Bearer ${key}` } : {},\n });\n if (!res.ok) {\n await failBody(res);\n }\n const json = (await res.json()) as {\n data?: {\n id: string;\n context_window?: number;\n context_length?: number;\n privacy?: string;\n privacy_tier?: string;\n reasoning?: boolean;\n pricing?: {\n input_per_1m?: number;\n output_per_1m?: number;\n prompt?: number;\n completion?: number;\n };\n }[];\n };\n const data = Array.isArray(json.data) ? json.data : [];\n return data.map((m) => ({\n id: m.id,\n contextWindow: m.context_window ?? m.context_length,\n inputPer1M: m.pricing?.input_per_1m ?? m.pricing?.prompt,\n outputPer1M: m.pricing?.output_per_1m ?? m.pricing?.completion,\n privacy: m.privacy ?? m.privacy_tier,\n reasoning: m.reasoning,\n }));\n}\n","import { SuiGrpcClient } from '@mysten/sui/grpc';\nimport { ed25519 } from '@noble/curves/ed25519';\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { bytesToHex, hexToBytes } from '@noble/hashes/utils';\nimport { DEFAULT_API_BASE } from './inference.js';\n\n// Confidential receipt verifier (SPEC_CONFIDENTIAL_API v3.0, Phase D).\n//\n// Lets anyone CHECK — not just trust — a t2000 confidential response, by\n// receipt id. The Sui-anchor check is FULLY TRUSTLESS: it reads the on-chain\n// `ReceiptAnchored` event straight from a public Sui fullnode and confirms the\n// committed `wire_hash` + `workload_id` match the signed receipt — t2000 can't\n// forge that (a wrong/missing anchor → fails closed). The confidential-upstream\n// check reads the attestation evidence embedded in the signed receipt\n// (`upstream.verified`).\n//\n// All three core checks are trustless client-side: the Sui anchor (read from a\n// fullnode), the receipt signature (recompute dstack ACI canonical bytes per\n// `canonical.rs` + verify against the attested key — ed25519 current,\n// secp256k1-recover legacy), and the TDX quote\n// (@phala/dcap-qvl chains to Intel's root — removing the server-side-DCAP SPOF).\n// The remaining hop is keyset_endorsement (tying the receipt key to the quote's\n// identity key); the receipt-sig check already proves the receipt is signed by\n// the published keyset key. Per the spec: a wrong \"verifiable\" claim is worse\n// than honest ZDR — so each check states exactly what it proves.\n\nconst RECEIPT_ANCHORED_SUFFIX = '::anchor::ReceiptAnchored';\n\nexport type CheckStatus = 'pass' | 'fail' | 'skip';\nexport type TrustMode = 'trustless' | 'receipt-asserted' | 'roadmap';\n\nexport interface VerifyCheck {\n name: string;\n status: CheckStatus;\n detail: string;\n trust: TrustMode;\n}\n\nexport interface VerifyAnchor {\n txDigest: string;\n anchoredAtMs?: string;\n anchoredBy?: string;\n explorer: string;\n}\n\n/** A typed TCB claim from the attested upstream (dstack ACI §tcb-and-claims). */\nexport interface UpstreamClaim {\n name: string;\n status: string;\n source?: string;\n}\n\nexport interface VerifyUpstream {\n provider?: string;\n modelId?: string;\n result?: string;\n tcbStatus?: string;\n /** The attested-session id (`as_…`) — resolve at GET /v1/aci/sessions/{id}. */\n sessionId?: string;\n /** Typed TCB claims (tee_attested, tcb_up_to_date, gpu_attested, …). */\n claims?: UpstreamClaim[];\n}\n\nexport interface VerifyResult {\n receiptId: string;\n /** True iff the receipt resolved AND its on-chain Sui anchor matches. */\n verified: boolean;\n /** The trustless core: an on-chain ReceiptAnchored event matches the receipt. */\n anchorVerified: boolean;\n checks: VerifyCheck[];\n wireHash?: string;\n workloadId?: string;\n upstream?: VerifyUpstream;\n anchor?: VerifyAnchor;\n}\n\nexport interface VerifyOptions {\n /** Override the API base (default `api.t2000.ai/v1`). */\n apiBase?: string;\n /** Sui network for the trustless anchor read (default `mainnet`). */\n network?: 'mainnet' | 'testnet';\n /** Confidential model id for fetching the attested receipt-signing key\n * (default `phala/glm-5.2`; the gateway key is workload-wide). */\n model?: string;\n /** Skip the local DCAP quote verification (the slower, network-bound check). */\n skipQuote?: boolean;\n}\n\ninterface AciReceiptSignature {\n algo?: string;\n key_id?: string;\n value?: string;\n}\n\ninterface AciReceipt {\n api_version?: string;\n receipt_id?: string;\n chat_id?: string | null;\n workload_id?: string;\n workload_keyset_digest?: string;\n endpoint?: string;\n method?: string;\n served_at?: number;\n signature?: AciReceiptSignature;\n event_log?: {\n type?: string;\n wire_hash?: string;\n result?: string;\n provider?: string;\n upstream_name?: string;\n model_id?: string;\n tcb_status?: string;\n session_id?: string;\n claims?:\n | Record<string, { status?: string; source?: string }>\n | { name?: string; status?: string; source?: string }[];\n }[];\n}\n\n/** Normalize ACI claims (object-map or array) into a typed list. */\nfunction normalizeClaims(\n claims:\n | Record<string, { status?: string; source?: string }>\n | { name?: string; status?: string; source?: string }[]\n | undefined\n): UpstreamClaim[] {\n if (!claims) {\n return [];\n }\n if (Array.isArray(claims)) {\n return claims\n .filter((c) => c.name)\n .map((c) => ({\n name: c.name as string,\n status: c.status ?? 'unknown',\n source: c.source,\n }));\n }\n return Object.entries(claims).map(([name, v]) => ({\n name,\n status: v?.status ?? 'unknown',\n source: v?.source,\n }));\n}\n\nfunction fullnodeUrl(network: 'mainnet' | 'testnet'): string {\n return network === 'testnet'\n ? 'https://fullnode.testnet.sui.io'\n : 'https://fullnode.mainnet.sui.io';\n}\n\ntype Jsonish = string | number | boolean | null | Jsonish[] | { [k: string]: Jsonish };\n\n// JCS (RFC 8785 subset) matching the dstack ACI gateway's `canonical.rs`:\n// object keys sorted by UTF-16 code units (JS default string order on the BMP),\n// integers only, no whitespace. JSON.stringify's string-escaping already matches\n// the gateway's (\\b \\t \\n \\f \\r, \\u00xx for other controls, non-ASCII verbatim).\nfunction jcs(value: Jsonish): string {\n if (value === null) {\n return 'null';\n }\n if (typeof value === 'boolean') {\n return value ? 'true' : 'false';\n }\n if (typeof value === 'number') {\n if (!Number.isInteger(value)) {\n throw new Error('JCS: non-integer number');\n }\n return String(value);\n }\n if (typeof value === 'string') {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map(jcs).join(',')}]`;\n }\n const keys = Object.keys(value).sort();\n return `{${keys.map((k) => `${JSON.stringify(k)}:${jcs(value[k])}`).join(',')}}`;\n}\n\n// Verify the ACI receipt signature. The dstack gateway has shipped two schemes:\n//\n// • `ed25519` (current, key_id `dstack-kms-receipt-ed25519-v1`): a 64-byte\n// signature over the RAW JCS bytes of the receipt exactly as served — every\n// field present (incl. newer ones like `model`), with only `signature.value`\n// omitted. Verified against the attested 32-byte ed25519 key.\n// • `ecdsa-secp256k1` (legacy, §9.4): a 65-byte `r‖s‖v` signature over\n// `sha256(JCS(<the 10 protocol fields>))`; recover the public key and\n// require it to equal the attested key.\n//\n// Returns true only on a genuine match (any error → false).\n// (Module-level export for tests; the public SDK surface is `verifyReceipt`.)\nexport function verifyReceiptSignature(\n receipt: AciReceipt,\n signingKeyHex: string\n): boolean {\n try {\n const sig = receipt.signature;\n if (!sig?.value) {\n return false;\n }\n const endorsed = hexToBytes(signingKeyHex.replace(/^0x/, ''));\n const sigBytes = hexToBytes(sig.value);\n\n if (sig.algo === 'ed25519') {\n if (sigBytes.length !== 64 || endorsed.length !== 32) {\n return false;\n }\n // Canonicalise the receipt AS SERVED (untyped fields included) so the\n // check stays correct when the gateway adds receipt fields — only\n // `signature.value` is stripped.\n const { value: _omitted, ...sigRest } = sig;\n const canonical = {\n ...(receipt as unknown as { [k: string]: Jsonish }),\n signature: sigRest as unknown as Jsonish,\n };\n const msg = new TextEncoder().encode(jcs(canonical));\n return ed25519.verify(sigBytes, msg, endorsed);\n }\n\n if (sig.algo !== 'ecdsa-secp256k1') {\n return false;\n }\n // Legacy: reconstruct the exact canonical value — the 10 protocol fields,\n // with the signature object stripped of `value` (event_log entries are\n // already the flat {seq,type,...fields} shape the gateway canonicalises).\n const canonical: Jsonish = {\n api_version: receipt.api_version ?? '',\n receipt_id: receipt.receipt_id ?? '',\n chat_id: receipt.chat_id ?? null,\n workload_id: receipt.workload_id ?? '',\n workload_keyset_digest: receipt.workload_keyset_digest ?? '',\n endpoint: receipt.endpoint ?? '',\n method: receipt.method ?? '',\n served_at: receipt.served_at ?? 0,\n event_log: (receipt.event_log ?? []) as unknown as Jsonish,\n signature: { algo: sig.algo, key_id: sig.key_id ?? '' },\n };\n const prehash = sha256(new TextEncoder().encode(jcs(canonical)));\n\n if (sigBytes.length !== 65) {\n return false;\n }\n let v = sigBytes[64];\n if (v >= 27 && v <= 30) {\n v -= 27;\n }\n if (v > 3) {\n return false;\n }\n const recovered = secp256k1.Signature.fromCompact(sigBytes.slice(0, 64))\n .addRecoveryBit(v)\n .recoverPublicKey(prehash)\n .toHex(false);\n return recovered.toLowerCase() === bytesToHex(endorsed).toLowerCase();\n } catch {\n return false;\n }\n}\n\ninterface QuoteCheck {\n status: CheckStatus;\n detail: string;\n /** Definitively bad (verify the chain failed) — flips overall `verified`. */\n forged: boolean;\n tcbStatus?: string;\n}\n\n// TDX quote verification — TRUSTLESS, client-side (SPEC_CONFIDENTIAL_API Phase D\n// hardening). This is what removes the server-side-DCAP SPOF: instead of\n// trusting the gateway's `verified:true`, the client re-verifies the quote.\n// 1. @phala/dcap-qvl verifies the TDX quote, chaining to Intel's root CA via\n// PCCS collateral (Intel-signed, so the PCCS is a cache, not a trust point)\n// → genuine enclave + TCB status.\n// 2. confirm the genuine quote's `report_data` commits the report's\n// `signing_address` (the attested gateway identity) — so the report's TEE\n// binding is quote-backed, not fabricated — and that the quote is for the\n// same `workload_id` as the receipt.\n// (Tying the receipt-signing key to the identity key via keyset_endorsement is a\n// further hop; the receipt-signature check already proves the receipt is signed\n// by the published keyset key.)\ninterface AttReport {\n workload_id?: string;\n signing_address?: string;\n attestation?: { evidence?: { quote?: string } };\n}\n\nasync function verifyTdxQuote(\n base: string,\n model: string,\n receiptWorkloadId: string\n): Promise<QuoteCheck> {\n let nonce: string;\n try {\n nonce = bytesToHex(globalThis.crypto.getRandomValues(new Uint8Array(32)));\n } catch {\n return { status: 'skip', detail: 'no secure RNG available', forged: false };\n }\n\n let report: AttReport | undefined;\n try {\n const res = await fetch(\n `${base}/aci/attestation?model=${encodeURIComponent(model)}&nonce=${nonce}`\n );\n if (res.ok) {\n report = ((await res.json()) as { report?: AttReport }).report;\n }\n } catch {\n // network — fall through to skip\n }\n const quoteHex = report?.attestation?.evidence?.quote;\n if (!quoteHex) {\n return {\n status: 'skip',\n detail: 'attestation report (with quote) unavailable — pass --model?',\n forged: false,\n };\n }\n\n try {\n // `@phala/dcap-qvl` is CJS. When the SDK is bundled (e.g. into the CLI) and\n // hit via dynamic import, its named exports land under `.default`; unbundled\n // Node hoists them to the top level. Resolve both so it works either way.\n const dcap = await import('@phala/dcap-qvl');\n const getCollateralAndVerify =\n dcap.getCollateralAndVerify ?? dcap.default?.getCollateralAndVerify;\n if (typeof getCollateralAndVerify !== 'function') {\n return {\n status: 'fail',\n forged: false,\n detail: 'DCAP verifier unavailable in this build',\n };\n }\n const quoteBytes = hexToBytes(quoteHex.replace(/^0x/, ''));\n // Throws if the quote isn't a genuine TDX quote chaining to Intel's root.\n const vr = await getCollateralAndVerify(quoteBytes);\n const td = vr.report.asTd10() ?? vr.report.asTd15()?.base ?? null;\n const reportData = td?.reportData;\n const signingAddr = report?.signing_address?.replace(/^0x/, '').toLowerCase();\n const addrBound = Boolean(\n reportData &&\n signingAddr &&\n bytesToHex(reportData.slice(0, 20)) === signingAddr\n );\n const workloadMatch = report?.workload_id === receiptWorkloadId;\n const tcb = vr.status;\n const tcbBad = tcb === 'Revoked' || tcb === 'Unknown';\n const forged = !(addrBound && workloadMatch) || tcbBad;\n let detail: string;\n if (forged && tcbBad) {\n detail = `genuine TDX but TCB ${tcb}`;\n } else if (!addrBound) {\n detail = \"report_data does NOT commit the report's signing address\";\n } else if (!workloadMatch) {\n detail = \"quote workload_id does not match the receipt's\";\n } else {\n detail = `genuine Intel TDX (verified vs Intel collateral), TCB ${tcb}; report_data commits the attested signing address`;\n }\n return { status: forged ? 'fail' : 'pass', forged, tcbStatus: tcb, detail };\n } catch (e) {\n // A thrown verify is usually a PCCS/collateral/network issue, not a real\n // forgery from our own gateway — surface it but don't claim \"forged\".\n return {\n status: 'fail',\n forged: false,\n detail: `could not verify the quote: ${e instanceof Error ? e.message : 'error'}`,\n };\n }\n}\n\n/**\n * Verify a confidential response by its receipt id. Reads the signed receipt\n * (public), its on-chain Sui anchor (trustless), and reports a per-check result\n * that FAILS CLOSED on any forgery or mismatch.\n */\nexport async function verifyReceipt(\n receiptId: string,\n opts: VerifyOptions = {},\n): Promise<VerifyResult> {\n const base = opts.apiBase ?? DEFAULT_API_BASE;\n const network = opts.network ?? 'mainnet';\n const checks: VerifyCheck[] = [];\n\n // === 1. Receipt — fetch + structural soundness (public, no key) ===\n let receipt: AciReceipt | null = null;\n try {\n const res = await fetch(`${base}/aci/receipts/${encodeURIComponent(receiptId)}`);\n if (res.ok) {\n receipt = (await res.json()) as AciReceipt;\n }\n } catch {\n // network error → receipt stays null → fails closed below\n }\n if (!receipt?.event_log) {\n checks.push({\n name: 'Receipt',\n status: 'fail',\n detail: 'receipt not found or malformed',\n trust: 'receipt-asserted',\n });\n return { receiptId, verified: false, anchorVerified: false, checks };\n }\n const wireHash = receipt.event_log.find((e) => e.type === 'response.returned')\n ?.wire_hash;\n const workloadId = receipt.workload_id;\n checks.push({\n name: 'Receipt',\n status: wireHash && workloadId ? 'pass' : 'fail',\n detail: wireHash\n ? `well-formed (${receipt.event_log.length} log entries, workload ${workloadId})`\n : 'missing response wire_hash / workload_id',\n trust: 'receipt-asserted',\n });\n\n // === 2. Confidential upstream — attestation evidence in the signed receipt ===\n const upstreamEv = receipt.event_log.find((e) => e.type === 'upstream.verified');\n const upstreamOk = upstreamEv?.result === 'verified';\n const claims = normalizeClaims(upstreamEv?.claims);\n checks.push({\n name: 'Confidential upstream',\n status: upstreamEv ? (upstreamOk ? 'pass' : 'fail') : 'skip',\n detail: upstreamEv\n ? `${upstreamEv.provider ?? upstreamEv.upstream_name ?? 'upstream'}: ${upstreamEv.result ?? 'unknown'}${upstreamEv.tcb_status ? ` (TCB ${upstreamEv.tcb_status})` : ''}`\n : 'no upstream.verified event (routed/non-confidential?)',\n trust: 'receipt-asserted',\n });\n\n // === 3. Sui anchor — TRUSTLESS: read the on-chain event from a fullnode ===\n let anchorVerified = false;\n let anchor: VerifyAnchor | undefined;\n let digest: string | undefined;\n try {\n const res = await fetch(`${base}/aci/anchor/${encodeURIComponent(receiptId)}`);\n if (res.ok) {\n const j = (await res.json()) as { txDigest?: string };\n digest = j.txDigest;\n }\n } catch {\n // no anchor lookup → fails the anchor check below\n }\n if (!digest) {\n checks.push({\n name: 'Sui anchor',\n status: 'fail',\n detail: `no anchor on record — POST ${base}/aci/anchor/${receiptId} to create one`,\n trust: 'trustless',\n });\n } else {\n try {\n const client = new SuiGrpcClient({ baseUrl: fullnodeUrl(network), network });\n const tx = await client.core.getTransaction({\n digest,\n include: { events: true },\n });\n const txn = tx.$kind === 'Transaction' ? tx.Transaction : tx.FailedTransaction;\n const ev = (txn.events ?? []).find((e) =>\n e.eventType.endsWith(RECEIPT_ANCHORED_SUFFIX),\n );\n const data = (ev?.json ?? {}) as Record<string, unknown>;\n const onChainReceipt = String(data.receipt_id ?? '');\n const onChainWire = String(data.wire_hash ?? '');\n const onChainWorkload = String(data.workload_id ?? '');\n const matches =\n onChainReceipt === receiptId &&\n onChainWire === wireHash &&\n onChainWorkload === workloadId;\n anchorVerified = matches;\n anchor = {\n txDigest: digest,\n anchoredAtMs: data.anchored_at_ms ? String(data.anchored_at_ms) : undefined,\n anchoredBy: data.anchored_by ? String(data.anchored_by) : undefined,\n explorer: `https://suiscan.xyz/${network}/tx/${digest}`,\n };\n checks.push({\n name: 'Sui anchor',\n status: matches ? 'pass' : 'fail',\n detail: matches\n ? `on-chain ReceiptAnchored matches (wire_hash + workload_id), tx ${digest}`\n : `on-chain event does NOT match the receipt (wire ${onChainWire || 'absent'})`,\n trust: 'trustless',\n });\n } catch (e) {\n checks.push({\n name: 'Sui anchor',\n status: 'fail',\n detail: `could not read anchor tx ${digest}: ${e instanceof Error ? e.message : 'error'}`,\n trust: 'trustless',\n });\n }\n }\n\n // === 4. Receipt signature — recover the signer + match the attested key ===\n // The signing key (gateway receipt key) is workload-wide; fetch the attested\n // keyset and confirm its workload matches this receipt before trusting it.\n let sigStatus: CheckStatus = 'skip';\n let sigDetail = 'no signature on receipt';\n if (receipt.signature?.value) {\n try {\n const model = opts.model ?? 'phala/glm-5.2';\n const res = await fetch(\n `${base}/aci/attestation?model=${encodeURIComponent(model)}`,\n );\n const att = res.ok\n ? ((await res.json()) as { signingKey?: string; workloadId?: string })\n : null;\n if (!att?.signingKey) {\n sigDetail = 'could not fetch the attested keyset to check the signature';\n } else if (att.workloadId && att.workloadId !== workloadId) {\n sigDetail = `attested keyset is for a different workload — pass --model for ${workloadId}`;\n } else {\n const ok = verifyReceiptSignature(receipt, att.signingKey);\n sigStatus = ok ? 'pass' : 'fail';\n sigDetail = ok\n ? `signed by the attested receipt key (${receipt.signature.key_id ?? 'key'})`\n : 'signature does NOT recover the attested receipt key — forged/altered';\n }\n } catch {\n sigDetail = 'signature check errored';\n }\n }\n checks.push({\n name: 'Receipt signature',\n status: sigStatus,\n detail: sigDetail,\n trust: sigStatus === 'skip' ? 'roadmap' : 'trustless',\n });\n\n // === 5. TDX quote (DCAP) — verify the quote genuine + fresh, client-side ===\n if (opts.skipQuote) {\n checks.push({\n name: 'TDX quote (DCAP)',\n status: 'skip',\n detail: 'skipped (--quick)',\n trust: 'trustless',\n });\n } else {\n const q = await verifyTdxQuote(\n base,\n opts.model ?? 'phala/glm-5.2',\n workloadId ?? ''\n );\n checks.push({\n name: 'TDX quote (DCAP)',\n status: q.status,\n detail: q.detail,\n trust: 'trustless',\n });\n }\n\n // FAIL CLOSED: a sound receipt AND no trustless check left in `fail`. A DCAP\n // (or anchor/signature) check that errored counts as fail — \"couldn't prove\"\n // is \"not verified\"; we never report verified on an unchecked/failed quote.\n const trustlessFailed = checks.some(\n (c) => c.trust === 'trustless' && c.status === 'fail'\n );\n return {\n receiptId,\n verified: Boolean(wireHash && workloadId) && !trustlessFailed,\n anchorVerified,\n checks,\n wireHash,\n workloadId,\n upstream: upstreamEv\n ? {\n provider: upstreamEv.provider ?? upstreamEv.upstream_name,\n modelId: upstreamEv.model_id,\n result: upstreamEv.result,\n tcbStatus: upstreamEv.tcb_status,\n sessionId: upstreamEv.session_id,\n claims: claims.length > 0 ? claims : undefined,\n }\n : undefined,\n anchor,\n };\n}\n","// Unified spending-limit config store (`~/.t2000/config.json`). Moved here from\n// the CLI (`lib/config-store.ts`) + the SDK `SafeguardEnforcer` so ONE gate\n// serves CLI + MCP + programmatic writes (closes the H5 gap — R-0 Finding 1).\n//\n// Node-only (uses `node:fs`) — NOT re-exported from `browser.ts`. The browser\n// (Audric) write path skips client-side limits entirely; the server budget\n// ledger is the cap there.\n//\n// Schema (`~/.t2000/config.json`):\n// { \"limits\": { \"perTxUsd\": 25, \"dailyUsd\": 100 },\n// \"dailySpend\": { \"date\": \"2026-06-15\", \"usd\": 12.5 } }\n//\n// `daily` is CUMULATIVE across all outbound writes (send + swap + pay) since\n// midnight UTC — matches the engine's `autonomousDailyLimit` + the user mental\n// model (\"$100/day total\", not \"$100 per send\"). Locked S.424.\n\nimport { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';\nimport { join, dirname } from 'node:path';\nimport { homedir } from 'node:os';\n\nexport interface LimitsConfig {\n /** Caps any single outbound write (send | swap | pay) by USD value. */\n perTxUsd?: number;\n /** Caps CUMULATIVE outbound spend (all writes) per UTC day, by USD value. */\n dailyUsd?: number;\n}\n\nexport interface DailySpend {\n /** UTC date `YYYY-MM-DD` the running total applies to. */\n date: string;\n /** USD spent so far on `date`. */\n usd: number;\n}\n\nexport interface LimitsFile {\n limits?: LimitsConfig;\n dailySpend?: DailySpend;\n}\n\nconst DEFAULT_CONFIG_DIR = join(homedir(), '.t2000');\n\nexport function resolveConfigPath(configDir?: string): string {\n return join(configDir ?? DEFAULT_CONFIG_DIR, 'config.json');\n}\n\n/** UTC date `YYYY-MM-DD`. */\nexport function todayUtc(): string {\n return new Date().toISOString().slice(0, 10);\n}\n\nexport function readLimitsFile(configDir?: string): LimitsFile {\n const path = resolveConfigPath(configDir);\n try {\n return sanitize(JSON.parse(readFileSync(path, 'utf-8')));\n } catch {\n return {};\n }\n}\n\n/**\n * Write the limits + dailySpend keys, PRESERVING any other keys already on\n * disk (a config file may carry unrelated data). Mode 0600.\n */\nexport function writeLimitsFile(file: LimitsFile, configDir?: string): string {\n const path = resolveConfigPath(configDir);\n let existing: Record<string, unknown> = {};\n try {\n existing = JSON.parse(readFileSync(path, 'utf-8'));\n } catch {\n existing = {};\n }\n // Drop the dead v3 SafeguardEnforcer keys if present (maxPerTx/maxDailySend/\n // dailyUsed/dailyResetDate/locked) — they were never read by v4 and are\n // replaced by `limits` + `dailySpend`.\n for (const dead of ['maxPerTx', 'maxDailySend', 'dailyUsed', 'dailyResetDate', 'locked']) {\n delete existing[dead];\n }\n const merged: Record<string, unknown> = { ...existing };\n if (file.limits && (file.limits.perTxUsd !== undefined || file.limits.dailyUsd !== undefined)) {\n merged.limits = file.limits;\n } else {\n delete merged.limits;\n }\n if (file.dailySpend) merged.dailySpend = file.dailySpend;\n else delete merged.dailySpend;\n\n const dir = dirname(path);\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n writeFileSync(path, JSON.stringify(merged, null, 2) + '\\n', { mode: 0o600 });\n return path;\n}\n\nexport function getLimits(configDir?: string): LimitsConfig | undefined {\n return readLimitsFile(configDir).limits;\n}\n\nexport function hasLimits(configDir?: string): boolean {\n const l = readLimitsFile(configDir).limits;\n return !!l && (l.perTxUsd !== undefined || l.dailyUsd !== undefined);\n}\n\n/** Merge-set limits (only provided fields change). Returns the written path. */\nexport function setLimits(limits: LimitsConfig, configDir?: string): string {\n const file = readLimitsFile(configDir);\n const merged: LimitsConfig = { ...file.limits };\n if (limits.perTxUsd !== undefined) merged.perTxUsd = limits.perTxUsd;\n if (limits.dailyUsd !== undefined) merged.dailyUsd = limits.dailyUsd;\n return writeLimitsFile({ ...file, limits: merged }, configDir);\n}\n\n/** Remove all limits (keeps the dailySpend ledger). Returns the written path. */\nexport function clearLimits(configDir?: string): string {\n const file = readLimitsFile(configDir);\n return writeLimitsFile({ ...file, limits: undefined }, configDir);\n}\n\n/** Cumulative USD spent so far today (0 when the ledger is from a prior day). */\nexport function dailySpentToday(configDir?: string): number {\n const { dailySpend } = readLimitsFile(configDir);\n if (!dailySpend || dailySpend.date !== todayUtc()) return 0;\n return dailySpend.usd;\n}\n\n/** Add `usd` to today's running total (resets on UTC date rollover). */\nexport function recordDailySpend(usd: number, configDir?: string): void {\n if (!Number.isFinite(usd) || usd <= 0) return;\n const file = readLimitsFile(configDir);\n const today = todayUtc();\n const prior = file.dailySpend && file.dailySpend.date === today ? file.dailySpend.usd : 0;\n writeLimitsFile({ ...file, dailySpend: { date: today, usd: prior + usd } }, configDir);\n}\n\nfunction sanitize(raw: unknown): LimitsFile {\n if (typeof raw !== 'object' || raw === null) return {};\n const r = raw as Record<string, unknown>;\n const out: LimitsFile = {};\n\n if (typeof r.limits === 'object' && r.limits !== null) {\n const l = r.limits as Record<string, unknown>;\n const limits: LimitsConfig = {};\n if (typeof l.perTxUsd === 'number' && l.perTxUsd > 0) limits.perTxUsd = l.perTxUsd;\n // Migrate the legacy `dailySendUsd` (v4 CLI, per-send sub-cap) → `dailyUsd`\n // (cumulative all-writes). New canonical key wins if both are present.\n if (typeof l.dailyUsd === 'number' && l.dailyUsd > 0) limits.dailyUsd = l.dailyUsd;\n else if (typeof l.dailySendUsd === 'number' && l.dailySendUsd > 0) limits.dailyUsd = l.dailySendUsd;\n if (limits.perTxUsd !== undefined || limits.dailyUsd !== undefined) out.limits = limits;\n }\n\n if (typeof r.dailySpend === 'object' && r.dailySpend !== null) {\n const d = r.dailySpend as Record<string, unknown>;\n if (typeof d.date === 'string' && typeof d.usd === 'number' && d.usd >= 0) {\n out.dailySpend = { date: d.date, usd: d.usd };\n }\n }\n\n return out;\n}\n","// Spending-limit error — thrown by the unified limits gate (`@t2000/sdk/limits`)\n// when an outbound write exceeds an opted-in cap. Shared by CLI + MCP +\n// programmatic callers (the gate lives in the SDK write paths). Carries a\n// structured shape so the CLI can render `--json` output and the MCP can\n// surface a typed failure.\n\nexport type LimitKind = 'perTxUsd' | 'dailyUsd';\nexport type LimitOperation = 'send' | 'swap' | 'pay';\n\nexport class LimitExceededError extends Error {\n readonly code = 'LIMIT_EXCEEDED';\n readonly operation: LimitOperation;\n readonly limitKind: LimitKind;\n readonly limit: number;\n readonly attempted: number;\n\n constructor(params: {\n operation: LimitOperation;\n limitKind: LimitKind;\n limit: number;\n attempted: number;\n }) {\n const label = params.limitKind === 'perTxUsd' ? 'per-transaction limit' : 'daily spend limit';\n super(\n `Exceeds ${label} ($${params.limit}). Attempted $${params.attempted.toFixed(2)}. Use --force / force:true to override.`,\n );\n this.name = 'LimitExceededError';\n this.operation = params.operation;\n this.limitKind = params.limitKind;\n this.limit = params.limit;\n this.attempted = params.attempted;\n }\n\n toJSON(): unknown {\n return {\n error: this.code,\n message: this.message,\n operation: this.operation,\n limitKind: this.limitKind,\n limit: this.limit,\n attempted: this.attempted,\n };\n }\n}\n","// The unified spending-limit gate. ONE enforcer for CLI + MCP + programmatic\n// writes — wired into the T2000 write paths (send / swap / pay), so every\n// surface that calls those methods inherits the same cap (closes H5).\n//\n// USD-denominated. `perTxUsd` caps any single write; `dailyUsd` caps the\n// CUMULATIVE spend across all writes since UTC midnight (the running total\n// lives in the `dailySpend` ledger). `force` bypasses both — the caller owns\n// the prompt/consent.\n\nimport {\n type LimitsConfig,\n getLimits,\n setLimits,\n clearLimits,\n hasLimits,\n dailySpentToday,\n recordDailySpend,\n} from './config.js';\nimport { LimitExceededError, type LimitOperation } from './errors.js';\n\n/**\n * Best-effort USD value for an asset+amount pair, for the limit gate. Stables\n * are 1:1; SUI (and anything else) returns `null` — \"unknown, don't gate\".\n * The limits are USD-denominated; SUI-USD gating would need a price lookup and\n * is intentionally out of scope (matches the prior CLI behavior).\n */\nexport function approxUsdValue(asset: string, amount: number): number | null {\n const symbol = asset.toUpperCase();\n if (symbol === 'USDC' || symbol === 'USDSUI') return amount;\n return null;\n}\n\n/**\n * Pure gate — no I/O. Returns silently when allowed; throws\n * `LimitExceededError` when blocked.\n */\nexport function assertLimitConfig(input: {\n limits: LimitsConfig | undefined;\n spentTodayUsd: number;\n operation: LimitOperation;\n amountUsd: number;\n force?: boolean;\n}): void {\n if (input.force) return;\n if (!Number.isFinite(input.amountUsd) || input.amountUsd <= 0) return;\n const { limits } = input;\n if (!limits) return;\n\n if (limits.perTxUsd !== undefined && input.amountUsd > limits.perTxUsd) {\n throw new LimitExceededError({\n operation: input.operation,\n limitKind: 'perTxUsd',\n limit: limits.perTxUsd,\n attempted: input.amountUsd,\n });\n }\n\n if (limits.dailyUsd !== undefined && input.spentTodayUsd + input.amountUsd > limits.dailyUsd) {\n throw new LimitExceededError({\n operation: input.operation,\n limitKind: 'dailyUsd',\n // The cap is total/day; report the cap (attempted is THIS write's USD).\n limit: limits.dailyUsd,\n attempted: input.spentTodayUsd + input.amountUsd,\n });\n }\n}\n\nexport interface LimitAssertInput {\n operation: LimitOperation;\n /** This write's USD value. Pass 0 / non-positive to skip (e.g. SUI sends). */\n amountUsd: number;\n /** When true, skip the gate. */\n force?: boolean;\n}\n\n/**\n * The spending-limit enforcer — reads/writes `~/.t2000/config.json` (or a\n * `configDir` override for tests). Constructed once by the T2000 agent and\n * called around every outbound write; also drives the CLI `t2 limit` commands.\n */\nexport class LimitEnforcer {\n constructor(private readonly configDir?: string) {}\n\n /** Throws `LimitExceededError` when the write exceeds an opted-in cap. */\n assert(input: LimitAssertInput): void {\n assertLimitConfig({\n limits: getLimits(this.configDir),\n spentTodayUsd: dailySpentToday(this.configDir),\n operation: input.operation,\n amountUsd: input.amountUsd,\n force: input.force,\n });\n }\n\n /** Add a settled write's USD value to today's cumulative total. */\n record(amountUsd: number): void {\n recordDailySpend(amountUsd, this.configDir);\n }\n\n getLimits(): LimitsConfig | undefined {\n return getLimits(this.configDir);\n }\n\n hasLimits(): boolean {\n return hasLimits(this.configDir);\n }\n\n setLimits(limits: LimitsConfig): void {\n setLimits(limits, this.configDir);\n }\n\n clearLimits(): void {\n clearLimits(this.configDir);\n }\n\n dailySpentToday(): number {\n return dailySpentToday(this.configDir);\n }\n}\n","export { T2000 } from './t2000.js';\nexport type { TransactionSigner } from './signer.js';\nexport { KeypairSigner } from './wallet/keypairSigner.js';\nexport { ZkLoginSigner, type ZkLoginProof } from './wallet/zkLoginSigner.js';\nexport { payWithMpp, preflightPay, parseMppSuiChallenge } from './wallet/pay.js';\nexport {\n chatCompletion,\n chatCompletionStream,\n listModels,\n DEFAULT_API_BASE,\n} from './inference.js';\nexport type {\n ChatMessage,\n ChatParams,\n ChatResult,\n ChatUsage,\n ApiModel,\n} from './inference.js';\nexport { verifyReceipt } from './verify.js';\nexport type {\n VerifyResult,\n VerifyCheck,\n VerifyAnchor,\n VerifyUpstream,\n UpstreamClaim,\n VerifyOptions,\n CheckStatus,\n TrustMode,\n} from './verify.js';\nexport { executeTx } from './wallet/executeTx.js';\nexport { T2000Error, mapWalletError, mapMoveAbortCode } from './errors.js';\nexport type { T2000ErrorCode, T2000ErrorData } from './errors.js';\nexport type {\n T2000Options,\n BalanceResponse,\n SuiHolding,\n SendResult,\n DepositInfo,\n PaymentRequest,\n TransactionRecord,\n TransactionLeg,\n PayOptions,\n PayResult,\n SwapResult,\n SwapQuoteResult,\n} from './types.js';\nexport {\n MIST_PER_SUI,\n SUI_DECIMALS,\n USDC_DECIMALS,\n T2000_OVERLAY_FEE_WALLET,\n SUPPORTED_ASSETS,\n CLOCK_ID,\n DEFAULT_NETWORK,\n} from './constants.js';\nexport type { SupportedAsset, StableAsset, SendableAsset } from './constants.js';\nexport {\n STABLE_ASSETS,\n SENDABLE_ASSETS,\n GASLESS_MIN_STABLE_AMOUNT,\n GASLESS_STABLE_TYPES,\n DEFAULT_GRPC_URL,\n GAS_RESERVE_MIN,\n CETUS_USDC_SUI_POOL,\n OPERATION_ASSETS,\n isAllowedAsset,\n assertAllowedAsset,\n} from './constants.js';\nexport type { Operation } from './constants.js';\nexport {\n validateAddress,\n truncateAddress,\n normalizeCoinType,\n getSuiClient,\n getSuiGrpcClient,\n} from './utils/sui.js';\nexport {\n SUI_ADDRESS_REGEX,\n SUI_ADDRESS_STRICT_REGEX,\n SUINS_NAME_REGEX,\n InvalidAddressError,\n SuinsNotRegisteredError,\n SuinsRpcError,\n looksLikeSuiNs,\n resolveSuinsViaRpc,\n resolveAddressToSuinsViaRpc,\n normalizeAddressInput,\n} from './utils/suins.js';\nexport type { NormalizedAddress } from './utils/suins.js';\nexport {\n KNOWN_TARGETS,\n LABEL_PATTERNS,\n classifyAction,\n classifyLabel,\n fallbackLabel,\n refineLendingLabel,\n classifyTransaction,\n extractTransferDetails,\n extractAllUserLegs,\n} from './wallet/classify.js';\nexport type {\n ClassifyBalanceChange,\n ClassifyResult,\n ExtractedTransfer,\n TxDirection,\n} from './wallet/classify.js';\nexport {\n parseSuiRpcTx,\n extractTxSender,\n extractTxCommands,\n queryHistory,\n queryTransaction,\n} from './wallet/history.js';\nexport type { SuiRpcTxBlock } from './wallet/history.js';\nexport { queryBalance } from './wallet/balance.js';\nexport {\n mistToSui,\n suiToMist,\n usdcToRaw,\n rawToUsdc,\n stableToRaw,\n rawToStable,\n getDecimals,\n formatUsd,\n formatSui,\n formatAssetAmount,\n normalizeAsset,\n} from './utils/format.js';\nexport {\n generateKeypair,\n keypairFromPrivateKey,\n saveKey,\n saveBech32,\n loadKey,\n walletExists,\n exportPrivateKey,\n getAddress,\n} from './wallet/keyManager.js';\nexport { buildSendTx, addSendToTx, preflightSend } from './wallet/send.js';\nexport {\n A2A_ESCROW_PACKAGE_ID,\n MAX_JOB_USDC,\n JOB_STATES,\n preflightCreateJob,\n buildCreateJobTx,\n buildDeliverJobTx,\n buildReleaseJobTx,\n buildRejectJobTx,\n buildRefundJobTx,\n getJob,\n jobActionsFor,\n verifyJobForSeller,\n} from './wallet/job.js';\nexport type { Job, JobState, JobTerms, JobVerification } from './wallet/job.js';\nexport {\n fetchAllCoins,\n selectAndSplitCoin,\n selectSuiCoin,\n} from './wallet/coinSelection.js';\nexport type { CoinPage, SelectAndSplitResult } from './wallet/coinSelection.js';\nexport {\n composeTx,\n deriveAllowedAddressesFromPtb,\n WRITE_APPENDER_REGISTRY,\n SPONSORED_PYTH_DEPENDENT_PROVIDERS,\n getSponsoredSwapProviders,\n} from './composeTx.js';\nexport type {\n WriteToolName,\n WriteStep,\n ComposeTxOptions,\n ComposeTxResult,\n AppenderContext,\n StepPreview,\n SendTransferInput,\n SwapExecuteInput,\n} from './composeTx.js';\nexport { simulateTransaction, throwIfSimulationFailed } from './utils/simulate.js';\nexport type { SimulationResult } from './utils/simulate.js';\nexport { getSwapQuote } from './swap-quote.js';\nexport {\n findSwapRoute,\n buildSwapTx,\n addSwapToTx,\n preflightSwap,\n OVERLAY_FEE_RATE,\n serializeCetusRoute,\n deserializeCetusRoute,\n verifyCetusRouteCoinMatch,\n isCetusRouteFresh,\n} from './protocols/cetus-swap.js';\nexport type {\n SwapRouteResult,\n OverlayFeeConfig,\n SerializedCetusRoute,\n SerializedRouterDataV3,\n SerializedCetusRoutePath,\n} from './protocols/cetus-swap.js';\nexport {\n COIN_REGISTRY,\n TOKEN_MAP,\n resolveTokenType,\n resolveSymbol,\n getDecimalsForCoinType,\n getCoinMeta,\n isInRegistry,\n SUI_TYPE,\n USDC_TYPE,\n USDT_TYPE,\n USDSUI_TYPE,\n USDE_TYPE,\n ETH_TYPE,\n WBTC_TYPE,\n WAL_TYPE,\n NAVX_TYPE,\n IKA_TYPE,\n LOFI_TYPE,\n MANIFEST_TYPE,\n} from './token-registry.js';\nexport type { CoinMeta } from './token-registry.js';\n// [S.323 / 2026-05-25] VOLO vSUI staking re-exports removed (full cut).\n// vSUI still exists in the codebase as a passive token (NAVI reward type\n// + Cetus swap target), but t2000 no longer exposes mint/redeem surfaces.\nexport {\n AGENT_ID_PARENT,\n AGENT_ID_PARENT_NAME,\n AGENT_ID_PARENT_NFT_ID,\n AUDRIC_PARENT,\n AUDRIC_PARENT_NAME,\n AUDRIC_PARENT_NFT_ID,\n buildAddLeafTx,\n buildRevokeLeafTx,\n displayHandle,\n fullHandle,\n validateLabel,\n} from './protocols/suins-leaf.js';\nexport type {\n BuildAddLeafParams,\n BuildRevokeLeafParams,\n LabelValidationResult,\n SuinsParent,\n} from './protocols/suins-leaf.js';\n// Unified spending limits (per-tx + cumulative daily, USD) — one gate for\n// CLI + MCP + programmatic writes (R-0 Finding 1; closes H5). Node-only.\nexport {\n LimitEnforcer,\n LimitExceededError,\n approxUsdValue,\n assertLimitConfig,\n getLimits,\n hasLimits,\n setLimits,\n clearLimits,\n dailySpentToday,\n recordDailySpend,\n readLimitsFile,\n writeLimitsFile,\n} from './limits/index.js';\nexport type { LimitsConfig, DailySpend, LimitsFile, LimitKind, LimitOperation, LimitAssertInput } from './limits/index.js';\n// Synchronous, network-free preflight (layer 2) — pure input validation the\n// v3 host runs before the LLM round-trip / tap-to-confirm. Per-builder\n// validators (`preflightSend`/`preflightPay`/`preflightSwap`) are exported\n// alongside their builders above; these are the shared primitives.\nexport {\n type PreflightResult,\n PREFLIGHT_MAX_AMOUNT,\n PREFLIGHT_OK,\n preflightFail,\n checkPositiveAmount,\n checkSuiAddress,\n} from './preflight.js';\n","import { Transaction } from '@mysten/sui/transactions';\nimport { T2000Error } from '../errors.js';\nimport { USDC_TYPE } from '../token-registry.js';\nimport { USDC_DECIMALS } from '../constants.js';\nimport {\n type PreflightResult,\n PREFLIGHT_OK,\n preflightFail,\n checkSuiAddress,\n} from '../preflight.js';\nimport { validateAddress, type SuiCoreClient } from '../utils/sui.js';\nimport { selectAndSplitCoin } from './coinSelection.js';\n\n/**\n * A2A Escrow — client for the `a2a_escrow::escrow` Move package\n * (SPEC_A2A_ESCROW, t2 Agents Phase 3).\n *\n * One shared `Job<USDC>` object per engagement; the escrow balance lives IN\n * the object (no treasury, no admin key). These builders construct UNSIGNED\n * transactions; the caller signs (buyer for create/release/reject, seller\n * for deliver, ANYONE for the two timeout cranks) and may sponsor gas — the\n * Move calls authorize on `ctx.sender()`, so sponsorship never weakens auth.\n *\n * Browser-safe (no fs / keyManager imports) so store surfaces can build the\n * buyer-side legs on a zkLogin session key.\n *\n * Deployed on Sui mainnet 2026-07-17. Override via env for testnet/dev.\n */\n\n/** The published `a2a_escrow` package id (mainnet). */\nexport const A2A_ESCROW_PACKAGE_ID =\n process.env.A2A_ESCROW_PACKAGE_ID ??\n '0x9e67c380fb7079d793d6d15ff916b24d82779d7119bfa4631863102ed485c0a0';\n\nconst CLOCK_ID = '0x6';\nconst MODULE = 'escrow';\n\n/** v1 job-value cap in USDC — same instinct as the catalog price cap: the\n * no-arbitration reject-split is only fair at sizes where neither side is\n * incentivized to game it (SPEC_A2A_ESCROW §2). */\nexport const MAX_JOB_USDC = 50;\n\n/** Job lifecycle states, mirroring the Move constants. */\nexport const JOB_STATES = [\n 'funded',\n 'delivered',\n 'released',\n 'refunded',\n 'rejected',\n] as const;\nexport type JobState = (typeof JOB_STATES)[number];\n\nexport interface JobTerms {\n /** The seller's wallet (the listing's payTo / claimed Agent ID wallet). */\n seller: string;\n /** Job value in display USDC (e.g. `5` = 5 USDC). ≤ `MAX_JOB_USDC`. */\n amountUsdc: number;\n /** Hash/commitment of the job spec (hex string, `0x…` or bare). */\n specHash: string;\n /** Epoch-ms deadline the seller must deliver by. */\n deliverByMs: number;\n /** Buyer's accept/reject window (ms) after delivery; lapse = release. */\n reviewWindowMs: number;\n /** Buyer's share in basis points on reject (0–10000). Fixed at create. */\n rejectSplitBps: number;\n}\n\n/** Parsed on-chain `Job` object. */\nexport interface Job {\n id: string;\n buyer: string;\n seller: string;\n /** Locked amount in display USDC (immutable record). */\n amountUsdc: number;\n /** What's still in the object — 0 after settlement. */\n escrowUsdc: number;\n specHash: string;\n deliverByMs: number;\n reviewWindowMs: number;\n rejectSplitBps: number;\n state: JobState;\n deliveryHash: string | null;\n deliveredAtMs: number | null;\n createdAtMs: number;\n}\n\n// ---------------------------------------------------------------------------\n// Hash plumbing — spec/delivery commitments travel as vector<u8>.\n// ---------------------------------------------------------------------------\n\nfunction hexToBytes(hex: string): number[] {\n const clean = hex.startsWith('0x') ? hex.slice(2) : hex;\n if (clean.length === 0 || clean.length % 2 !== 0 || /[^0-9a-fA-F]/.test(clean)) {\n throw new T2000Error(\n 'INVALID_AMOUNT',\n `Expected a hex hash (0x…), got \"${hex.slice(0, 32)}\"`,\n );\n }\n const out: number[] = [];\n for (let i = 0; i < clean.length; i += 2) {\n out.push(Number.parseInt(clean.slice(i, i + 2), 16));\n }\n return out;\n}\n\n/** gRPC's `json` include renders Move `vector<u8>` as a base64 STRING;\n * JSON-RPC (and tests) hand back number arrays. Accept both. */\nfunction bytesToHex(bytes: number[] | Uint8Array | string): string {\n const arr =\n typeof bytes === 'string'\n ? Array.from(atob(bytes), (c) => c.charCodeAt(0))\n : bytes;\n let s = '0x';\n for (const b of arr) s += b.toString(16).padStart(2, '0');\n return s;\n}\n\n// ---------------------------------------------------------------------------\n// Preflight\n// ---------------------------------------------------------------------------\n\n/**\n * Synchronous, network-free preflight for `create`. Terms sanity only —\n * the balance read happens in `buildCreateJobTx`.\n */\nexport function preflightCreateJob(terms: JobTerms): PreflightResult {\n const addressCheck = checkSuiAddress(terms.seller);\n if (!addressCheck.valid) return addressCheck;\n if (!Number.isFinite(terms.amountUsdc) || terms.amountUsdc <= 0) {\n return preflightFail('INVALID_AMOUNT', `Amount must be positive. Got ${terms.amountUsdc}.`);\n }\n if (terms.amountUsdc > MAX_JOB_USDC) {\n return preflightFail(\n 'INVALID_AMOUNT',\n `v1 caps escrow jobs at ${MAX_JOB_USDC} USDC (no-arbitration split only stays fair at small sizes). Got ${terms.amountUsdc}.`,\n );\n }\n if (terms.deliverByMs <= Date.now()) {\n return preflightFail('INVALID_AMOUNT', 'deliverByMs must be in the future.');\n }\n if (terms.reviewWindowMs < 0) {\n return preflightFail('INVALID_AMOUNT', 'reviewWindowMs must be ≥ 0.');\n }\n if (\n !Number.isInteger(terms.rejectSplitBps) ||\n terms.rejectSplitBps < 0 ||\n terms.rejectSplitBps > 10_000\n ) {\n return preflightFail('INVALID_AMOUNT', 'rejectSplitBps must be an integer 0–10000.');\n }\n try {\n hexToBytes(terms.specHash);\n } catch (e) {\n return preflightFail('INVALID_AMOUNT', (e as T2000Error).message);\n }\n return PREFLIGHT_OK;\n}\n\n// ---------------------------------------------------------------------------\n// Transaction builders (unsigned; caller signs + executes / sponsors)\n// ---------------------------------------------------------------------------\n\n/**\n * Buyer creates AND funds a job in one PTB — `escrow::create` consumes a\n * `Coin<USDC>` sourced from the buyer's coins + address balance.\n */\nexport async function buildCreateJobTx({\n client,\n buyer,\n terms,\n}: {\n client: SuiCoreClient;\n buyer: string;\n terms: JobTerms;\n}): Promise<Transaction> {\n const pf = preflightCreateJob(terms);\n if (!pf.valid) throw new T2000Error(pf.code, pf.error);\n\n const seller = validateAddress(terms.seller);\n if (seller === validateAddress(buyer)) {\n throw new T2000Error('INVALID_ADDRESS', 'Buyer and seller must be different wallets.');\n }\n // Floor, never round up — a rounded-up raw amount can exceed the on-chain\n // balance (financial-amounts discipline).\n const rawAmount = BigInt(Math.floor(terms.amountUsdc * 10 ** USDC_DECIMALS));\n\n const tx = new Transaction();\n const { coin } = await selectAndSplitCoin(tx, client, buyer, USDC_TYPE, rawAmount, {\n allowSwapAll: false,\n });\n tx.moveCall({\n target: `${A2A_ESCROW_PACKAGE_ID}::${MODULE}::create`,\n typeArguments: [USDC_TYPE],\n arguments: [\n tx.pure.address(seller),\n coin,\n tx.pure.vector('u8', hexToBytes(terms.specHash)),\n tx.pure.u64(terms.deliverByMs),\n tx.pure.u64(terms.reviewWindowMs),\n tx.pure.u64(terms.rejectSplitBps),\n tx.object(CLOCK_ID),\n ],\n });\n return tx;\n}\n\nfunction jobCall(jobId: string, fn: 'release' | 'refund' | 'reject'): Transaction {\n const tx = new Transaction();\n tx.moveCall({\n target: `${A2A_ESCROW_PACKAGE_ID}::${MODULE}::${fn}`,\n typeArguments: [USDC_TYPE],\n arguments: [tx.object(jobId), tx.object(CLOCK_ID)],\n });\n return tx;\n}\n\n/** Seller posts the delivery commitment (hex hash) before the deadline. */\nexport function buildDeliverJobTx(jobId: string, deliveryHash: string): Transaction {\n const tx = new Transaction();\n tx.moveCall({\n target: `${A2A_ESCROW_PACKAGE_ID}::${MODULE}::deliver`,\n typeArguments: [USDC_TYPE],\n arguments: [\n tx.object(jobId),\n tx.pure.vector('u8', hexToBytes(deliveryHash)),\n tx.object(CLOCK_ID),\n ],\n });\n return tx;\n}\n\n/** Buyer accepts (or anyone, once the review window lapsed) → funds to seller. */\nexport function buildReleaseJobTx(jobId: string): Transaction {\n return jobCall(jobId, 'release');\n}\n\n/** Buyer rejects within the review window → split per the create terms. */\nexport function buildRejectJobTx(jobId: string): Transaction {\n return jobCall(jobId, 'reject');\n}\n\n/** Anyone, after the deadline with no delivery → funds back to the buyer. */\nexport function buildRefundJobTx(jobId: string): Transaction {\n return jobCall(jobId, 'refund');\n}\n\n// ---------------------------------------------------------------------------\n// Reads\n// ---------------------------------------------------------------------------\n\n/** Fetch + parse a `Job` shared object. Throws `RPC_ERROR` when the id\n * doesn't resolve to an a2a_escrow Job. */\nexport async function getJob(client: SuiCoreClient, jobId: string): Promise<Job> {\n const resp = await client.core\n .getObject({ objectId: jobId, include: { json: true } })\n .catch((e: unknown) => {\n throw new T2000Error(\n 'RPC_ERROR',\n `Job ${jobId} not found: ${e instanceof Error ? e.message : String(e)}`,\n );\n });\n const objType = resp.object?.type ?? '';\n const json = resp.object?.json as Record<string, unknown> | null | undefined;\n if (!json || !objType.includes(`::${MODULE}::Job<`)) {\n throw new T2000Error('RPC_ERROR', `Object ${jobId} is not an a2a_escrow Job.`);\n }\n const stateNum = Number(json.state ?? -1);\n const state = JOB_STATES[stateNum];\n if (!state) {\n throw new T2000Error('RPC_ERROR', `Job ${jobId} has unknown state ${stateNum}.`);\n }\n const deliveredAtMs = Number(json.delivered_at_ms ?? 0);\n const deliveryBytes = (json.delivery_hash ?? []) as number[] | Uint8Array;\n const hasDelivery = deliveredAtMs > 0;\n return {\n id: jobId,\n buyer: String(json.buyer),\n seller: String(json.seller),\n amountUsdc: Number(json.amount) / 10 ** USDC_DECIMALS,\n escrowUsdc: Number(json.escrow) / 10 ** USDC_DECIMALS,\n specHash: bytesToHex((json.spec_hash ?? []) as number[] | Uint8Array),\n deliverByMs: Number(json.deliver_by_ms),\n reviewWindowMs: Number(json.review_window_ms),\n rejectSplitBps: Number(json.reject_split_bps),\n state,\n deliveryHash: hasDelivery ? bytesToHex(deliveryBytes) : null,\n deliveredAtMs: hasDelivery ? deliveredAtMs : null,\n createdAtMs: Number(json.created_at_ms),\n };\n}\n\n/** What `caller` can do to `job` right now — drives `t2 job watch` (the\n * ACP-style \"available action\" readout) and any host UI. */\nexport function jobActionsFor(\n job: Job,\n caller: string,\n nowMs = Date.now(),\n): string[] {\n const me = validateAddress(caller);\n const isBuyer = me === job.buyer;\n const isSeller = me === job.seller;\n const actions: string[] = [];\n if (job.state === 'funded') {\n if (isSeller && nowMs <= job.deliverByMs) actions.push('deliver');\n if (isBuyer) actions.push('release');\n if (nowMs > job.deliverByMs) actions.push('refund');\n } else if (job.state === 'delivered') {\n const windowClosesMs = (job.deliveredAtMs ?? 0) + job.reviewWindowMs;\n if (isBuyer && nowMs <= windowClosesMs) actions.push('release', 'reject');\n if (nowMs > windowClosesMs) actions.push('release');\n }\n return actions;\n}\n\nexport interface JobVerification {\n ok: boolean;\n job: Job;\n /** Human-readable reasons when `ok` is false. */\n problems: string[];\n}\n\n/**\n * Seller-side escrow verification — the x402 `intent: \"escrow\"` credential\n * check. Before starting work on a job id received in an `X-PAYMENT` header,\n * the seller confirms ON-CHAIN (works for every buyer signer, incl. zkLogin):\n * funded, pays ME, covers the price, and leaves enough runway to deliver.\n */\nexport async function verifyJobForSeller({\n client,\n jobId,\n seller,\n minAmountUsdc,\n minRunwayMs = 60_000,\n}: {\n client: SuiCoreClient;\n jobId: string;\n seller: string;\n /** The listing's price for this job class. */\n minAmountUsdc: number;\n /** Minimum time-to-deadline to accept the job (default 60s). */\n minRunwayMs?: number;\n}): Promise<JobVerification> {\n const job = await getJob(client, jobId);\n const problems: string[] = [];\n if (job.state !== 'funded') {\n problems.push(`state is \"${job.state}\", expected \"funded\"`);\n }\n if (job.seller !== validateAddress(seller)) {\n problems.push(`job pays ${job.seller}, not this seller`);\n }\n if (job.escrowUsdc < minAmountUsdc) {\n problems.push(`escrow holds ${job.escrowUsdc} USDC, price is ${minAmountUsdc}`);\n }\n if (job.deliverByMs - Date.now() < minRunwayMs) {\n problems.push('deadline too close to accept');\n }\n return { ok: problems.length === 0, job, problems };\n}\n","/**\n * SPEC 7 v0.4 § Layer 0 — Canonical Write Architecture.\n *\n * `composeTx({ steps })` is the single canonical entry-point for every\n * Audric Enoki-sponsored write. The fragment-appender pattern (Layer 1)\n * is the implementation; this primitive dispatches each step to its\n * registered appender from the typed `WRITE_APPENDER_REGISTRY`.\n *\n * Single-write and multi-write go through the same code path. A 1-step\n * `composeTx([{ toolName: 'send_transfer', input: {...} }])` produces\n * the same shape of result as a 3-step bundle.\n *\n * **Why this exists**\n *\n * Pre-Layer-0, four parallel write stacks lived across the audric host:\n * `transactions/prepare` (fat ~600-line route), `services/prepare`\n * (hand-rolled), `debug-swap` (diagnostic), and PayButton (dapp-kit).\n * Each one re-implemented merge/split/transfer + hand-maintained the\n * `allowedAddresses` array Enoki requires. Two production bugs in the\n * past 60 days came from drift between them — PR-H1 (claim-rewards\n * self-transfer missing from allowedAddresses) and PR-H4 (borrow/\n * withdraw self-transfer same bug).\n *\n * Layer 0 collapses 3 of those stacks into one canonical primitive.\n * PayButton stays out by design (different signer, different trust\n * model — see `audric-canonical-write.mdc` for the rationale and the\n * `// CANONICAL-BYPASS:` escape-hatch contract).\n *\n * **What composeTx owns**\n *\n * - PTB assembly via per-tool wallet-mode appenders (the\n * `WRITE_APPENDER_REGISTRY`).\n * - Pre-built `txKindBytes` (`tx.build({ onlyTransactionKind: true })`)\n * ready for Enoki's `createSponsoredTransaction`.\n * - Auto-derived `derivedAllowedAddresses` from the assembled PTB's\n * top-level `transferObjects` calls — eliminates the PR-H1/H4 bug\n * class permanently. Hand-maintained arrays are now unreachable.\n * - S.38 Pyth flag plumbing — `sponsoredContext: true` automatically\n * applies `skipPythUpdate` (borrow/withdraw) and `skipOracle` (repay)\n * to NAVI appenders so Enoki doesn't reject `tx.gas`-as-argument.\n *\n * **What composeTx does NOT own**\n *\n * - **Fees** — Audric concern, not @t2000/sdk concern (CLAUDE.md\n * rule #9). The SDK is fee-free by design as of @t2000/sdk@1.1.0\n * (B5 v2). Audric host wraps composeTx with fee insertion in P2.2c.\n * - **Sponsorship** — caller's job. composeTx returns `txKindBytes`\n * pre-built for Enoki; the caller calls `createSponsoredTransaction`\n * with their JWT.\n * - **Chain-mode coin handoff between steps** — Layer 2 (engine\n * bundling) ships this. P2.2b is wallet-mode-only: each step fetches\n * coins independently. Layer 2 will extend by introducing\n * `inputCoinFromStep: number` to thread upstream output coins.\n *\n * **Cross-references**\n *\n * - Spec → `spec/SPEC_7_MULTI_WRITE_PTB.md` § \"Layer 0: Canonical\n * Write Architecture\"\n * - Read-side companion → `t2000/.cursor/rules/single-source-of-truth.mdc`\n * + `audric/.cursor/rules/audric-canonical-portfolio.mdc`\n * - Write-side rule → `audric/.cursor/rules/audric-canonical-write.mdc`\n */\n\nimport type { SuiCoreClient } from './utils/sui.js';\nimport {\n Transaction,\n type TransactionObjectArgument,\n} from '@mysten/sui/transactions';\nimport type { OverlayFeeConfig } from './protocols/cetus-swap.js';\nimport { addSwapToTx, type SwapRouteResult } from './protocols/cetus-swap.js';\nimport { addSendToTx } from './wallet/send.js';\nimport {\n selectSuiCoin,\n type SponsoredCoinMergeCache,\n} from './wallet/coinSelection.js';\nimport { resolveTokenType, getDecimalsForCoinType, SUI_TYPE } from './token-registry.js';\nimport {\n GASLESS_MIN_STABLE_AMOUNT,\n GASLESS_STABLE_TYPES,\n SUPPORTED_ASSETS,\n assertAllowedAsset,\n type SendableAsset,\n type SupportedAsset,\n} from './constants.js';\nimport { T2000Error } from './errors.js';\nimport { validateAddress } from './utils/sui.js';\n\n/**\n * Canonical write tools. The 8 tools that can be composed into a PTB.\n *\n * History:\n * - 2026-05-08 (Track B): added `harvest_rewards` (compound macro).\n * - 2026-05-25 (S.323): removed `volo_stake` / `volo_unstake` — full Volo\n * cut across SDK/CLI/MCP after the engine cut Volo in S.277. vSUI\n * remains as a passive token (NAVI reward, Cetus swap target).\n *\n * Excluded by design:\n * - `save_contact` — no on-chain leg (Prisma-only).\n */\n// [S.444 — NAVI/DeFi removed] Canonical write tools narrowed to the two\n// surviving on-chain verbs: gasless send + Cetus swap. save/withdraw/borrow/\n// repay/claim/harvest were deleted with NAVI (v2 keeps them on @t2000/sdk@4.x).\nexport type WriteToolName =\n | 'send_transfer'\n | 'swap_execute';\n\n// Per-tool input contracts. Match the engine tool input schemas, not the\n// audric host's loosely-typed `params` blob — the registry is the typed\n// surface that lets the host shed the `any`-typed switch statement.\n\n/**\n * [v4.0 Phase A Day 2 — SPEC_AGENT_WALLET_GREENFIELD §A]\n * `asset` is now REQUIRED (no more silent USDC default). The parameter\n * type is the wider `SupportedAsset` rather than the narrower\n * `SendableAsset` so callers that thread a wide-typed asset through\n * (primarily the engine LLM tool surface) compile without modification.\n * Runtime narrowing happens via `assertAllowedAsset('send', asset)`,\n * which throws `INVALID_ASSET` for anything outside the\n * `['USDC', 'USDsui', 'SUI']` whitelist. USDC + USDsui route through\n * the gasless `0x2::balance::send_funds` Move call; SUI uses the\n * standard `transferObjects` path.\n *\n * Audric hosts: the audric chat client (`audric-chat-client.tsx`)\n * already defaults asset to `'USDC'` at the marker layer before\n * calling `sponsoredTx({ type: 'send' })`, so this signature change\n * doesn't break the LLM flow. LLM intents like \"send 5 WAL\" now\n * surface a clear error instead of silently building a non-gasless\n * tx.\n */\nexport interface SendTransferInput {\n to: string;\n amount: number;\n asset: SupportedAsset;\n}\n\nexport interface SwapExecuteInput {\n from: string;\n to: string;\n amount: number;\n slippage?: number;\n byAmountIn?: boolean;\n /** Cetus provider allow-list. Sponsored callers MUST pass an exclusion list\n * to remove Pyth-dependent providers — see addSwapToTx JSDoc. composeTx\n * derives this automatically from `sponsoredContext` if omitted. */\n providers?: string[];\n /**\n * [SPEC 20.2 / D-1 (a)] Optional precomputed Cetus route discovered at\n * `swap_quote` time. Bypasses `findSwapRoute()` (-400-500ms) inside\n * `addSwapToTx`. Caller (audric prepare-route) is responsible for\n * coin-type verification (D-2) + freshness check (D-3) before passing.\n * `addSwapToTx` performs an additional sanity check on `amountIn` +\n * `byAmountIn` and falls back to fresh discovery on mismatch.\n */\n precomputedRoute?: SwapRouteResult;\n}\n\n/**\n * Discriminated union mapping `toolName` → `input`. Used to type\n * `WriteStep` so consumers get autocomplete + compile-time validation\n * that the input matches the tool.\n *\n * **[SPEC 13 Phase 1] `inputCoinFromStep`** — consumer steps may\n * reference an earlier step's output coin handle by index. When set,\n * `composeTx`'s orchestration loop threads the producer's\n * `outputCoin` into this step's appender as the `inputCoin` arg,\n * bypassing the wallet pre-fetch path. The producer's terminal\n * `tx.transferObjects([coin], sender)` is suppressed automatically so\n * the same handle isn't double-consumed.\n */\nexport type WriteStep =\n | { toolName: 'send_transfer'; input: SendTransferInput; inputCoinFromStep?: number }\n | { toolName: 'swap_execute'; input: SwapExecuteInput; inputCoinFromStep?: number };\n\nexport interface ComposeTxOptions {\n sender: string;\n steps: WriteStep[];\n client: SuiCoreClient;\n /**\n * S.38 Pyth flag (sponsorship-critical). When true:\n * - NAVI borrow/withdraw appenders apply `skipPythUpdate: true`\n * (preserves on-chain price-feed updates, skips the tx.gas-using\n * Pyth fee payment that Enoki rejects).\n * - NAVI repay appender applies `skipOracle: true` (debt reduction\n * has no health-factor risk, full oracle bypass is safe).\n * - Cetus swap appender applies `getProvidersExcluding([HAEDALPMM,\n * METASTABLE, OBRIC, STEAMM_OMM, STEAMM_OMM_V2, SEVENK,\n * HAEDALHMMV2])` — Pyth-dependent providers reference `tx.gas` for\n * oracle fees, also rejected by Enoki.\n * - SUI sends fetch coins via `getCoins` (tx.gas belongs to sponsor,\n * not user) instead of splitting from `tx.gas`.\n *\n * Self-funded callers (CLI, MCP, server tasks) leave this `false` /\n * omit — they pay all oracle/Pyth fees from their own SUI gas.\n */\n sponsoredContext?: boolean;\n /**\n * Per-call overlay fee config for Cetus swaps. Audric host passes\n * `{ rate: 0.001, receiver: T2000_OVERLAY_FEE_WALLET }` to charge the\n * 0.1% swap overlay. CLI / direct SDK callers omit. Forwarded to\n * `addSwapToTx`'s `input.overlayFee`.\n */\n overlayFee?: OverlayFeeConfig;\n}\n\n/** Per-step preview returned by each registry appender. Tool-specific shape. */\nexport type StepPreview =\n | { toolName: 'send_transfer'; effectiveAmount: number; recipient: string; asset: SendableAsset }\n | { toolName: 'swap_execute'; effectiveAmountIn: number; expectedAmountOut: number; route: SwapRouteResult };\n\nexport interface ComposeTxResult {\n tx: Transaction;\n /**\n * Pre-built bytes for Enoki's `createSponsoredTransaction`. Built\n * with `onlyTransactionKind: true` so the gas coin can be supplied\n * by the sponsor.\n */\n txKindBytes: Uint8Array;\n /**\n * Auto-derived from the assembled PTB's top-level `transferObjects`\n * commands. Replaces hand-maintained `allowedAddresses` arrays in\n * audric host's `transactions/prepare` + `services/prepare` —\n * eliminates the PR-H1/H4 bug class permanently.\n */\n derivedAllowedAddresses: string[];\n perStepPreviews: StepPreview[];\n}\n\n/**\n * Per-appender context passed into every registry entry. Carries the\n * RPC client, sender, sponsorship flag, optional per-call overlay\n * fee config (Cetus swaps), and SPEC 13 Phase 1 chain-mode fields.\n */\nexport interface AppenderContext {\n client: SuiCoreClient;\n sender: string;\n sponsoredContext: boolean;\n overlayFee?: OverlayFeeConfig;\n /**\n * [SPEC 13 Phase 1] When set, the consumer appender consumes this\n * coin handle directly instead of pre-fetching from the wallet via\n * `selectAndSplitCoin` / `selectSuiCoin`. Provided by the\n * orchestration loop when the step has `inputCoinFromStep` set; the\n * loop looks up `priorOutputs[step.inputCoinFromStep]` and threads\n * it through here.\n *\n * In chain mode, the consumer consumes the handle IN FULL — the\n * `input.amount` field is treated as informational (used for preview\n * math). This matches Cetus's `routerSwap`, NAVI's `deposit`/`repay`,\n * and the Sui `transferObjects` semantics: each takes a coin object\n * and consumes its entire balance.\n */\n chainedCoin?: TransactionObjectArgument;\n /**\n * [SPEC 13 Phase 1] True when this step's output coin will be\n * consumed by a downstream step (some later step has\n * `inputCoinFromStep === currentStepIndex`). Producer appenders MUST\n * skip their terminal `tx.transferObjects([coin], ctx.sender)` call\n * when this is true — otherwise the same `TransactionObjectArgument`\n * gets used twice (once by the consumer, once by the transfer) and\n * the PTB build fails or the on-chain leg reverts.\n */\n isOutputConsumed?: boolean;\n /**\n * Per-PTB merge cache for sponsored coin-object sourcing, shared across\n * every appender in a single `composeTx` run. Lets multiple legs that\n * source the same coin type (two SUI swaps, swap USDC + save USDC, etc.)\n * reuse a single merged primary coin instead of each re-fetching +\n * re-merging the same coin objects (the second merge of which references\n * already-consumed coins → Enoki dry-run `ArgumentWithoutValue`). Applies\n * to ALL coin types, not just SUI. See `SponsoredCoinMergeCache` JSDoc.\n */\n coinMergeCache?: SponsoredCoinMergeCache;\n}\n\n/**\n * [SPEC 13 Phase 1] Appender return shape. Producers populate\n * `outputCoin` so the orchestration loop can thread it into a\n * downstream consumer's `chainedCoin`. The terminal consumer\n * (`send_transfer`) omits it.\n *\n * `swap_execute` is the only dual-mode tool — it accepts `chainedCoin`\n * AND populates `outputCoin`. (Pre-S.444 the DeFi tools\n * save/withdraw/borrow/repay were also producers/consumers; removed with NAVI.)\n */\nexport interface AppenderResult<TPreview extends StepPreview> {\n preview: TPreview;\n outputCoin?: TransactionObjectArgument;\n}\n\ntype AppenderFn<TInput, TPreview extends StepPreview> = (\n tx: Transaction,\n input: TInput,\n ctx: AppenderContext,\n) => Promise<AppenderResult<TPreview>>;\n\n/**\n * Cetus provider exclusion list for sponsored flows. Mirrors the\n * audric host's `SPONSORED_TX_PROVIDERS` constant — these 7 providers\n * reference `tx.gas` for Pyth oracle fee payments, which Enoki rejects.\n *\n * NOTE: keeping this hardcoded means `findSwapRoute` doesn't need a\n * dependency on `@cetusprotocol/aggregator-sdk`'s `getProvidersExcluding`\n * helper — composeTx forwards the literal list to Cetus, Cetus does the\n * inverse lookup. Result is identical.\n */\nexport const SPONSORED_PYTH_DEPENDENT_PROVIDERS = [\n 'HAEDALPMM',\n 'METASTABLE',\n 'OBRIC',\n 'STEAMM_OMM',\n 'STEAMM_OMM_V2',\n 'SEVENK',\n 'HAEDALHMMV2',\n] as const;\n\n/**\n * Get all eligible Cetus provider names except the Pyth-dependent ones,\n * for sponsored swap context. Computed from the Cetus SDK's\n * `getAllProviders()` minus the exclusion list.\n *\n * [Bug A fix / 2026-05-10] Exported so the engine's `swap_quote` tool can\n * call this when discovering routes for sponsored hosts. Previously the\n * engine only exclude these providers at COMPOSE time; now it excludes\n * at QUOTE time too, so the precomputed route stashed on\n * `pending_action.cetusRoute` is always sponsor-safe.\n */\nexport async function getSponsoredSwapProviders(): Promise<string[]> {\n const { getProvidersExcluding } = await import('@cetusprotocol/aggregator-sdk');\n return getProvidersExcluding([...SPONSORED_PYTH_DEPENDENT_PROVIDERS]);\n}\n\n/**\n * The typed registry. Each entry is a wallet-mode dispatcher that takes\n * (tx, input, ctx) and returns a per-step preview. Compile-time check\n * that all `WriteToolName` values have an entry — TypeScript will\n * fail the build if a tool is missing.\n *\n * [S.444] Narrowed to send_transfer + swap_execute after the NAVI/DeFi cut.\n */\nexport const WRITE_APPENDER_REGISTRY: {\n send_transfer: AppenderFn<SendTransferInput, Extract<StepPreview, { toolName: 'send_transfer' }>>;\n swap_execute: AppenderFn<SwapExecuteInput, Extract<StepPreview, { toolName: 'swap_execute' }>>;\n} = {\n send_transfer: async (tx, input, ctx) => {\n const recipient = validateAddress(input.to);\n // [v4.0 Phase A Day 2] Asset is required (no `?? 'USDC'` default).\n // assertAllowedAsset narrows the runtime value to\n // `'USDC' | 'USDsui' | 'SUI'` and throws INVALID_ASSET otherwise.\n // The TypeScript shape is `SupportedAsset` (wider, accommodates\n // engine LLM tool callers that pass wide-typed assets through);\n // the runtime assertion is the canonical gate.\n if (!input.asset) {\n throw new T2000Error(\n 'INVALID_ASSET',\n \"send_transfer requires an explicit asset. Use one of: USDC, USDsui, SUI.\",\n );\n }\n assertAllowedAsset('send', input.asset);\n const asset: SendableAsset = input.asset as SendableAsset;\n const assetInfo = SUPPORTED_ASSETS[asset];\n if (input.amount <= 0) {\n throw new T2000Error('INVALID_AMOUNT', 'Send amount must be greater than zero');\n }\n\n const rawAmount = BigInt(Math.floor(input.amount * 10 ** assetInfo.decimals));\n\n // [v4.0 Phase A Day 2] Chain-mode (`chainedCoin` from a previous\n // appender) ALWAYS uses the legacy `transferObjects` path —\n // bundles never qualify for gasless because the protocol allowlist\n // only accepts PTBs whose ops are `balance::send_funds` /\n // `balance::redeem_funds` / `coin::send_funds` etc. A withdraw →\n // send bundle has the withdraw Move call, so the whole tx pays gas.\n if (ctx.chainedCoin) {\n addSendToTx(tx, ctx.chainedCoin, recipient);\n return {\n preview: {\n toolName: 'send_transfer',\n effectiveAmount: Number(rawAmount) / 10 ** assetInfo.decimals,\n recipient,\n asset,\n },\n };\n }\n\n if (asset === 'SUI') {\n // Standard gas-native SUI transfer — NOT gasless (SUI is not on\n // the protocol `balance::send_funds` allowlist).\n const result = await selectSuiCoin(\n tx,\n ctx.client,\n ctx.sender,\n rawAmount,\n ctx.sponsoredContext,\n ctx.coinMergeCache,\n );\n addSendToTx(tx, result.coin, recipient);\n return {\n preview: {\n toolName: 'send_transfer',\n effectiveAmount: Number(result.effectiveAmount) / 10 ** assetInfo.decimals,\n recipient,\n asset,\n },\n };\n }\n\n // USDC / USDsui — gasless single-step send via `0x2::balance::send_funds`.\n // Surfaces the protocol's 0.01 minimum BEFORE building so we don't\n // burn a sponsorship slot on a tx that will revert on-chain.\n if (input.amount < GASLESS_MIN_STABLE_AMOUNT) {\n throw new T2000Error(\n 'INVALID_AMOUNT',\n `Minimum gasless transfer is ${GASLESS_MIN_STABLE_AMOUNT} ${asset}. Got ${input.amount}.`,\n );\n }\n // Pre-flight balance check (composeTx's selectAndSplitCoin used to\n // do this; we lose the coin-selection but keep the balance gate so\n // build-time errors stay actionable for audric's prepare route).\n const balanceResp = await ctx.client.core.getBalance({ owner: ctx.sender, coinType: assetInfo.type });\n if (BigInt(balanceResp.balance.balance) < rawAmount) {\n throw new T2000Error('INSUFFICIENT_BALANCE', `Insufficient ${asset} balance`, {\n available: Number(balanceResp.balance.balance) / 10 ** assetInfo.decimals,\n required: input.amount,\n });\n }\n const coinType = GASLESS_STABLE_TYPES[asset];\n tx.moveCall({\n target: '0x2::balance::send_funds',\n typeArguments: [coinType],\n arguments: [\n tx.balance({ type: coinType, balance: rawAmount }),\n tx.pure.address(recipient),\n ],\n });\n return {\n preview: {\n toolName: 'send_transfer',\n effectiveAmount: Number(rawAmount) / 10 ** assetInfo.decimals,\n recipient,\n asset,\n },\n };\n },\n\n swap_execute: async (tx, input, ctx) => {\n const fromType = resolveTokenType(input.from);\n const toType = resolveTokenType(input.to);\n if (!fromType || !toType) {\n throw new T2000Error(\n 'ASSET_NOT_SUPPORTED',\n `Unknown token in swap: from=${input.from}, to=${input.to}`,\n );\n }\n\n const providers = input.providers\n ?? (ctx.sponsoredContext ? await getSponsoredSwapProviders() : undefined);\n\n const result = await addSwapToTx(tx, ctx.client, ctx.sender, {\n from: input.from,\n to: input.to,\n amount: input.amount,\n slippage: input.slippage,\n byAmountIn: input.byAmountIn,\n overlayFee: ctx.overlayFee,\n providers,\n inputCoin: ctx.chainedCoin,\n precomputedRoute: input.precomputedRoute,\n sponsoredContext: ctx.sponsoredContext,\n coinMergeCache: ctx.coinMergeCache,\n });\n if (!ctx.isOutputConsumed) {\n tx.transferObjects([result.coin], ctx.sender);\n }\n return {\n preview: {\n toolName: 'swap_execute',\n effectiveAmountIn: result.effectiveAmountIn,\n expectedAmountOut: result.expectedAmountOut,\n route: result.route,\n },\n outputCoin: result.coin,\n };\n },\n\n // [S.444] claim_rewards / harvest_rewards appenders removed with NAVI.\n // [S.323] volo_stake / volo_unstake appenders removed earlier.\n};\n\n// Reference unused import to suppress noUnusedLocals; SUI_TYPE is used\n// by selectSuiCoin internally and re-export from index.ts.\nvoid SUI_TYPE;\nvoid getDecimalsForCoinType;\n\n/**\n * Walks the assembled PTB's command list and extracts every recipient\n * address from top-level `TransferObjects` commands. Top-level only —\n * recipients inside nested Move calls are NOT inspected (Enoki only\n * cross-checks top-level commands).\n *\n * Replaces hand-maintained `allowedAddresses` arrays. Two production\n * bugs in 60 days came from drift between the array and the actual\n * PTB recipients (PR-H1 + PR-H4). Computing this from the PTB makes\n * drift impossible by construction.\n */\nexport function deriveAllowedAddressesFromPtb(tx: Transaction): string[] {\n const addresses = new Set<string>();\n const data = tx.getData();\n\n const addAddressFromInput = (inputIndex: number | undefined): void => {\n if (inputIndex === undefined) return;\n const input = data.inputs[inputIndex];\n if (!input) return;\n const pureBytes = (input as { Pure?: { bytes?: string } }).Pure?.bytes;\n if (!pureBytes) return;\n // Pure bytes are base64-encoded BCS for Sui addresses (32 bytes →\n // 44-char base64). Decode + format as 0x-prefixed hex.\n try {\n const bytes = base64ToBytes(pureBytes);\n if (bytes.length !== 32) return; // not an address\n const hex = '0x' + Array.from(bytes).map((b) => b.toString(16).padStart(2, '0')).join('');\n addresses.add(hex);\n } catch {\n // not a parseable address — skip\n }\n };\n\n for (const cmd of data.commands) {\n // Path 1 — `TransferObjects.address` (the legacy send/withdraw/\n // claim/fee-transfer recipient surface). The Sui transaction-builder\n // stores each top-level command as a tagged object:\n // { TransferObjects: { objects, address: { Input: <index> } } }.\n const transferCmd = (cmd as { TransferObjects?: unknown }).TransferObjects;\n if (transferCmd) {\n const addressArg = (transferCmd as { address?: unknown }).address;\n const addressInputIndex = (addressArg as { Input?: number } | undefined)?.Input;\n addAddressFromInput(addressInputIndex);\n continue;\n }\n\n // Path 2 — `0x2::balance::send_funds(balance, recipient)` (gasless\n // stablecoin transfer, v4.0 Phase A Day 2). Recipient is arg[1],\n // not a TransferObjects.address. The Move call shape:\n // { MoveCall: { package, module, function, arguments: [...] } }\n // target = `0x2::balance::send_funds`, arguments[1] = recipient.\n const moveCall = (cmd as { MoveCall?: unknown }).MoveCall;\n if (moveCall) {\n const mc = moveCall as {\n package?: string;\n module?: string;\n function?: string;\n arguments?: Array<{ Input?: number } | unknown>;\n };\n // The `package` field is the normalized framework address. For\n // `0x2::balance::send_funds` it's `0x0000…0002` (`SUI_FRAMEWORK_ADDRESS`).\n // Match on module + function defensively; the recipient extraction\n // only fires when the signature matches.\n const isBalanceSendFunds =\n mc.module === 'balance' && mc.function === 'send_funds';\n const isCoinSendFunds =\n mc.module === 'coin' && mc.function === 'send_funds';\n if (isBalanceSendFunds || isCoinSendFunds) {\n const args = mc.arguments ?? [];\n const recipientArg = args[1] as { Input?: number } | undefined;\n addAddressFromInput(recipientArg?.Input);\n }\n continue;\n }\n }\n\n return Array.from(addresses);\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n if (typeof Buffer !== 'undefined') {\n return Uint8Array.from(Buffer.from(b64, 'base64'));\n }\n // Browser fallback (in case this ever runs in a worker)\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\n/**\n * Compose a PTB from a list of canonical write steps. Each step\n * dispatches to its registered fragment-appender; the assembled PTB is\n * returned alongside pre-built `txKindBytes` ready for Enoki sponsorship\n * + auto-derived `derivedAllowedAddresses`.\n *\n * Single-step: `composeTx({ steps: [{ toolName: 'send_transfer', input: {...} }], ... })`\n * Multi-step (Layer 2): `composeTx({ steps: [{...}, {...}, {...}], ... })`\n *\n * Throws:\n * - `T2000Error('NO_APPENDER')` — unknown `toolName`\n * - Any error thrown by the per-step appender (insufficient balance,\n * asset not supported, route not found, etc.) — propagates as-is.\n */\nexport async function composeTx(opts: ComposeTxOptions): Promise<ComposeTxResult> {\n const tx = new Transaction();\n tx.setSender(opts.sender);\n\n const baseCtx = {\n client: opts.client,\n sender: opts.sender,\n sponsoredContext: opts.sponsoredContext ?? false,\n overlayFee: opts.overlayFee,\n // One cache per compose run — shared across all legs (any coin type)\n // so multi-leg sponsored bundles that source the same coin (two SUI\n // swaps, swap USDC + save USDC, ...) merge that coin's objects once.\n coinMergeCache: new Map() as SponsoredCoinMergeCache,\n };\n\n // [SPEC 13 Phase 1] First pass: validate every `inputCoinFromStep`\n // reference and build the `consumedSteps` set. Forward-only\n // references; producer-only tools can't be consumers.\n const consumedSteps = new Set<number>();\n for (let i = 0; i < opts.steps.length; i++) {\n const step = opts.steps[i];\n const stepWithChain = step as { inputCoinFromStep?: number };\n const idx = stepWithChain.inputCoinFromStep;\n if (idx === undefined) continue;\n\n if (!Number.isInteger(idx) || idx < 0 || idx >= i) {\n throw new T2000Error(\n 'CHAIN_MODE_INVALID',\n `Step ${i} (${step.toolName}) has inputCoinFromStep=${idx}, ` +\n `which must be a non-negative integer < ${i} (forward-only references).`,\n );\n }\n\n const producer = opts.steps[idx];\n if (producer.toolName === 'send_transfer') {\n throw new T2000Error(\n 'CHAIN_MODE_INVALID',\n `Step ${i} (${step.toolName}) references step ${idx} (${producer.toolName}) as ` +\n `producer, but 'send_transfer' is a terminal consumer that does not ` +\n `produce a chainable coin handle. Allowed producers: swap_execute.`,\n );\n }\n\n consumedSteps.add(idx);\n }\n\n // [SPEC 13 Phase 1] Second pass: dispatch each step in order,\n // capturing producers' output handles in `priorOutputs` and threading\n // them into consumers' `chainedCoin`.\n const priorOutputs: (TransactionObjectArgument | null)[] = [];\n const previews: StepPreview[] = [];\n for (let i = 0; i < opts.steps.length; i++) {\n const step = opts.steps[i];\n const appender = (WRITE_APPENDER_REGISTRY as Record<string, AppenderFn<unknown, StepPreview>>)[step.toolName];\n if (!appender) {\n throw new T2000Error(\n 'UNKNOWN',\n `No fragment appender registered for tool '${step.toolName}'. ` +\n `Allowed: ${(Object.keys(WRITE_APPENDER_REGISTRY) as WriteToolName[]).join(', ')}`,\n );\n }\n\n const stepWithChain = step as { inputCoinFromStep?: number };\n let chainedCoin: TransactionObjectArgument | undefined;\n if (stepWithChain.inputCoinFromStep !== undefined) {\n const upstream = priorOutputs[stepWithChain.inputCoinFromStep];\n if (!upstream) {\n // Producer didn't return an outputCoin (shouldn't happen given the\n // first-pass guard, but defends against future appender bugs).\n throw new T2000Error(\n 'CHAIN_MODE_INVALID',\n `Step ${i} (${step.toolName}) expected a coin handle from step ` +\n `${stepWithChain.inputCoinFromStep}, but the producer did not return one.`,\n );\n }\n chainedCoin = upstream;\n }\n\n const stepCtx: AppenderContext = {\n ...baseCtx,\n chainedCoin,\n isOutputConsumed: consumedSteps.has(i),\n };\n\n const result = await appender(tx, step.input, stepCtx);\n priorOutputs.push(result.outputCoin ?? null);\n previews.push(result.preview);\n }\n\n const txKindBytes = await tx.build({ client: opts.client, onlyTransactionKind: true });\n const derivedAllowedAddresses = deriveAllowedAddressesFromPtb(tx);\n\n return {\n tx,\n txKindBytes,\n derivedAllowedAddresses,\n perStepPreviews: previews,\n };\n}\n","import { Transaction } from '@mysten/sui/transactions';\nimport { T2000Error } from '../errors.js';\nimport { mapMoveAbortCode } from '../errors.js';\nimport type { SuiCoreClient } from './sui.js';\n\nexport interface SimulationResult {\n success: boolean;\n gasEstimateSui: number;\n error?: {\n moveAbortCode?: number;\n moveModule?: string;\n reason: string;\n rawError: string;\n };\n}\n\nexport async function simulateTransaction(\n client: SuiCoreClient,\n tx: Transaction,\n sender: string,\n): Promise<SimulationResult> {\n tx.setSender(sender);\n\n try {\n // [gRPC migration] `core.simulateTransaction` replaces `dryRunTransactionBlock`.\n // It returns a discriminated union; effects.status is `{ success, error }`\n // where `error` is a structured `ExecutionError` (not the legacy raw string).\n const txBytes = await tx.build({ client });\n const sim = await client.core.simulateTransaction({\n transaction: txBytes,\n include: { effects: true },\n });\n const txn = sim.$kind === 'Transaction' ? sim.Transaction : sim.FailedTransaction;\n const effects = txn.effects;\n const gasUsed = effects?.gasUsed;\n\n const gasEstimateSui = gasUsed\n ? (Number(gasUsed.computationCost) +\n Number(gasUsed.storageCost) -\n Number(gasUsed.storageRebate)) / 1e9\n : 0;\n\n const errObj = effects && !effects.status.success ? effects.status.error : undefined;\n if (sim.$kind === 'FailedTransaction' || errObj) {\n const rawError = errObj?.message ?? 'Unknown simulation error';\n // Prefer the structured MoveAbort code; fall back to regex-parsing the\n // message for non-abort errors / pre-structured formats.\n const structuredAbort =\n errObj?.$kind === 'MoveAbort' ? Number(errObj.MoveAbort.abortCode) : undefined;\n const parsed = parseMoveAbort(rawError);\n const abortCode = structuredAbort ?? parsed.abortCode;\n\n return {\n success: false,\n gasEstimateSui,\n error: {\n moveAbortCode: abortCode,\n moveModule: parsed.module,\n reason: abortCode != null ? mapMoveAbortCode(abortCode) : parsed.reason,\n rawError,\n },\n };\n }\n\n return { success: true, gasEstimateSui };\n } catch (err) {\n const rawError = err instanceof Error ? err.message : String(err);\n return {\n success: false,\n gasEstimateSui: 0,\n error: {\n reason: 'Simulation failed: ' + rawError,\n rawError,\n },\n };\n }\n}\n\nexport function throwIfSimulationFailed(sim: SimulationResult): void {\n if (sim.success) return;\n\n throw new T2000Error(\n 'SIMULATION_FAILED',\n sim.error?.reason ?? 'Transaction simulation failed',\n {\n moveAbortCode: sim.error?.moveAbortCode,\n moveModule: sim.error?.moveModule,\n reason: sim.error?.reason,\n rawError: sim.error?.rawError,\n },\n );\n}\n\nfunction parseMoveAbort(errorStr: string): {\n abortCode?: number;\n module?: string;\n reason: string;\n} {\n // Pattern: MoveAbort(MoveLocation { module: ModuleId { ... name: \"module\" }, ... }, code)\n const abortMatch = errorStr.match(/MoveAbort\\([^,]*,\\s*(\\d+)\\)/);\n const moduleMatch = errorStr.match(/name:\\s*Identifier\\(\"([^\"]+)\"\\)/);\n\n if (abortMatch) {\n const code = parseInt(abortMatch[1], 10);\n const module = moduleMatch?.[1];\n const reason = mapMoveAbortCode(code);\n return { abortCode: code, module, reason };\n }\n\n // Pattern: MovePrimitiveRuntimeError\n if (errorStr.includes('MovePrimitiveRuntimeError')) {\n const module = moduleMatch?.[1];\n return {\n module,\n reason: `Move runtime error in ${module ?? 'unknown'} module`,\n };\n }\n\n return { reason: errorStr };\n}\n","/**\n * SuiNS leaf-subname builders for the `audric.sui` parent NFT.\n *\n * Used by SPEC 10 v0.2.1 Phase A.1 — Audric Passport Identity. Lets the audric host\n * mint and revoke `username.audric.sui` leaves under the parent NFT held by the\n * dedicated custody address (`0xaca29165…23d11`).\n *\n * **Why a dedicated SDK module (not inline in the audric route):**\n * - Consumers (audric/web's `/api/identity/{reserve,change,release}` routes) can import\n * the canonical builder shape without re-discovering the `SuinsTransaction` API.\n * - Single source of truth for the parent NFT ID + parent name.\n * - Single source of truth for label validation (length / charset / hyphen rules).\n *\n * **Signer model — read this before wiring into a route:**\n * These builders are signed by the **service account** (the parent NFT custody address),\n * NOT by the user's zkLogin key. Per `audric/.cursor/rules/audric-canonical-write.mdc`,\n * the SPEC 10 leaf-mint API routes are explicitly documented as a CANONICAL-BYPASS of\n * the `composeTx` write contract — they are server-to-server, the user's key is never\n * in the loop, and Enoki sponsors the gas. PTB atomicity requires single-signer, so\n * leaf mints cannot be bundled with chat-agent writes via composeTx.\n *\n * **Reference:** `spec/runbooks/RUNBOOK_audric_sui_parent.md` §1 (parent NFT ID) +\n * §3 (validated SDK reference shape) + §4 (mainnet smoke test 2026-05-01).\n */\n\nimport { Transaction } from '@mysten/sui/transactions';\nimport { isValidSuiAddress, normalizeSuiAddress } from '@mysten/sui/utils';\nimport { SuinsTransaction, type SuinsClient } from '@mysten/suins';\n\n/**\n * Parent name registered on SuiNS mainnet. Audric's identity namespace anchor.\n *\n * Every leaf created via `buildAddLeafTx` becomes `<label>.audric.sui` and resolves\n * via the standard SuiNS resolver (`suix_resolveNameServiceAddress`).\n */\nexport const AUDRIC_PARENT_NAME = 'audric.sui';\n\n/**\n * On-chain object ID of the `audric.sui` parent NFT (a `SuinsRegistration`).\n *\n * Owned by the dedicated custody address `0xaca29165188f10136073788f648e1186dd25100100146186ebecedaf94b23d11`\n * (per `RUNBOOK_audric_sui_parent.md` §1). Every leaf mint / revoke MUST be signed\n * by the address that owns this NFT. Mainnet only.\n */\nexport const AUDRIC_PARENT_NFT_ID =\n '0x070456e283ec988b6302bdd6cc5172bbdcb709998cf116586fb98d19b0870198';\n\n/**\n * A SuiNS parent under which leaf subnames are minted: the registered SLD name\n * + the on-chain `SuinsRegistration` NFT id the minting service must own/sign.\n *\n * Added 2026-06-29 (Agent ID Phase B, gate 2) to let the same leaf machinery\n * serve a SECOND namespace — `agent-id.sui` for Agent ID handles — without\n * forking it. Audric stays the default so every existing caller is unchanged.\n */\nexport interface SuinsParent {\n name: string;\n nftId: string;\n}\n\n/** The Audric consumer-handle parent (`<label>.audric.sui` → `@audric`). */\nexport const AUDRIC_PARENT: SuinsParent = {\n name: AUDRIC_PARENT_NAME,\n nftId: AUDRIC_PARENT_NFT_ID,\n};\n\n/** The Agent ID parent (`<label>.agent-id.sui` → `@agent-id`). Distinct from\n * audric.sui on purpose (infra/agent registry vs consumer brand).\n *\n * Registered on SuiNS mainnet 2026-06-29; the `SuinsRegistration` NFT\n * (`0xc8c1…d5d1f`) is held by the custody address\n * `0x6988a92d…30e4532`, which signs leaf mints + pays their gas. Override via\n * `AGENT_ID_PARENT_NFT_ID` for testnet/dev. */\nexport const AGENT_ID_PARENT_NAME = 'agent-id.sui';\nexport const AGENT_ID_PARENT_NFT_ID =\n process.env.AGENT_ID_PARENT_NFT_ID ??\n '0xc8c13f5b5a6d4c47c04877014794f65e67e2745d3bfa089b736eb54b0ebd5d1f';\nexport const AGENT_ID_PARENT: SuinsParent = {\n name: AGENT_ID_PARENT_NAME,\n nftId: AGENT_ID_PARENT_NFT_ID,\n};\n\nexport interface BuildAddLeafParams {\n /** Bare label, e.g. `'alice'` — NOT the full `'alice.audric.sui'` path. */\n label: string;\n /** Sui address the leaf will resolve to (typically the user's zkLogin wallet). */\n targetAddress: string;\n /** Parent to mint under. Defaults to Audric (back-compat). */\n parent?: SuinsParent;\n}\n\nexport interface BuildRevokeLeafParams {\n /** Bare label of the leaf to revoke. */\n label: string;\n /** Parent the leaf lives under. Defaults to Audric (back-compat). */\n parent?: SuinsParent;\n}\n\nexport type LabelValidationResult = { valid: true } | { valid: false; reason: string };\n\n/**\n * SuiNS labels accept lowercase ASCII letters, digits, and hyphens. Hyphens cannot\n * lead or trail. The 3–63 char window matches SuiNS protocol rules and the SuiNS\n * dashboard's own `Register` form.\n *\n * The regex permits a single character only when it is alphanumeric (rejected by\n * the length check below for being < 3, but the pattern itself stays internally\n * consistent with DNS conventions).\n *\n * SUINS-LABEL-RULE — paired with `audric/apps/web/lib/identity/validate-label.ts`.\n * The audric host duplicates these rules inline to avoid pulling the full SDK\n * (and its server-side transitive deps) into the client bundle. If SuiNS ever\n * label rules, BOTH this file and the audric copy need updating.\n */\nconst LABEL_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;\n\n/**\n * Validate a leaf label against SuiNS protocol rules. Pure function; no I/O.\n *\n * Pre-call this before `buildAddLeafTx` / `buildRevokeLeafTx` if you want a\n * structured error (the builder functions throw on invalid labels). The audric\n * `/api/identity/check` endpoint uses this to drive the picker's real-time\n * availability indicator.\n *\n * Reserved-name policy (specific Audric handles like `support`, `admin`,\n * `official`) is NOT enforced here — that's a UI / route-level concern owned\n * by the audric host, not a protocol-level rule. See SPEC 10 D3.\n */\nexport function validateLabel(label: unknown): LabelValidationResult {\n if (typeof label !== 'string') {\n return { valid: false, reason: 'label must be a string' };\n }\n if (label.length < 3) {\n return { valid: false, reason: 'label must be at least 3 characters' };\n }\n if (label.length > 63) {\n return { valid: false, reason: 'label must be at most 63 characters' };\n }\n if (!LABEL_PATTERN.test(label)) {\n return {\n valid: false,\n reason:\n 'label may only contain lowercase letters, digits, and hyphens, and may not start or end with a hyphen',\n };\n }\n if (label.includes('--')) {\n return { valid: false, reason: 'label may not contain consecutive hyphens' };\n }\n return { valid: true };\n}\n\n/**\n * Build an unsigned PTB that creates a `<label>.audric.sui` leaf subname pointing\n * to `targetAddress`.\n *\n * The returned `Transaction` has neither sender nor gas configured — the caller\n * (audric's `/api/identity/reserve` route) sets the sender to the parent NFT\n * custody address and submits via Enoki sponsorship. See `audric-transaction-flow.mdc`\n * for the sponsored-tx wrapper pattern; note SPEC 10 leaf-mint is a documented\n * CANONICAL-BYPASS of `composeTx` because the signer is the service account, not\n * the user's zkLogin key.\n *\n * Throws synchronously if `label` violates protocol rules or `targetAddress` is\n * not a valid Sui address — fail-closed before bytes are built.\n */\nexport function buildAddLeafTx(\n suinsClient: SuinsClient,\n { label, targetAddress, parent = AUDRIC_PARENT }: BuildAddLeafParams,\n): Transaction {\n const labelCheck = validateLabel(label);\n if (!labelCheck.valid) {\n throw new Error(`buildAddLeafTx: invalid label \"${label}\" — ${labelCheck.reason}`);\n }\n if (typeof targetAddress !== 'string' || !isValidSuiAddress(normalizeSuiAddress(targetAddress))) {\n throw new Error(`buildAddLeafTx: invalid targetAddress \"${targetAddress}\"`);\n }\n if (!parent.nftId) {\n throw new Error(`buildAddLeafTx: parent NFT id not configured for \"${parent.name}\"`);\n }\n\n const tx = new Transaction();\n const suinsTx = new SuinsTransaction(suinsClient, tx);\n suinsTx.createLeafSubName({\n parentNft: parent.nftId,\n name: `${label}.${parent.name}`,\n targetAddress: normalizeSuiAddress(targetAddress),\n });\n return tx;\n}\n\n/**\n * Build an unsigned PTB that revokes a `<label>.audric.sui` leaf subname.\n *\n * Used by:\n * 1. The change-username flow (`/api/identity/change`): revoke old leaf inside\n * the same PTB as the new leaf creation, atomically.\n * 2. The release-username flow (`/api/admin/identity/release`): admin recovery\n * of squatted / impersonating handles.\n * 3. Account-deletion flow (future): revoke leaf when user deletes their account.\n *\n * The mainnet smoke test (2026-05-01) confirmed revocation gas cost is roughly\n * negative net (storage rebate exceeds computation) — see RUNBOOK §4.\n */\nexport function buildRevokeLeafTx(\n suinsClient: SuinsClient,\n { label, parent = AUDRIC_PARENT }: BuildRevokeLeafParams,\n): Transaction {\n const labelCheck = validateLabel(label);\n if (!labelCheck.valid) {\n throw new Error(`buildRevokeLeafTx: invalid label \"${label}\" — ${labelCheck.reason}`);\n }\n if (!parent.nftId) {\n throw new Error(`buildRevokeLeafTx: parent NFT id not configured for \"${parent.name}\"`);\n }\n\n const tx = new Transaction();\n const suinsTx = new SuinsTransaction(suinsClient, tx);\n suinsTx.removeLeafSubName({\n parentNft: parent.nftId,\n name: `${label}.${parent.name}`,\n });\n return tx;\n}\n\n/**\n * Convenience: turn a bare label into the full `<label>.audric.sui` path.\n *\n * **Use this for ON-CHAIN operations** — SuiNS leaf NFT `name` field, the\n * `createLeafSubName` / `removeLeafSubName` move calls, and any RPC call\n * that returns/expects the canonical name string. The `<label>.audric.sui`\n * form is what the SuiNS protocol writes into the NFT `name` field.\n *\n * **Do NOT use this for UI rendering** — that's `displayHandle()`'s job\n * (S.118 reversal of SPEC 10 D10, see audric-build-tracker). Pre-S.118\n * we surfaced the full `.sui` form everywhere; we now use the SuiNS V2\n * `@` form (`alice@audric`) for display because it's shorter, fits the\n * agent harness mono aesthetic, and matches SuiNS's own V2 standard.\n *\n * Both forms resolve to the same address via SuiNS RPC (verified\n * mainnet 2026-05-08 PF1) — `displayHandle()` is purely a render-layer\n * choice, not a backend storage change.\n */\nexport function fullHandle(\n label: string,\n parentName: string = AUDRIC_PARENT_NAME,\n): string {\n return `${label}.${parentName}`;\n}\n\n/**\n * SuiNS V2 short-form display alias. `displayHandle('alice')` →\n * `'alice@audric'`. Use for chat narration, permission cards, receipts,\n * profile pages, share-to-X copy, OG metadata, and lookup_user output.\n *\n * **Why a separate function from `fullHandle`:**\n * - `fullHandle('alice')` → `'alice.audric.sui'` is the **on-chain**\n * NFT name field; SuiNS's `createLeafSubName` writes exactly this\n * string and `suix_resolveNameServiceAddress` accepts it.\n * - `displayHandle('alice')` → `'alice@audric'` is the **UI** form\n * that users see and share. SuiNS RPC also accepts this form\n * (verified mainnet 2026-05-08 PF1 — both forms return the same\n * address), so we have one storage form (`<label>.audric.sui`) and\n * two interchangeable input forms (the user can paste either).\n *\n * Reverses SPEC 10 D10 (\"full handle ALWAYS\"). See audric-build-tracker\n * S.118 for the rationale; see also `audric/apps/web/lib/identity/`\n * for canonicalization in the input parser (which is a no-op since\n * SuiNS RPC accepts both — kept available for future-proofing).\n */\nexport function displayHandle(\n label: string,\n parentName: string = AUDRIC_PARENT_NAME,\n): string {\n // Strip the trailing `.sui` TLD for the `@` display form.\n // `displayHandle('alice')` → `'alice@audric'`; for Agent ID,\n // `displayHandle('bot', AGENT_ID_PARENT_NAME)`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A;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAC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C,KAAK,YAAO,WAAW,MAAM,EAAE;EACtF;AACA,MAAI,CAAC,OAAO,OAAO;AACjB,UAAM,IAAI,MAAM,wDAAwD,OAAO,IAAI,GAAG;EACxF;AAEA,QAAM,KAAK,IAAImB,YAAAA;AACf,QAAM,UAAU,IAAI,iBAAiB,aAAa,EAAE;AACpD,UAAQ,kBAAkB;IACxB,WAAW,OAAO;IAClB,MAAM,GAAG,KAAK,IAAI,OAAO,IAAI;EAAA,CAC9B;AACD,SAAO;AACT;AAoBO,SAAS,WACd,OACA,aAAqB,oBACb;AACR,SAAO,GAAG,KAAK,IAAI,UAAU;AAC/B;AAsBO,SAAS,cACd,OACA,aAAqB,oBACb;AAIR,QAAM,gBAAgB,WAAW,QAAQ,UAAU,EAAE;AACrD,SAAO,GAAG,KAAK,IAAI,aAAa;AAClC;AJfA,eAAA;","names":["EventEmitter","fromBase64","result","toBase64","GrpcTransactionType","TransactionEffectsType","BalanceChangeType","OperationTypeNode","Kind","#fetch","fromBase64","bcs","bcs","sha512","_0n","_1n","_0n","_1n","Fp","Fp","_1n","_0n","_1n","_0n","_1n","_0n","_1n","_0n","Fp","Fn","_0n","_1n","_2n","_8n","Fp","Fn","uvRatio","p","Fp","Fn","randomBytes","adjustScalarBytes","_1n","_1n","_2n","_5n","_8n","_2n","_1n","sha512","isBytes","anumber","abytes","ahash","anumber","aexists","abytes","clean","abytes","createHasher","oidNist","ahash","abytes","clean","aexists","hmac","ahash","anumber","hmac","clean","HashMD","aexists","abytes","clean","SHA512_IV","split","shrSH","shrSL","rotrSH","rotrSL","rotrBH","rotrBL","add","add3L","add3H","add4L","add4H","add5L","add5H","K512","split","SHA512_Kh","SHA512_Kl","SHA512_W_H","SHA512_W_L","SHA2_64B","HashMD","rotrSH","shrSH","rotrSL","shrSL","rotrBH","rotrBL","add4L","add4H","add5L","add5H","add","add3L","add3H","clean","_SHA512","SHA512_IV","sha512","createHasher","_SHA512","oidNist","sha512","bip39MnemonicToSeedSync","_HMAC","hmac","hmac","sha512","Ed25519Keypair","_0n","_1n","isBytes","hexToNumber","_0n","bytesToNumberBE","bytesToHex","bytesToNumberLE","abytes","numberToBytesBE","hexToBytes","numberToBytesLE","hexToBytes","isBytes","copyBytes","isPosBig","_0n","inRange","aInRange","bitLen","_1n","bitMask","_1n","concatBytes","notImplemented","memoized","_0n","_1n","_2n","_3n","_4n","_5n","_7n","_8n","_9n","_16n","mod","pow2","_0n","invert","mod","_1n","assertIsSquare","Fp","sqrt3mod4","_4n","sqrt5mod8","_5n","_8n","_2n","sqrt9mod16","Field","tonelliShanks","_7n","_16n","_3n","FpLegendre","FpSqrt","_9n","isNegativeLE","FIELD_FIELDS","validateField","FpPow","FpInvertBatch","FpLegendre","Fp","_1n","_2n","nLength","anumber","Field","_0n","bitMask","_1n","mod","FpPow","invert","FpSqrt","numberToBytesLE","numberToBytesBE","bytesToNumberLE","bytesToNumberBE","FpInvertBatch","bytesToNumberLE","bytesToNumberBE","mod","_1n","numberToBytesLE","numberToBytesBE","_0n","_1n","negateCt","normalizeZ","FpInvertBatch","validateW","calcWOpts","bitMask","calcOffsets","pointPrecomputes","pointWindowSizes","getW","assert0","wNAF","bitLen","wbits","createField","validateField","Field","_0n","Fp","Fn","_0n","_1n","_2n","_8n","isEdValidXY","Fp","edwards","Fn","uvRatio","aInRange","memoized","copyBytes","bytesToNumberLE","p","normalizeZ","bytesToHex","wNAF","PrimeEdwardsPoint","notImplemented","eddsa","randomBytes","adjustScalarBytes","concatBytes","isBytes","Field","_0n","_1n","_2n","_3n","_5n","_8n","ed25519_CURVE_p","ed25519_CURVE","ed25519_pow_2_252_3","pow2","adjustScalarBytes","ED25519_SQRT_M1","uvRatio","mod","isNegativeLE","Field","ed25519","ED25519_SQRT_M1","uvRatio","_1n","ed25519","bytesToNumberLE","ed25519_CURVE","ed25519_CURVE_p","mod","isNegativeLE","abytes","PrimeEdwardsPoint","_0n","_2n","_0n","bitMask","bitLen","_1n","bytesToNumberBE","_3n","_4n","Fn","Fp","concatBytes","memoized","negateCt","endo","normalizeZ","bytesToHex","wNAF","Fp","Fn","randomBytes","ahash","hmac","concatBytes","_1n","r","s","hexToBytes","_2n","bytesToHex","bytesToNumberBE","bitMask","aInRange","_0n","isBytes","Fp","Fn","Field","nLength","_2n","_3n","pow2","Field","val","$moduleName","$moduleName","$moduleName","Entry","VecMap","$moduleName","type_name.TypeName","vec_map.VecMap","$moduleName","TypeName","$moduleName","domain_1.Domain","vec_map.VecMap","type_name.TypeName","$moduleName","domain.Domain","$moduleName","$moduleName","bag.Bag","$moduleName","data.Data","$moduleName","$moduleName","$moduleName","$moduleName","pricing_config.Range","linked_table.LinkedTable","payment.initRegistration","payment.initRenewal","paymentsModule.calculatePrice","paymentsModule.handleBasePayment","paymentsModule.handlePayment","payment.register","payment.renew","paymentsModule.calculatePriceAfterDiscount","couponHouse.applyCoupon","freeClaims.freeClaim","discounts.applyPercentageDiscount","controller.setReverseLookup","controller.burnExpiredSubname","controller.burnExpired","isValidSuiAddress","normalizeSuiAddress","requested","swapAll","effectiveAmount","coin","SUI_TYPE","BN","T2000Error","selectSuiCoin","selectAndSplitCoin","findSwapRoute","resolveTokenType","serializeCetusRoute","mod","body","result","buildCoinToAddressBalanceMigration","SuiGrpcClient","getDecimalsForCoinType","Transaction","hexToBytes","canonical","ed25519","sha256","bytesToHex","join","homedir","dirname","DEFAULT_CONFIG_DIR","EventEmitter","buildSwapTx","preflightSwap","coinWithBalance","getSwapQuote","CLOCK_ID","clean"]}