@hypurrquant/defi-cli 0.2.4 → 0.2.5

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/error.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/util.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/date.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/primitive.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/extract.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/struct.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/parse.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/stringify.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/index.js","../../defi-core/src/types.ts","../../defi-core/src/error.ts","../../defi-core/src/json.ts","../../defi-core/src/erc20.ts","../../defi-core/src/provider.ts","../../defi-core/src/multicall.ts","../../defi-core/src/registry/chain.ts","../../defi-core/src/registry/protocol.ts","../../defi-core/src/registry/registry.ts","../../defi-protocols/src/factory.ts","../../defi-protocols/src/dex/uniswap_v3.ts","../../defi-protocols/src/dex/uniswap_v2.ts","../../defi-protocols/src/dex/algebra_v3.ts","../../defi-protocols/src/dex/balancer_v3.ts","../../defi-protocols/src/dex/curve.ts","../../defi-protocols/src/dex/solidly.ts","../../defi-protocols/src/dex/woofi.ts","../../defi-protocols/src/dex/solidly_gauge.ts","../../defi-protocols/src/dex/masterchef.ts","../../defi-protocols/src/lending/aave_v3.ts","../../defi-protocols/src/lending/aave_v2.ts","../../defi-protocols/src/lending/aave_oracle.ts","../../defi-protocols/src/lending/compound_v2.ts","../../defi-protocols/src/lending/compound_v3.ts","../../defi-protocols/src/lending/euler_v2.ts","../../defi-protocols/src/lending/morpho.ts","../../defi-protocols/src/cdp/felix.ts","../../defi-protocols/src/cdp/felix_oracle.ts","../../defi-protocols/src/vault/erc4626.ts","../../defi-protocols/src/liquid_staking/generic_lst.ts","../../defi-protocols/src/liquid_staking/sthype.ts","../../defi-protocols/src/liquid_staking/kinetiq.ts","../../defi-protocols/src/yield_source/pendle.ts","../../defi-protocols/src/yield_source/generic_yield.ts","../../defi-protocols/src/derivatives/hlp.ts","../../defi-protocols/src/derivatives/generic_derivatives.ts","../../defi-protocols/src/options/rysk.ts","../../defi-protocols/src/options/generic_options.ts","../../defi-protocols/src/nft/erc721.ts","../../defi-protocols/src/dex/dex_price.ts","../src/mcp-server.ts","../src/executor.ts"],"sourcesContent":["/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nfunction getLineColFromPtr(string, ptr) {\n let lines = string.slice(0, ptr).split(/\\r\\n|\\n|\\r/g);\n return [lines.length, lines.pop().length + 1];\n}\nfunction makeCodeBlock(string, line, column) {\n let lines = string.split(/\\r\\n|\\n|\\r/g);\n let codeblock = '';\n let numberLen = (Math.log10(line + 1) | 0) + 1;\n for (let i = line - 1; i <= line + 1; i++) {\n let l = lines[i - 1];\n if (!l)\n continue;\n codeblock += i.toString().padEnd(numberLen, ' ');\n codeblock += ': ';\n codeblock += l;\n codeblock += '\\n';\n if (i === line) {\n codeblock += ' '.repeat(numberLen + column + 2);\n codeblock += '^\\n';\n }\n }\n return codeblock;\n}\nexport class TomlError extends Error {\n line;\n column;\n codeblock;\n constructor(message, options) {\n const [line, column] = getLineColFromPtr(options.toml, options.ptr);\n const codeblock = makeCodeBlock(options.toml, line, column);\n super(`Invalid TOML document: ${message}\\n\\n${codeblock}`, options);\n this.line = line;\n this.column = column;\n this.codeblock = codeblock;\n }\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { TomlError } from './error.js';\nfunction isEscaped(str, ptr) {\n let i = 0;\n while (str[ptr - ++i] === '\\\\')\n ;\n return --i && (i % 2);\n}\nexport function indexOfNewline(str, start = 0, end = str.length) {\n let idx = str.indexOf('\\n', start);\n if (str[idx - 1] === '\\r')\n idx--;\n return idx <= end ? idx : -1;\n}\nexport function skipComment(str, ptr) {\n for (let i = ptr; i < str.length; i++) {\n let c = str[i];\n if (c === '\\n')\n return i;\n if (c === '\\r' && str[i + 1] === '\\n')\n return i + 1;\n if ((c < '\\x20' && c !== '\\t') || c === '\\x7f') {\n throw new TomlError('control characters are not allowed in comments', {\n toml: str,\n ptr: ptr,\n });\n }\n }\n return str.length;\n}\nexport function skipVoid(str, ptr, banNewLines, banComments) {\n let c;\n while ((c = str[ptr]) === ' ' || c === '\\t' || (!banNewLines && (c === '\\n' || c === '\\r' && str[ptr + 1] === '\\n')))\n ptr++;\n return banComments || c !== '#'\n ? ptr\n : skipVoid(str, skipComment(str, ptr), banNewLines);\n}\nexport function skipUntil(str, ptr, sep, end, banNewLines = false) {\n if (!end) {\n ptr = indexOfNewline(str, ptr);\n return ptr < 0 ? str.length : ptr;\n }\n for (let i = ptr; i < str.length; i++) {\n let c = str[i];\n if (c === '#') {\n i = indexOfNewline(str, i);\n }\n else if (c === sep) {\n return i + 1;\n }\n else if (c === end || (banNewLines && (c === '\\n' || (c === '\\r' && str[i + 1] === '\\n')))) {\n return i;\n }\n }\n throw new TomlError('cannot find end of structure', {\n toml: str,\n ptr: ptr\n });\n}\nexport function getStringEnd(str, seek) {\n let first = str[seek];\n let target = first === str[seek + 1] && str[seek + 1] === str[seek + 2]\n ? str.slice(seek, seek + 3)\n : first;\n seek += target.length - 1;\n do\n seek = str.indexOf(target, ++seek);\n while (seek > -1 && first !== \"'\" && isEscaped(str, seek));\n if (seek > -1) {\n seek += target.length;\n if (target.length > 1) {\n if (str[seek] === first)\n seek++;\n if (str[seek] === first)\n seek++;\n }\n }\n return seek;\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nlet DATE_TIME_RE = /^(\\d{4}-\\d{2}-\\d{2})?[T ]?(?:(\\d{2}):\\d{2}(?::\\d{2}(?:\\.\\d+)?)?)?(Z|[-+]\\d{2}:\\d{2})?$/i;\nexport class TomlDate extends Date {\n #hasDate = false;\n #hasTime = false;\n #offset = null;\n constructor(date) {\n let hasDate = true;\n let hasTime = true;\n let offset = 'Z';\n if (typeof date === 'string') {\n let match = date.match(DATE_TIME_RE);\n if (match) {\n if (!match[1]) {\n hasDate = false;\n date = `0000-01-01T${date}`;\n }\n hasTime = !!match[2];\n // Make sure to use T instead of a space. Breaks in case of extreme values otherwise.\n hasTime && date[10] === ' ' && (date = date.replace(' ', 'T'));\n // Do not allow rollover hours.\n if (match[2] && +match[2] > 23) {\n date = '';\n }\n else {\n offset = match[3] || null;\n date = date.toUpperCase();\n if (!offset && hasTime)\n date += 'Z';\n }\n }\n else {\n date = '';\n }\n }\n super(date);\n if (!isNaN(this.getTime())) {\n this.#hasDate = hasDate;\n this.#hasTime = hasTime;\n this.#offset = offset;\n }\n }\n isDateTime() {\n return this.#hasDate && this.#hasTime;\n }\n isLocal() {\n return !this.#hasDate || !this.#hasTime || !this.#offset;\n }\n isDate() {\n return this.#hasDate && !this.#hasTime;\n }\n isTime() {\n return this.#hasTime && !this.#hasDate;\n }\n isValid() {\n return this.#hasDate || this.#hasTime;\n }\n toISOString() {\n let iso = super.toISOString();\n // Local Date\n if (this.isDate())\n return iso.slice(0, 10);\n // Local Time\n if (this.isTime())\n return iso.slice(11, 23);\n // Local DateTime\n if (this.#offset === null)\n return iso.slice(0, -1);\n // Offset DateTime\n if (this.#offset === 'Z')\n return iso;\n // This part is quite annoying: JS strips the original timezone from the ISO string representation\n // Instead of using a \"modified\" date and \"Z\", we restore the representation \"as authored\"\n let offset = (+(this.#offset.slice(1, 3)) * 60) + +(this.#offset.slice(4, 6));\n offset = this.#offset[0] === '-' ? offset : -offset;\n let offsetDate = new Date(this.getTime() - (offset * 60e3));\n return offsetDate.toISOString().slice(0, -1) + this.#offset;\n }\n static wrapAsOffsetDateTime(jsDate, offset = 'Z') {\n let date = new TomlDate(jsDate);\n date.#offset = offset;\n return date;\n }\n static wrapAsLocalDateTime(jsDate) {\n let date = new TomlDate(jsDate);\n date.#offset = null;\n return date;\n }\n static wrapAsLocalDate(jsDate) {\n let date = new TomlDate(jsDate);\n date.#hasTime = false;\n date.#offset = null;\n return date;\n }\n static wrapAsLocalTime(jsDate) {\n let date = new TomlDate(jsDate);\n date.#hasDate = false;\n date.#offset = null;\n return date;\n }\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { skipVoid } from './util.js';\nimport { TomlDate } from './date.js';\nimport { TomlError } from './error.js';\nlet INT_REGEX = /^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\\d(_?\\d)*))$/;\nlet FLOAT_REGEX = /^[+-]?\\d(_?\\d)*(\\.\\d(_?\\d)*)?([eE][+-]?\\d(_?\\d)*)?$/;\nlet LEADING_ZERO = /^[+-]?0[0-9_]/;\nlet ESCAPE_REGEX = /^[0-9a-f]{2,8}$/i;\nlet ESC_MAP = {\n b: '\\b',\n t: '\\t',\n n: '\\n',\n f: '\\f',\n r: '\\r',\n e: '\\x1b',\n '\"': '\"',\n '\\\\': '\\\\',\n};\nexport function parseString(str, ptr = 0, endPtr = str.length) {\n let isLiteral = str[ptr] === '\\'';\n let isMultiline = str[ptr++] === str[ptr] && str[ptr] === str[ptr + 1];\n if (isMultiline) {\n endPtr -= 2;\n if (str[ptr += 2] === '\\r')\n ptr++;\n if (str[ptr] === '\\n')\n ptr++;\n }\n let tmp = 0;\n let isEscape;\n let parsed = '';\n let sliceStart = ptr;\n while (ptr < endPtr - 1) {\n let c = str[ptr++];\n if (c === '\\n' || (c === '\\r' && str[ptr] === '\\n')) {\n if (!isMultiline) {\n throw new TomlError('newlines are not allowed in strings', {\n toml: str,\n ptr: ptr - 1,\n });\n }\n }\n else if ((c < '\\x20' && c !== '\\t') || c === '\\x7f') {\n throw new TomlError('control characters are not allowed in strings', {\n toml: str,\n ptr: ptr - 1,\n });\n }\n if (isEscape) {\n isEscape = false;\n if (c === 'x' || c === 'u' || c === 'U') {\n // Unicode escape\n let code = str.slice(ptr, (ptr += (c === 'x' ? 2 : c === 'u' ? 4 : 8)));\n if (!ESCAPE_REGEX.test(code)) {\n throw new TomlError('invalid unicode escape', {\n toml: str,\n ptr: tmp,\n });\n }\n try {\n parsed += String.fromCodePoint(parseInt(code, 16));\n }\n catch {\n throw new TomlError('invalid unicode escape', {\n toml: str,\n ptr: tmp,\n });\n }\n }\n else if (isMultiline && (c === '\\n' || c === ' ' || c === '\\t' || c === '\\r')) {\n // Multiline escape\n ptr = skipVoid(str, ptr - 1, true);\n if (str[ptr] !== '\\n' && str[ptr] !== '\\r') {\n throw new TomlError('invalid escape: only line-ending whitespace may be escaped', {\n toml: str,\n ptr: tmp,\n });\n }\n ptr = skipVoid(str, ptr);\n }\n else if (c in ESC_MAP) {\n // Classic escape\n parsed += ESC_MAP[c];\n }\n else {\n throw new TomlError('unrecognized escape sequence', {\n toml: str,\n ptr: tmp,\n });\n }\n sliceStart = ptr;\n }\n else if (!isLiteral && c === '\\\\') {\n tmp = ptr - 1;\n isEscape = true;\n parsed += str.slice(sliceStart, tmp);\n }\n }\n return parsed + str.slice(sliceStart, endPtr - 1);\n}\nexport function parseValue(value, toml, ptr, integersAsBigInt) {\n // Constant values\n if (value === 'true')\n return true;\n if (value === 'false')\n return false;\n if (value === '-inf')\n return -Infinity;\n if (value === 'inf' || value === '+inf')\n return Infinity;\n if (value === 'nan' || value === '+nan' || value === '-nan')\n return NaN;\n // Avoid FP representation of -0\n if (value === '-0')\n return integersAsBigInt ? 0n : 0;\n // Numbers\n let isInt = INT_REGEX.test(value);\n if (isInt || FLOAT_REGEX.test(value)) {\n if (LEADING_ZERO.test(value)) {\n throw new TomlError('leading zeroes are not allowed', {\n toml: toml,\n ptr: ptr,\n });\n }\n value = value.replace(/_/g, '');\n let numeric = +value;\n if (isNaN(numeric)) {\n throw new TomlError('invalid number', {\n toml: toml,\n ptr: ptr,\n });\n }\n if (isInt) {\n if ((isInt = !Number.isSafeInteger(numeric)) && !integersAsBigInt) {\n throw new TomlError('integer value cannot be represented losslessly', {\n toml: toml,\n ptr: ptr,\n });\n }\n if (isInt || integersAsBigInt === true)\n numeric = BigInt(value);\n }\n return numeric;\n }\n const date = new TomlDate(value);\n if (!date.isValid()) {\n throw new TomlError('invalid value', {\n toml: toml,\n ptr: ptr,\n });\n }\n return date;\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parseString, parseValue } from './primitive.js';\nimport { parseArray, parseInlineTable } from './struct.js';\nimport { skipVoid, skipUntil, skipComment, getStringEnd } from './util.js';\nimport { TomlError } from './error.js';\nfunction sliceAndTrimEndOf(str, startPtr, endPtr) {\n let value = str.slice(startPtr, endPtr);\n let commentIdx = value.indexOf('#');\n if (commentIdx > -1) {\n // The call to skipComment allows to \"validate\" the comment\n // (absence of control characters)\n skipComment(str, commentIdx);\n value = value.slice(0, commentIdx);\n }\n return [value.trimEnd(), commentIdx];\n}\nexport function extractValue(str, ptr, end, depth, integersAsBigInt) {\n if (depth === 0) {\n throw new TomlError('document contains excessively nested structures. aborting.', {\n toml: str,\n ptr: ptr\n });\n }\n let c = str[ptr];\n if (c === '[' || c === '{') {\n let [value, endPtr] = c === '['\n ? parseArray(str, ptr, depth, integersAsBigInt)\n : parseInlineTable(str, ptr, depth, integersAsBigInt);\n if (end) {\n endPtr = skipVoid(str, endPtr);\n if (str[endPtr] === ',')\n endPtr++;\n else if (str[endPtr] !== end) {\n throw new TomlError('expected comma or end of structure', {\n toml: str,\n ptr: endPtr,\n });\n }\n }\n return [value, endPtr];\n }\n let endPtr;\n if (c === '\"' || c === \"'\") {\n endPtr = getStringEnd(str, ptr);\n let parsed = parseString(str, ptr, endPtr);\n if (end) {\n endPtr = skipVoid(str, endPtr);\n if (str[endPtr] && str[endPtr] !== ',' && str[endPtr] !== end && str[endPtr] !== '\\n' && str[endPtr] !== '\\r') {\n throw new TomlError('unexpected character encountered', {\n toml: str,\n ptr: endPtr,\n });\n }\n endPtr += (+(str[endPtr] === ','));\n }\n return [parsed, endPtr];\n }\n endPtr = skipUntil(str, ptr, ',', end);\n let slice = sliceAndTrimEndOf(str, ptr, endPtr - (+(str[endPtr - 1] === ',')));\n if (!slice[0]) {\n throw new TomlError('incomplete key-value declaration: no value specified', {\n toml: str,\n ptr: ptr\n });\n }\n if (end && slice[1] > -1) {\n endPtr = skipVoid(str, ptr + slice[1]);\n endPtr += +(str[endPtr] === ',');\n }\n return [\n parseValue(slice[0], str, ptr, integersAsBigInt),\n endPtr,\n ];\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parseString } from './primitive.js';\nimport { extractValue } from './extract.js';\nimport { getStringEnd, indexOfNewline, skipComment, skipVoid } from './util.js';\nimport { TomlError } from './error.js';\nlet KEY_PART_RE = /^[a-zA-Z0-9-_]+[ \\t]*$/;\nexport function parseKey(str, ptr, end = '=') {\n let dot = ptr - 1;\n let parsed = [];\n let endPtr = str.indexOf(end, ptr);\n if (endPtr < 0) {\n throw new TomlError('incomplete key-value: cannot find end of key', {\n toml: str,\n ptr: ptr,\n });\n }\n do {\n let c = str[ptr = ++dot];\n // If it's whitespace, ignore\n if (c !== ' ' && c !== '\\t') {\n // If it's a string\n if (c === '\"' || c === '\\'') {\n if (c === str[ptr + 1] && c === str[ptr + 2]) {\n throw new TomlError('multiline strings are not allowed in keys', {\n toml: str,\n ptr: ptr,\n });\n }\n let eos = getStringEnd(str, ptr);\n if (eos < 0) {\n throw new TomlError('unfinished string encountered', {\n toml: str,\n ptr: ptr,\n });\n }\n dot = str.indexOf('.', eos);\n let strEnd = str.slice(eos, dot < 0 || dot > endPtr ? endPtr : dot);\n let newLine = indexOfNewline(strEnd);\n if (newLine > -1) {\n throw new TomlError('newlines are not allowed in keys', {\n toml: str,\n ptr: ptr + dot + newLine,\n });\n }\n if (strEnd.trimStart()) {\n throw new TomlError('found extra tokens after the string part', {\n toml: str,\n ptr: eos,\n });\n }\n if (endPtr < eos) {\n endPtr = str.indexOf(end, eos);\n if (endPtr < 0) {\n throw new TomlError('incomplete key-value: cannot find end of key', {\n toml: str,\n ptr: ptr,\n });\n }\n }\n parsed.push(parseString(str, ptr, eos));\n }\n else {\n // Normal raw key part consumption and validation\n dot = str.indexOf('.', ptr);\n let part = str.slice(ptr, dot < 0 || dot > endPtr ? endPtr : dot);\n if (!KEY_PART_RE.test(part)) {\n throw new TomlError('only letter, numbers, dashes and underscores are allowed in keys', {\n toml: str,\n ptr: ptr,\n });\n }\n parsed.push(part.trimEnd());\n }\n }\n // Until there's no more dot\n } while (dot + 1 && dot < endPtr);\n return [parsed, skipVoid(str, endPtr + 1, true, true)];\n}\nexport function parseInlineTable(str, ptr, depth, integersAsBigInt) {\n let res = {};\n let seen = new Set();\n let c;\n ptr++;\n while ((c = str[ptr++]) !== '}' && c) {\n if (c === ',') {\n throw new TomlError('expected value, found comma', {\n toml: str,\n ptr: ptr - 1,\n });\n }\n else if (c === '#')\n ptr = skipComment(str, ptr);\n else if (c !== ' ' && c !== '\\t' && c !== '\\n' && c !== '\\r') {\n let k;\n let t = res;\n let hasOwn = false;\n let [key, keyEndPtr] = parseKey(str, ptr - 1);\n for (let i = 0; i < key.length; i++) {\n if (i)\n t = hasOwn ? t[k] : (t[k] = {});\n k = key[i];\n if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== 'object' || seen.has(t[k]))) {\n throw new TomlError('trying to redefine an already defined value', {\n toml: str,\n ptr: ptr,\n });\n }\n if (!hasOwn && k === '__proto__') {\n Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });\n }\n }\n if (hasOwn) {\n throw new TomlError('trying to redefine an already defined value', {\n toml: str,\n ptr: ptr,\n });\n }\n let [value, valueEndPtr] = extractValue(str, keyEndPtr, '}', depth - 1, integersAsBigInt);\n seen.add(value);\n t[k] = value;\n ptr = valueEndPtr;\n }\n }\n if (!c) {\n throw new TomlError('unfinished table encountered', {\n toml: str,\n ptr: ptr,\n });\n }\n return [res, ptr];\n}\nexport function parseArray(str, ptr, depth, integersAsBigInt) {\n let res = [];\n let c;\n ptr++;\n while ((c = str[ptr++]) !== ']' && c) {\n if (c === ',') {\n throw new TomlError('expected value, found comma', {\n toml: str,\n ptr: ptr - 1,\n });\n }\n else if (c === '#')\n ptr = skipComment(str, ptr);\n else if (c !== ' ' && c !== '\\t' && c !== '\\n' && c !== '\\r') {\n let e = extractValue(str, ptr - 1, ']', depth - 1, integersAsBigInt);\n res.push(e[0]);\n ptr = e[1];\n }\n }\n if (!c) {\n throw new TomlError('unfinished array encountered', {\n toml: str,\n ptr: ptr,\n });\n }\n return [res, ptr];\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parseKey } from './struct.js';\nimport { extractValue } from './extract.js';\nimport { skipVoid } from './util.js';\nimport { TomlError } from './error.js';\nfunction peekTable(key, table, meta, type) {\n let t = table;\n let m = meta;\n let k;\n let hasOwn = false;\n let state;\n for (let i = 0; i < key.length; i++) {\n if (i) {\n t = hasOwn ? t[k] : (t[k] = {});\n m = (state = m[k]).c;\n if (type === 0 /* Type.DOTTED */ && (state.t === 1 /* Type.EXPLICIT */ || state.t === 2 /* Type.ARRAY */)) {\n return null;\n }\n if (state.t === 2 /* Type.ARRAY */) {\n let l = t.length - 1;\n t = t[l];\n m = m[l].c;\n }\n }\n k = key[i];\n if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 /* Type.DOTTED */ && m[k]?.d) {\n return null;\n }\n if (!hasOwn) {\n if (k === '__proto__') {\n Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });\n Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });\n }\n m[k] = {\n t: i < key.length - 1 && type === 2 /* Type.ARRAY */\n ? 3 /* Type.ARRAY_DOTTED */\n : type,\n d: false,\n i: 0,\n c: {},\n };\n }\n }\n state = m[k];\n if (state.t !== type && !(type === 1 /* Type.EXPLICIT */ && state.t === 3 /* Type.ARRAY_DOTTED */)) {\n // Bad key type!\n return null;\n }\n if (type === 2 /* Type.ARRAY */) {\n if (!state.d) {\n state.d = true;\n t[k] = [];\n }\n t[k].push(t = {});\n state.c[state.i++] = (state = { t: 1 /* Type.EXPLICIT */, d: false, i: 0, c: {} });\n }\n if (state.d) {\n // Redefining a table!\n return null;\n }\n state.d = true;\n if (type === 1 /* Type.EXPLICIT */) {\n t = hasOwn ? t[k] : (t[k] = {});\n }\n else if (type === 0 /* Type.DOTTED */ && hasOwn) {\n return null;\n }\n return [k, t, state.c];\n}\nexport function parse(toml, { maxDepth = 1000, integersAsBigInt } = {}) {\n let res = {};\n let meta = {};\n let tbl = res;\n let m = meta;\n for (let ptr = skipVoid(toml, 0); ptr < toml.length;) {\n if (toml[ptr] === '[') {\n let isTableArray = toml[++ptr] === '[';\n let k = parseKey(toml, ptr += +isTableArray, ']');\n if (isTableArray) {\n if (toml[k[1] - 1] !== ']') {\n throw new TomlError('expected end of table declaration', {\n toml: toml,\n ptr: k[1] - 1,\n });\n }\n k[1]++;\n }\n let p = peekTable(k[0], res, meta, isTableArray ? 2 /* Type.ARRAY */ : 1 /* Type.EXPLICIT */);\n if (!p) {\n throw new TomlError('trying to redefine an already defined table or value', {\n toml: toml,\n ptr: ptr,\n });\n }\n m = p[2];\n tbl = p[1];\n ptr = k[1];\n }\n else {\n let k = parseKey(toml, ptr);\n let p = peekTable(k[0], tbl, m, 0 /* Type.DOTTED */);\n if (!p) {\n throw new TomlError('trying to redefine an already defined table or value', {\n toml: toml,\n ptr: ptr,\n });\n }\n let v = extractValue(toml, k[1], void 0, maxDepth, integersAsBigInt);\n p[1][p[0]] = v[0];\n ptr = v[1];\n }\n ptr = skipVoid(toml, ptr, true);\n if (toml[ptr] && toml[ptr] !== '\\n' && toml[ptr] !== '\\r') {\n throw new TomlError('each key-value declaration must be followed by an end-of-line', {\n toml: toml,\n ptr: ptr\n });\n }\n ptr = skipVoid(toml, ptr);\n }\n return res;\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nlet BARE_KEY = /^[a-z0-9-_]+$/i;\nfunction extendedTypeOf(obj) {\n let type = typeof obj;\n if (type === 'object') {\n if (Array.isArray(obj))\n return 'array';\n if (obj instanceof Date)\n return 'date';\n }\n return type;\n}\nfunction isArrayOfTables(obj) {\n for (let i = 0; i < obj.length; i++) {\n if (extendedTypeOf(obj[i]) !== 'object')\n return false;\n }\n return obj.length != 0;\n}\nfunction formatString(s) {\n return JSON.stringify(s).replace(/\\x7f/g, '\\\\u007f');\n}\nfunction stringifyValue(val, type, depth, numberAsFloat) {\n if (depth === 0) {\n throw new Error('Could not stringify the object: maximum object depth exceeded');\n }\n if (type === 'number') {\n if (isNaN(val))\n return 'nan';\n if (val === Infinity)\n return 'inf';\n if (val === -Infinity)\n return '-inf';\n if (numberAsFloat && Number.isInteger(val))\n return val.toFixed(1);\n return val.toString();\n }\n if (type === 'bigint' || type === 'boolean') {\n return val.toString();\n }\n if (type === 'string') {\n return formatString(val);\n }\n if (type === 'date') {\n if (isNaN(val.getTime())) {\n throw new TypeError('cannot serialize invalid date');\n }\n return val.toISOString();\n }\n if (type === 'object') {\n return stringifyInlineTable(val, depth, numberAsFloat);\n }\n if (type === 'array') {\n return stringifyArray(val, depth, numberAsFloat);\n }\n}\nfunction stringifyInlineTable(obj, depth, numberAsFloat) {\n let keys = Object.keys(obj);\n if (keys.length === 0)\n return '{}';\n let res = '{ ';\n for (let i = 0; i < keys.length; i++) {\n let k = keys[i];\n if (i)\n res += ', ';\n res += BARE_KEY.test(k) ? k : formatString(k);\n res += ' = ';\n res += stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1, numberAsFloat);\n }\n return res + ' }';\n}\nfunction stringifyArray(array, depth, numberAsFloat) {\n if (array.length === 0)\n return '[]';\n let res = '[ ';\n for (let i = 0; i < array.length; i++) {\n if (i)\n res += ', ';\n if (array[i] === null || array[i] === void 0) {\n throw new TypeError('arrays cannot contain null or undefined values');\n }\n res += stringifyValue(array[i], extendedTypeOf(array[i]), depth - 1, numberAsFloat);\n }\n return res + ' ]';\n}\nfunction stringifyArrayTable(array, key, depth, numberAsFloat) {\n if (depth === 0) {\n throw new Error('Could not stringify the object: maximum object depth exceeded');\n }\n let res = '';\n for (let i = 0; i < array.length; i++) {\n res += `${res && '\\n'}[[${key}]]\\n`;\n res += stringifyTable(0, array[i], key, depth, numberAsFloat);\n }\n return res;\n}\nfunction stringifyTable(tableKey, obj, prefix, depth, numberAsFloat) {\n if (depth === 0) {\n throw new Error('Could not stringify the object: maximum object depth exceeded');\n }\n let preamble = '';\n let tables = '';\n let keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n let k = keys[i];\n if (obj[k] !== null && obj[k] !== void 0) {\n let type = extendedTypeOf(obj[k]);\n if (type === 'symbol' || type === 'function') {\n throw new TypeError(`cannot serialize values of type '${type}'`);\n }\n let key = BARE_KEY.test(k) ? k : formatString(k);\n if (type === 'array' && isArrayOfTables(obj[k])) {\n tables += (tables && '\\n') + stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat);\n }\n else if (type === 'object') {\n let tblKey = prefix ? `${prefix}.${key}` : key;\n tables += (tables && '\\n') + stringifyTable(tblKey, obj[k], tblKey, depth - 1, numberAsFloat);\n }\n else {\n preamble += key;\n preamble += ' = ';\n preamble += stringifyValue(obj[k], type, depth, numberAsFloat);\n preamble += '\\n';\n }\n }\n }\n if (tableKey && (preamble || !tables)) // Create table only if necessary\n preamble = preamble ? `[${tableKey}]\\n${preamble}` : `[${tableKey}]`;\n return preamble && tables\n ? `${preamble}\\n${tables}`\n : preamble || tables;\n}\nexport function stringify(obj, { maxDepth = 1000, numbersAsFloat = false } = {}) {\n if (extendedTypeOf(obj) !== 'object') {\n throw new TypeError('stringify can only be called with an object');\n }\n let str = stringifyTable(0, obj, '', maxDepth, numbersAsFloat);\n if (str[str.length - 1] !== '\\n')\n return str + '\\n';\n return str;\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parse } from './parse.js';\nimport { stringify } from './stringify.js';\nimport { TomlDate } from './date.js';\nimport { TomlError } from './error.js';\nexport default { parse, stringify, TomlDate, TomlError };\nexport { parse, stringify, TomlDate, TomlError };\n","import type { Address, Hex } from \"viem\";\n\n// === Transaction Types ===\n\n/** A built DeFi transaction ready for simulation or broadcast */\nexport interface DeFiTx {\n description: string;\n to: Address;\n data: Hex;\n value: bigint;\n gas_estimate?: number;\n}\n\n/** Result of executing or simulating a transaction */\nexport interface ActionResult {\n tx_hash?: string;\n status: TxStatus;\n gas_used?: number;\n description: string;\n details: Record<string, unknown>;\n}\n\n/** Transaction status (serde: snake_case) */\nexport enum TxStatus {\n DryRun = \"dry_run\",\n Simulated = \"simulated\",\n SimulationFailed = \"simulation_failed\",\n Pending = \"pending\",\n Confirmed = \"confirmed\",\n Failed = \"failed\",\n}\n\n// === Token Types ===\n\n/** Token amount with decimals-aware formatting */\nexport interface TokenAmount {\n token: Address;\n symbol: string;\n amount: bigint;\n decimals: number;\n}\n\nexport function formatHuman(t: TokenAmount): string {\n const divisor = 10n ** BigInt(t.decimals);\n const whole = t.amount / divisor;\n const frac = t.amount % divisor;\n return `${whole}.${frac.toString().padStart(t.decimals, \"0\")} ${t.symbol}`;\n}\n\n/** Slippage tolerance in basis points */\nexport interface Slippage {\n bps: number;\n}\n\nexport function newSlippage(bps: number): Slippage {\n return { bps };\n}\n\nexport function defaultSwapSlippage(): Slippage {\n return { bps: 50 };\n}\n\nexport function applyMinSlippage(slippage: Slippage, amount: bigint): bigint {\n return (amount * BigInt(10000 - slippage.bps)) / 10000n;\n}\n\n// === Oracle / Price Types ===\n\nexport interface PriceData {\n source: string;\n source_type: string;\n asset: Address;\n price_usd: bigint;\n price_f64: number;\n block_number?: number;\n timestamp?: number;\n}\n\n// === DEX Types ===\n\nexport interface SwapParams {\n protocol: string;\n token_in: Address;\n token_out: Address;\n amount_in: bigint;\n slippage: Slippage;\n recipient: Address;\n deadline?: number;\n}\n\nexport interface QuoteParams {\n protocol: string;\n token_in: Address;\n token_out: Address;\n amount_in: bigint;\n}\n\nexport interface QuoteResult {\n protocol: string;\n amount_out: bigint;\n price_impact_bps?: number;\n fee_bps?: number;\n route: string[];\n}\n\nexport interface AddLiquidityParams {\n protocol: string;\n token_a: Address;\n token_b: Address;\n amount_a: bigint;\n amount_b: bigint;\n recipient: Address;\n}\n\nexport interface RemoveLiquidityParams {\n protocol: string;\n token_a: Address;\n token_b: Address;\n liquidity: bigint;\n recipient: Address;\n}\n\n// === Lending Types ===\n\nexport interface SupplyParams {\n protocol: string;\n asset: Address;\n amount: bigint;\n on_behalf_of: Address;\n}\n\nexport interface BorrowParams {\n protocol: string;\n asset: Address;\n amount: bigint;\n interest_rate_mode: InterestRateMode;\n on_behalf_of: Address;\n}\n\n/** Interest rate mode (serde: snake_case) */\nexport enum InterestRateMode {\n Variable = \"variable\",\n Stable = \"stable\",\n}\n\nexport interface RepayParams {\n protocol: string;\n asset: Address;\n amount: bigint;\n interest_rate_mode: InterestRateMode;\n on_behalf_of: Address;\n}\n\nexport interface WithdrawParams {\n protocol: string;\n asset: Address;\n amount: bigint;\n to: Address;\n}\n\nexport interface LendingRates {\n protocol: string;\n asset: Address;\n supply_apy: number;\n borrow_variable_apy: number;\n borrow_stable_apy?: number;\n utilization: number;\n total_supply: bigint;\n total_borrow: bigint;\n /** Reward token addresses for supply-side incentives */\n supply_reward_tokens?: string[];\n /** Reward token addresses for borrow-side incentives */\n borrow_reward_tokens?: string[];\n /** Emissions per second per supply reward token (raw uint256 as string) */\n supply_emissions_per_second?: string[];\n /** Emissions per second per borrow reward token (raw uint256 as string) */\n borrow_emissions_per_second?: string[];\n /** Supply-side incentive APY (%) from reward token emissions */\n supply_incentive_apy?: number;\n /** Borrow-side incentive APY (%) from reward token emissions (negative = subsidized) */\n borrow_incentive_apy?: number;\n}\n\nexport interface UserPosition {\n protocol: string;\n user: Address;\n supplies: PositionAsset[];\n borrows: PositionAsset[];\n health_factor?: number;\n net_apy?: number;\n}\n\nexport interface PositionAsset {\n asset: Address;\n symbol: string;\n amount: bigint;\n value_usd?: number;\n}\n\n// === CDP Types ===\n\nexport interface OpenCdpParams {\n protocol: string;\n collateral: Address;\n collateral_amount: bigint;\n debt_amount: bigint;\n recipient: Address;\n}\n\nexport interface AdjustCdpParams {\n protocol: string;\n cdp_id: bigint;\n collateral_delta?: bigint;\n debt_delta?: bigint;\n add_collateral: boolean;\n add_debt: boolean;\n}\n\nexport interface CloseCdpParams {\n protocol: string;\n cdp_id: bigint;\n}\n\nexport interface CdpInfo {\n protocol: string;\n cdp_id: bigint;\n collateral: TokenAmount;\n debt: TokenAmount;\n collateral_ratio: number;\n liquidation_price?: number;\n}\n\n// === Liquid Staking Types ===\n\nexport interface StakeParams {\n protocol: string;\n amount: bigint;\n recipient: Address;\n}\n\nexport interface UnstakeParams {\n protocol: string;\n amount: bigint;\n recipient: Address;\n}\n\nexport interface StakingInfo {\n protocol: string;\n staked_token: Address;\n liquid_token: Address;\n exchange_rate: number;\n apy?: number;\n total_staked: bigint;\n}\n\n// === Vault Types (ERC-4626) ===\n\nexport interface VaultInfo {\n protocol: string;\n vault_address: Address;\n asset: Address;\n total_assets: bigint;\n total_supply: bigint;\n apy?: number;\n}\n\n// === Derivatives Types ===\n\nexport interface DerivativesPositionParams {\n protocol: string;\n market: string;\n size: bigint;\n collateral: bigint;\n is_long: boolean;\n}\n\n// === Options Types ===\n\nexport interface OptionParams {\n protocol: string;\n underlying: Address;\n strike_price: bigint;\n expiry: number;\n is_call: boolean;\n amount: bigint;\n}\n\n// === ve(3,3) Types ===\n\nexport interface RewardInfo {\n token: Address;\n symbol: string;\n amount: bigint;\n value_usd?: number;\n}\n\nexport interface GaugeInfo {\n gauge: Address;\n pool: Address;\n total_staked: bigint;\n reward_rate: bigint;\n rewards: RewardInfo[];\n}\n\nexport interface VeNftInfo {\n token_id: bigint;\n amount: bigint;\n unlock_time: number;\n voting_power: bigint;\n}\n\n// === Yield Types ===\n\nexport interface YieldInfo {\n protocol: string;\n pool: string;\n apy: number;\n tvl: bigint;\n tokens: Address[];\n}\n\n// === Portfolio Tracker Types ===\nexport interface PortfolioSnapshot {\n timestamp: number;\n chain: string;\n wallet: string;\n tokens: TokenBalance[];\n defi_positions: DefiPosition[];\n total_value_usd: number;\n}\n\nexport interface TokenBalance {\n token: string;\n symbol: string;\n balance: bigint;\n value_usd: number;\n price_usd: number;\n}\n\nexport interface DefiPosition {\n protocol: string;\n type: \"lending_supply\" | \"lending_borrow\" | \"lp\" | \"staking\" | \"vault\";\n asset: string;\n amount: bigint;\n value_usd: number;\n}\n\nexport interface PortfolioPnL {\n period: string;\n start_value_usd: number;\n end_value_usd: number;\n pnl_usd: number;\n pnl_pct: number;\n token_changes: TokenChange[];\n}\n\nexport interface TokenChange {\n symbol: string;\n balance_change: bigint;\n value_change_usd: number;\n}\n","import type { Address } from \"viem\";\n\nexport type DefiErrorCode =\n | \"PROTOCOL_NOT_FOUND\"\n | \"TOKEN_NOT_FOUND\"\n | \"CHAIN_NOT_FOUND\"\n | \"INSUFFICIENT_BALANCE\"\n | \"INSUFFICIENT_ALLOWANCE\"\n | \"SLIPPAGE_EXCEEDED\"\n | \"SIMULATION_FAILED\"\n | \"ABI_ERROR\"\n | \"REGISTRY_ERROR\"\n | \"RPC_ERROR\"\n | \"PROVIDER_ERROR\"\n | \"CONTRACT_ERROR\"\n | \"INVALID_PARAM\"\n | \"UNSUPPORTED\"\n | \"INTERNAL\";\n\nexport class DefiError extends Error {\n readonly code: DefiErrorCode;\n\n constructor(code: DefiErrorCode, message: string) {\n super(message);\n this.name = \"DefiError\";\n this.code = code;\n }\n\n static protocolNotFound(name: string): DefiError {\n return new DefiError(\"PROTOCOL_NOT_FOUND\", `Protocol not found: ${name}`);\n }\n\n static tokenNotFound(name: string): DefiError {\n return new DefiError(\"TOKEN_NOT_FOUND\", `Token not found: ${name}`);\n }\n\n static chainNotFound(name: string): DefiError {\n return new DefiError(\"CHAIN_NOT_FOUND\", `Chain not found: ${name}`);\n }\n\n static insufficientBalance(needed: string, available: string): DefiError {\n return new DefiError(\n \"INSUFFICIENT_BALANCE\",\n `Insufficient balance: need ${needed}, have ${available}`,\n );\n }\n\n static insufficientAllowance(spender: Address): DefiError {\n return new DefiError(\n \"INSUFFICIENT_ALLOWANCE\",\n `Insufficient allowance for spender ${spender}`,\n );\n }\n\n static slippageExceeded(expected: string, actual: string): DefiError {\n return new DefiError(\n \"SLIPPAGE_EXCEEDED\",\n `Slippage exceeded: expected ${expected}, got ${actual}`,\n );\n }\n\n static simulationFailed(reason: string): DefiError {\n return new DefiError(\n \"SIMULATION_FAILED\",\n `Transaction simulation failed: ${reason}`,\n );\n }\n\n static abiError(reason: string): DefiError {\n return new DefiError(\"ABI_ERROR\", `ABI encoding error: ${reason}`);\n }\n\n static registryError(reason: string): DefiError {\n return new DefiError(\"REGISTRY_ERROR\", `Registry error: ${reason}`);\n }\n\n static rpcError(reason: string): DefiError {\n return new DefiError(\"RPC_ERROR\", `RPC error: ${reason}`);\n }\n\n static providerError(reason: string): DefiError {\n return new DefiError(\"PROVIDER_ERROR\", `Provider error: ${reason}`);\n }\n\n static contractError(reason: string): DefiError {\n return new DefiError(\"CONTRACT_ERROR\", `Contract error: ${reason}`);\n }\n\n static invalidParam(reason: string): DefiError {\n return new DefiError(\"INVALID_PARAM\", `Invalid parameter: ${reason}`);\n }\n\n static unsupported(operation: string): DefiError {\n return new DefiError(\n \"UNSUPPORTED\",\n `Unsupported operation: ${operation}`,\n );\n }\n\n static internal(reason: string): DefiError {\n return new DefiError(\"INTERNAL\", `Internal error: ${reason}`);\n }\n\n toJSON() {\n return { error: this.message };\n }\n}\n\nexport type Result<T> = T;\n","/**\n * BigInt JSON serialization utilities.\n *\n * Rust's alloy U256 (backed by ruint) serializes to JSON as 0x-prefixed\n * lowercase hex strings (e.g., \"0x75bcd15\"). We must match this exactly\n * for behavioral parity.\n */\n\n/** JSON replacer for Rust parity — bigint becomes 0x-hex string */\nexport function jsonReplacer(_key: string, value: unknown): unknown {\n if (typeof value === \"bigint\") {\n return \"0x\" + value.toString(16);\n }\n return value;\n}\n\n/** JSON replacer for SDK consumers — bigint becomes decimal string */\nexport function jsonReplacerDecimal(_key: string, value: unknown): unknown {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n}\n\n/** Stringify with decimal bigint handling */\nexport function jsonStringify(data: unknown, pretty = true): string {\n return pretty\n ? JSON.stringify(data, jsonReplacerDecimal, 2)\n : JSON.stringify(data, jsonReplacerDecimal);\n}\n\n/** Parse a 0x-hex or decimal string to bigint */\nexport function parseBigInt(value: string): bigint {\n if (value.startsWith(\"0x\") || value.startsWith(\"0X\")) {\n return BigInt(value);\n }\n return BigInt(value);\n}\n","import type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, parseAbi } from \"viem\";\nimport type { DeFiTx } from \"./types.js\";\n\nconst erc20Abi = parseAbi([\n \"function name() view returns (string)\",\n \"function symbol() view returns (string)\",\n \"function decimals() view returns (uint8)\",\n \"function totalSupply() view returns (uint256)\",\n \"function balanceOf(address account) view returns (uint256)\",\n \"function transfer(address to, uint256 amount) returns (bool)\",\n \"function allowance(address owner, address spender) view returns (uint256)\",\n \"function approve(address spender, uint256 amount) returns (bool)\",\n \"function transferFrom(address from, address to, uint256 amount) returns (bool)\",\n]);\n\nexport { erc20Abi };\n\nexport function buildApprove(\n token: Address,\n spender: Address,\n amount: bigint,\n): DeFiTx {\n const data = encodeFunctionData({\n abi: erc20Abi,\n functionName: \"approve\",\n args: [spender, amount],\n });\n return {\n description: `Approve ${spender} to spend ${amount} of token ${token}`,\n to: token,\n data,\n value: 0n,\n gas_estimate: 60_000,\n };\n}\n\nexport function buildTransfer(\n token: Address,\n to: Address,\n amount: bigint,\n): DeFiTx {\n const data = encodeFunctionData({\n abi: erc20Abi,\n functionName: \"transfer\",\n args: [to, amount],\n });\n return {\n description: `Transfer ${amount} of token ${token} to ${to}`,\n to: token,\n data,\n value: 0n,\n gas_estimate: 65_000,\n };\n}\n","import { createPublicClient, http, type PublicClient } from \"viem\";\n\nconst providerCache = new Map<string, PublicClient>();\n\nexport function getProvider(rpcUrl: string): PublicClient {\n const cached = providerCache.get(rpcUrl);\n if (cached) return cached;\n\n const client = createPublicClient({ transport: http(rpcUrl) });\n providerCache.set(rpcUrl, client);\n return client;\n}\n\nexport function clearProviderCache(): void {\n providerCache.clear();\n}\n","import type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, decodeFunctionResult, parseAbi } from \"viem\";\nimport type { DeFiTx } from \"./types.js\";\nimport { getProvider } from \"./provider.js\";\n\nexport const MULTICALL3_ADDRESS: Address =\n \"0xcA11bde05977b3631167028862bE2a173976CA11\";\n\nconst multicall3Abi = parseAbi([\n \"struct Call3 { address target; bool allowFailure; bytes callData; }\",\n \"struct Result { bool success; bytes returnData; }\",\n \"function aggregate3(Call3[] calls) returns (Result[] returnData)\",\n]);\n\nexport function buildMulticall(calls: Array<[Address, Hex]>): DeFiTx {\n const mcCalls = calls.map(([target, callData]) => ({\n target,\n allowFailure: true,\n callData,\n }));\n\n const data = encodeFunctionData({\n abi: multicall3Abi,\n functionName: \"aggregate3\",\n args: [mcCalls],\n });\n\n return {\n description: `Multicall3 batch (${calls.length} calls)`,\n to: MULTICALL3_ADDRESS,\n data,\n value: 0n,\n };\n}\n\nexport async function multicallRead(\n rpcUrl: string,\n calls: Array<[Address, Hex]>,\n): Promise<(Hex | null)[]> {\n const client = getProvider(rpcUrl);\n\n const mcCalls = calls.map(([target, callData]) => ({\n target,\n allowFailure: true,\n callData,\n }));\n\n const result = await client.call({\n to: MULTICALL3_ADDRESS,\n data: encodeFunctionData({\n abi: multicall3Abi,\n functionName: \"aggregate3\",\n args: [mcCalls],\n }),\n });\n\n if (!result.data) return calls.map(() => null);\n\n const decoded = decodeFunctionResult({\n abi: multicall3Abi,\n functionName: \"aggregate3\",\n data: result.data,\n }) as Array<{ success: boolean; returnData: Hex }>;\n\n return decoded.map((r) => (r.success ? r.returnData : null));\n}\n\nexport function decodeU256(data: Hex | null): bigint {\n if (!data || data.length < 66) return 0n;\n return BigInt(data.slice(0, 66));\n}\n\nexport function decodeU128(data: Hex | null): bigint {\n if (!data || data.length < 66) return 0n;\n const val = BigInt(data.slice(0, 66));\n return val & ((1n << 128n) - 1n);\n}\n","export class ChainConfig {\n name!: string;\n chain_id!: number;\n rpc_url!: string;\n explorer_url?: string;\n native_token!: string;\n wrapped_native?: string;\n multicall3?: string;\n\n effectiveRpcUrl(): string {\n const chainEnv = this.name.toUpperCase().replace(/ /g, \"_\") + \"_RPC_URL\";\n return (\n process.env[chainEnv] ??\n process.env[\"HYPEREVM_RPC_URL\"] ??\n this.rpc_url\n );\n }\n}\n","import type { Address } from \"viem\";\n\nexport enum ProtocolCategory {\n Dex = \"dex\",\n Lending = \"lending\",\n Cdp = \"cdp\",\n Bridge = \"bridge\",\n LiquidStaking = \"liquid_staking\",\n YieldSource = \"yield_source\",\n YieldAggregator = \"yield_aggregator\",\n Vault = \"vault\",\n Derivatives = \"derivatives\",\n Options = \"options\",\n LiquidityManager = \"liquidity_manager\",\n Nft = \"nft\",\n Other = \"other\",\n}\n\nexport function protocolCategoryLabel(category: ProtocolCategory): string {\n switch (category) {\n case ProtocolCategory.Dex:\n return \"DEX\";\n case ProtocolCategory.Lending:\n return \"Lending\";\n case ProtocolCategory.Cdp:\n return \"CDP\";\n case ProtocolCategory.Bridge:\n return \"Bridge\";\n case ProtocolCategory.LiquidStaking:\n return \"Liquid Staking\";\n case ProtocolCategory.YieldSource:\n return \"Yield Source\";\n case ProtocolCategory.YieldAggregator:\n return \"Yield Aggregator\";\n case ProtocolCategory.Vault:\n return \"Vault\";\n case ProtocolCategory.Derivatives:\n return \"Derivatives\";\n case ProtocolCategory.Options:\n return \"Options\";\n case ProtocolCategory.LiquidityManager:\n return \"Liquidity Manager\";\n case ProtocolCategory.Nft:\n return \"NFT\";\n case ProtocolCategory.Other:\n return \"Other\";\n }\n}\n\nexport interface ProtocolEntry {\n name: string;\n slug: string;\n category: ProtocolCategory;\n interface: string;\n chain: string;\n native?: boolean;\n contracts?: Record<string, Address>;\n description?: string;\n}\n","import { readFileSync, readdirSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { parse } from \"smol-toml\";\nimport { ChainConfig } from \"./chain.js\";\nimport type { TokenEntry } from \"./token.js\";\nimport { type ProtocolEntry, ProtocolCategory } from \"./protocol.js\";\n\nimport { existsSync } from \"fs\";\n\nconst __dirname = fileURLToPath(new URL(\".\", import.meta.url));\n\n// Resolve config dir: works from src/ (vitest), dist/ (built), and npm bundle (npx)\nfunction findConfigDir(): string {\n const candidates = [\n resolve(__dirname, \"../../../config\"), // from dist/registry/ (monorepo build)\n resolve(__dirname, \"../../../../config\"), // from src/registry/ (vitest)\n resolve(__dirname, \"../config\"), // from dist/ (npm bundle — config at package root)\n resolve(__dirname, \"../../config\"), // from dist/subdir (npm bundle variant)\n ];\n for (const dir of candidates) {\n if (existsSync(resolve(dir, \"chains.toml\"))) return dir;\n }\n throw new Error(`Config directory not found. Searched: ${candidates.join(\", \")}`);\n}\n\nconst CONFIG_DIR = findConfigDir();\n\nfunction readToml(relPath: string): string {\n return readFileSync(resolve(CONFIG_DIR, relPath), \"utf-8\");\n}\n\ninterface ChainConfigWrapper {\n chain: Record<string, ChainConfig>;\n}\n\ninterface TokensWrapper {\n token: TokenEntry[];\n}\n\ninterface ProtocolWrapper {\n protocol: ProtocolEntry;\n}\n\nexport class Registry {\n chains: Map<string, ChainConfig>;\n tokens: Map<string, TokenEntry[]>;\n protocols: ProtocolEntry[];\n\n private constructor(\n chains: Map<string, ChainConfig>,\n tokens: Map<string, TokenEntry[]>,\n protocols: ProtocolEntry[],\n ) {\n this.chains = chains;\n this.tokens = tokens;\n this.protocols = protocols;\n }\n\n static loadEmbedded(): Registry {\n const chains = Registry.loadChains();\n const tokens = Registry.loadTokens();\n const protocols = Registry.loadProtocols();\n return new Registry(chains, tokens, protocols);\n }\n\n private static loadChains(): Map<string, ChainConfig> {\n const raw = parse(readToml(\"chains.toml\")) as unknown as ChainConfigWrapper;\n const map = new Map<string, ChainConfig>();\n for (const [key, data] of Object.entries(raw.chain)) {\n const cfg = Object.assign(new ChainConfig(), data);\n map.set(key, cfg);\n }\n return map;\n }\n\n private static loadTokens(): Map<string, TokenEntry[]> {\n // Dynamically discover all token files in config/tokens/\n const map = new Map<string, TokenEntry[]>();\n const tokensDir = resolve(CONFIG_DIR, \"tokens\");\n try {\n const files = readdirSync(tokensDir).filter(f => f.endsWith(\".toml\"));\n for (const file of files) {\n const chain = file.replace(\".toml\", \"\");\n try {\n const raw = parse(readToml(`tokens/${file}`)) as unknown as TokensWrapper;\n map.set(chain, raw.token);\n } catch { /* skip invalid token files */ }\n }\n } catch { /* tokens dir may not exist */ }\n return map;\n }\n\n private static loadProtocols(): ProtocolEntry[] {\n // Dynamically discover all protocol TOML files across all categories\n const protocols: ProtocolEntry[] = [];\n const protocolsDir = resolve(CONFIG_DIR, \"protocols\");\n const categories = [\"dex\", \"lending\", \"cdp\", \"vault\", \"liquid_staking\", \"yield_aggregator\", \"yield_source\", \"derivatives\", \"options\", \"nft\", \"bridge\"];\n\n for (const category of categories) {\n const catDir = resolve(protocolsDir, category);\n try {\n if (!existsSync(catDir)) continue;\n const files = readdirSync(catDir).filter(f => f.endsWith(\".toml\"));\n for (const file of files) {\n try {\n const raw = parse(readToml(`protocols/${category}/${file}`)) as unknown as ProtocolWrapper;\n protocols.push(raw.protocol);\n } catch { /* skip invalid protocol files */ }\n }\n } catch { /* category dir may not exist */ }\n }\n return protocols;\n }\n\n getChain(name: string): ChainConfig {\n const chain = this.chains.get(name);\n if (!chain) throw new Error(`Chain not found: ${name}`);\n return chain;\n }\n\n getProtocol(name: string): ProtocolEntry {\n const protocol = this.protocols.find(\n (p) =>\n p.name.toLowerCase() === name.toLowerCase() ||\n p.slug.toLowerCase() === name.toLowerCase(),\n );\n if (!protocol) throw new Error(`Protocol not found: ${name}`);\n return protocol;\n }\n\n getProtocolsByCategory(category: ProtocolCategory): ProtocolEntry[] {\n return this.protocols.filter((p) => p.category === category);\n }\n\n getProtocolsForChain(chain: string): ProtocolEntry[] {\n return this.protocols.filter(\n (p) => p.chain.toLowerCase() === chain.toLowerCase(),\n );\n }\n\n resolveToken(chain: string, symbol: string): TokenEntry {\n const tokens = this.tokens.get(chain);\n if (!tokens) throw new Error(`Chain not found: ${chain}`);\n const token = tokens.find(\n (t) => t.symbol.toLowerCase() === symbol.toLowerCase(),\n );\n if (!token) throw new Error(`Token not found: ${symbol}`);\n return token;\n }\n}\n","import { DefiError } from \"@hypurrquant/defi-core\";\nimport type { ProtocolEntry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\n\n// DEX adapters\nimport { UniswapV3Adapter } from \"./dex/uniswap_v3.js\";\nimport { UniswapV2Adapter } from \"./dex/uniswap_v2.js\";\nimport { AlgebraV3Adapter } from \"./dex/algebra_v3.js\";\nimport { BalancerV3Adapter } from \"./dex/balancer_v3.js\";\nimport { CurveStableSwapAdapter } from \"./dex/curve.js\";\nimport { SolidlyAdapter } from \"./dex/solidly.js\";\nimport { WooFiAdapter } from \"./dex/woofi.js\";\nimport { SolidlyGaugeAdapter } from \"./dex/solidly_gauge.js\";\nimport { MasterChefAdapter } from \"./dex/masterchef.js\";\n\n// Trait interfaces\nimport type { IDex } from \"@hypurrquant/defi-core\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport type { ICdp } from \"@hypurrquant/defi-core\";\nimport type { IVault } from \"@hypurrquant/defi-core\";\nimport type { ILiquidStaking } from \"@hypurrquant/defi-core\";\nimport type { IGaugeSystem } from \"@hypurrquant/defi-core\";\nimport type { IGauge } from \"@hypurrquant/defi-core\";\nimport type { IYieldSource } from \"@hypurrquant/defi-core\";\nimport type { IDerivatives } from \"@hypurrquant/defi-core\";\nimport type { IOptions } from \"@hypurrquant/defi-core\";\nimport type { IOracle } from \"@hypurrquant/defi-core\";\nimport type { INft } from \"@hypurrquant/defi-core\";\n\n// Lending adapters\nimport { AaveV3Adapter } from \"./lending/aave_v3.js\";\nimport { AaveV2Adapter } from \"./lending/aave_v2.js\";\nimport { AaveOracleAdapter } from \"./lending/aave_oracle.js\";\nimport { CompoundV2Adapter } from \"./lending/compound_v2.js\";\nimport { CompoundV3Adapter } from \"./lending/compound_v3.js\";\nimport { EulerV2Adapter } from \"./lending/euler_v2.js\";\nimport { MorphoBlueAdapter } from \"./lending/morpho.js\";\n\n// CDP adapters\nimport { FelixCdpAdapter } from \"./cdp/felix.js\";\nimport { FelixOracleAdapter } from \"./cdp/felix_oracle.js\";\n\n// Vault adapters\nimport { ERC4626VaultAdapter } from \"./vault/erc4626.js\";\n\n// Liquid staking adapters\nimport { GenericLstAdapter } from \"./liquid_staking/generic_lst.js\";\nimport { StHypeAdapter } from \"./liquid_staking/sthype.js\";\nimport { KinetiqAdapter } from \"./liquid_staking/kinetiq.js\";\n\n// Yield source adapters\nimport { PendleAdapter } from \"./yield_source/pendle.js\";\nimport { GenericYieldAdapter } from \"./yield_source/generic_yield.js\";\n\n// Derivatives adapters\nimport { HlpVaultAdapter } from \"./derivatives/hlp.js\";\nimport { GenericDerivativesAdapter } from \"./derivatives/generic_derivatives.js\";\n\n// Options adapters\nimport { RyskAdapter } from \"./options/rysk.js\";\nimport { GenericOptionsAdapter } from \"./options/generic_options.js\";\n\n// NFT adapters\nimport { ERC721Adapter } from \"./nft/erc721.js\";\n\n// ============================================================\n// DEX\n// ============================================================\n\n/** Create a Dex implementation from a protocol registry entry */\nexport function createDex(entry: ProtocolEntry, rpcUrl?: string): IDex {\n switch (entry.interface) {\n case \"uniswap_v3\":\n return new UniswapV3Adapter(entry, rpcUrl);\n case \"uniswap_v4\":\n throw DefiError.unsupported(\n `[${entry.name}] Uniswap V4 (singleton PoolManager) is not yet supported — use HyperSwap V3 or another V3-compatible DEX for quotes`,\n );\n case \"algebra_v3\":\n return new AlgebraV3Adapter(entry, rpcUrl);\n case \"uniswap_v2\":\n return new UniswapV2Adapter(entry, rpcUrl);\n case \"solidly_v2\":\n case \"solidly_cl\":\n return new SolidlyAdapter(entry, rpcUrl);\n case \"curve_stableswap\":\n return new CurveStableSwapAdapter(entry);\n case \"balancer_v3\":\n return new BalancerV3Adapter(entry);\n case \"woofi\":\n return new WooFiAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`DEX interface '${entry.interface}' not yet implemented`);\n }\n}\n\n// ============================================================\n// Lending\n// ============================================================\n\n/** Create a Lending implementation from a protocol registry entry */\nexport function createLending(entry: ProtocolEntry, rpcUrl?: string): ILending {\n switch (entry.interface) {\n case \"aave_v3\":\n case \"aave_v3_isolated\":\n return new AaveV3Adapter(entry, rpcUrl);\n case \"aave_v2\":\n return new AaveV2Adapter(entry, rpcUrl);\n case \"morpho_blue\":\n return new MorphoBlueAdapter(entry, rpcUrl);\n case \"euler_v2\":\n return new EulerV2Adapter(entry, rpcUrl);\n case \"compound_v2\":\n return new CompoundV2Adapter(entry, rpcUrl);\n case \"compound_v3\":\n return new CompoundV3Adapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Lending interface '${entry.interface}' not yet implemented`);\n }\n}\n\n// ============================================================\n// CDP\n// ============================================================\n\n/** Create a CDP implementation from a protocol registry entry */\nexport function createCdp(entry: ProtocolEntry, rpcUrl?: string): ICdp {\n switch (entry.interface) {\n case \"liquity_v2\":\n return new FelixCdpAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`CDP interface '${entry.interface}' not yet implemented`);\n }\n}\n\n// ============================================================\n// Vault\n// ============================================================\n\n/** Create a Vault implementation from a protocol registry entry */\nexport function createVault(entry: ProtocolEntry, rpcUrl?: string): IVault {\n switch (entry.interface) {\n case \"erc4626\":\n case \"beefy_vault\":\n return new ERC4626VaultAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Vault interface '${entry.interface}' not yet implemented`);\n }\n}\n\n// ============================================================\n// Liquid Staking\n// ============================================================\n\n/** Create a LiquidStaking implementation from a protocol registry entry */\nexport function createLiquidStaking(entry: ProtocolEntry, rpcUrl?: string): ILiquidStaking {\n switch (entry.interface) {\n case \"kinetiq_staking\":\n return new KinetiqAdapter(entry, rpcUrl);\n case \"sthype_staking\":\n return new StHypeAdapter(entry, rpcUrl);\n case \"hyperbeat_lst\":\n case \"kintsu\":\n return new GenericLstAdapter(entry, rpcUrl);\n default:\n return new GenericLstAdapter(entry, rpcUrl);\n }\n}\n\n// ============================================================\n// Gauge\n// ============================================================\n\n/** Create a GaugeSystem implementation from a protocol registry entry */\nexport function createGauge(entry: ProtocolEntry, rpcUrl?: string): IGaugeSystem {\n switch (entry.interface) {\n case \"solidly_v2\":\n case \"solidly_cl\":\n case \"algebra_v3\":\n case \"hybra\":\n return new SolidlyGaugeAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Gauge interface '${entry.interface}' not supported`);\n }\n}\n\n/** Create a MasterChef IGauge implementation from a protocol registry entry */\nexport function createMasterChef(entry: ProtocolEntry, rpcUrl?: string): IGauge {\n return new MasterChefAdapter(entry, rpcUrl);\n}\n\n// ============================================================\n// Yield Source (fallback to GenericYield)\n// ============================================================\n\n/** Create a YieldSource implementation — falls back to GenericYield for unknown interfaces */\nexport function createYieldSource(entry: ProtocolEntry, rpcUrl?: string): IYieldSource {\n switch (entry.interface) {\n case \"pendle_v2\":\n return new PendleAdapter(entry, rpcUrl);\n default:\n return new GenericYieldAdapter(entry, rpcUrl);\n }\n}\n\n// ============================================================\n// Derivatives (fallback to GenericDerivatives)\n// ============================================================\n\n/** Create a Derivatives implementation — falls back to GenericDerivatives for unknown interfaces */\nexport function createDerivatives(entry: ProtocolEntry, rpcUrl?: string): IDerivatives {\n switch (entry.interface) {\n case \"hlp_vault\":\n return new HlpVaultAdapter(entry, rpcUrl);\n default:\n return new GenericDerivativesAdapter(entry, rpcUrl);\n }\n}\n\n// ============================================================\n// Options (fallback to GenericOptions)\n// ============================================================\n\n/** Create an Options implementation — falls back to GenericOptions for unknown interfaces */\nexport function createOptions(entry: ProtocolEntry, rpcUrl?: string): IOptions {\n switch (entry.interface) {\n case \"rysk\":\n return new RyskAdapter(entry, rpcUrl);\n default:\n return new GenericOptionsAdapter(entry, rpcUrl);\n }\n}\n\n// ============================================================\n// NFT\n// ============================================================\n\n/** Create an NFT implementation from a protocol registry entry */\nexport function createNft(entry: ProtocolEntry, rpcUrl?: string): INft {\n switch (entry.interface) {\n case \"erc721\":\n return new ERC721Adapter(entry, rpcUrl);\n case \"marketplace\":\n throw DefiError.unsupported(`NFT marketplace '${entry.name}' is not queryable as ERC-721. Use a specific collection address.`);\n default:\n throw DefiError.unsupported(`NFT interface '${entry.interface}' not supported`);\n }\n}\n\n// ============================================================\n// Oracle from Lending\n// ============================================================\n\n/** Create an Oracle from a lending protocol entry (Aave V3 forks have an oracle contract) */\nexport function createOracleFromLending(entry: ProtocolEntry, rpcUrl: string): IOracle {\n switch (entry.interface) {\n case \"aave_v3\":\n case \"aave_v3_isolated\":\n return new AaveOracleAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Oracle not available for lending interface '${entry.interface}'`);\n }\n}\n\n// ============================================================\n// Oracle from CDP\n// ============================================================\n\n/** Create an Oracle from a CDP protocol entry (Felix has its own PriceFeed contract) */\nexport function createOracleFromCdp(entry: ProtocolEntry, _asset: Address, rpcUrl: string): IOracle {\n switch (entry.interface) {\n case \"liquity_v2\":\n return new FelixOracleAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Oracle not available for CDP interface '${entry.interface}'`);\n }\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http, decodeAbiParameters } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst DEFAULT_FEE = 3000;\n\nconst swapRouterAbi = parseAbi([\n \"struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; }\",\n \"function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut)\",\n]);\n\nconst quoterAbi = parseAbi([\n \"struct QuoteExactInputSingleParams { address tokenIn; address tokenOut; uint256 amountIn; uint24 fee; uint160 sqrtPriceLimitX96; }\",\n \"function quoteExactInputSingle(QuoteExactInputSingleParams memory params) external returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\",\n]);\n\n// Ramses CL uses tickSpacing instead of fee in the quoter struct\nconst ramsesQuoterAbi = parseAbi([\n \"struct QuoteExactInputSingleParams { address tokenIn; address tokenOut; uint256 amountIn; int24 tickSpacing; uint160 sqrtPriceLimitX96; }\",\n \"function quoteExactInputSingle(QuoteExactInputSingleParams memory params) external returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\",\n]);\n\nconst positionManagerAbi = parseAbi([\n \"struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; }\",\n \"function mint(MintParams calldata params) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)\",\n]);\n\nexport class UniswapV3Adapter implements IDex {\n private readonly protocolName: string;\n private readonly router: Address;\n private readonly quoter: Address | undefined;\n private readonly positionManager: Address | undefined;\n private readonly factory: Address | undefined;\n private readonly fee: number;\n private readonly rpcUrl: string | undefined;\n private readonly useTickSpacingQuoter: boolean;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n this.quoter = entry.contracts?.[\"quoter\"];\n this.positionManager = entry.contracts?.[\"position_manager\"];\n this.factory = entry.contracts?.[\"factory\"];\n this.fee = DEFAULT_FEE;\n this.rpcUrl = rpcUrl;\n // Ramses CL and similar forks use tickSpacing-based pool identification\n this.useTickSpacingQuoter = entry.contracts?.[\"pool_deployer\"] !== undefined\n || entry.contracts?.[\"gauge_factory\"] !== undefined;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n const amountOutMinimum = 0n;\n\n const data = encodeFunctionData({\n abi: swapRouterAbi,\n functionName: \"exactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n fee: this.fee,\n recipient: params.recipient,\n deadline,\n amountIn: params.amount_in,\n amountOutMinimum,\n sqrtPriceLimitX96: 0n,\n },\n ],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} tokenIn for tokenOut`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async quote(params: QuoteParams): Promise<QuoteResult> {\n if (!this.rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL configured\");\n }\n\n if (this.quoter) {\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n // Try tickSpacing-based quoter first for Ramses CL and similar forks\n if (this.useTickSpacingQuoter) {\n const tickSpacings = [1, 10, 50, 100, 200];\n const tsResults = await Promise.allSettled(\n tickSpacings.map(async (ts) => {\n const result = await client.call({\n to: this.quoter!,\n data: encodeFunctionData({\n abi: ramsesQuoterAbi,\n functionName: \"quoteExactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n amountIn: params.amount_in,\n tickSpacing: ts,\n sqrtPriceLimitX96: 0n,\n },\n ],\n }),\n });\n if (!result.data) return { amountOut: 0n, tickSpacing: ts };\n const [amountOut] = decodeAbiParameters(\n [{ name: \"amountOut\", type: \"uint256\" }],\n result.data,\n );\n return { amountOut, tickSpacing: ts };\n }),\n );\n\n let best = { amountOut: 0n, tickSpacing: 50 };\n for (const r of tsResults) {\n if (r.status === \"fulfilled\" && r.value.amountOut > best.amountOut) {\n best = r.value;\n }\n }\n\n if (best.amountOut > 0n) {\n return {\n protocol: this.protocolName,\n amount_out: best.amountOut,\n price_impact_bps: undefined,\n fee_bps: undefined,\n route: [`${params.token_in} -> ${params.token_out} (tickSpacing: ${best.tickSpacing})`],\n };\n }\n\n // tickSpacing-based protocol (Ramses CL): quoter returned no result.\n // Pool exists but has no liquidity in this fork snapshot.\n throw DefiError.rpcError(\n `[${this.protocolName}] No quote available — pool exists but has zero liquidity for this pair`,\n );\n }\n\n // Standard Uniswap V3 fee-based quoter\n const feeTiers = [500, 3000, 10000, 100];\n const results = await Promise.allSettled(\n feeTiers.map(async (fee) => {\n const result = await client.call({\n to: this.quoter!,\n data: encodeFunctionData({\n abi: quoterAbi,\n functionName: \"quoteExactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n amountIn: params.amount_in,\n fee,\n sqrtPriceLimitX96: 0n,\n },\n ],\n }),\n });\n if (!result.data) return { amountOut: 0n, fee };\n const [amountOut] = decodeAbiParameters(\n [{ name: \"amountOut\", type: \"uint256\" }],\n result.data,\n );\n return { amountOut, fee };\n }),\n );\n\n let best = { amountOut: 0n, fee: 3000 };\n for (const r of results) {\n if (r.status === \"fulfilled\" && r.value.amountOut > best.amountOut) {\n best = r.value;\n }\n }\n\n if (best.amountOut > 0n) {\n return {\n protocol: this.protocolName,\n amount_out: best.amountOut,\n price_impact_bps: undefined,\n fee_bps: Math.floor(best.fee / 10),\n route: [`${params.token_in} -> ${params.token_out} (fee: ${best.fee})`],\n };\n }\n }\n\n // Fallback: simulate swap via eth_call on the router\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const callData = encodeFunctionData({\n abi: swapRouterAbi,\n functionName: \"exactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n fee: this.fee,\n recipient: \"0x0000000000000000000000000000000000000001\",\n deadline: BigInt(\"18446744073709551615\"),\n amountIn: params.amount_in,\n amountOutMinimum: 0n,\n sqrtPriceLimitX96: 0n,\n },\n ],\n });\n\n let output: `0x${string}` | undefined;\n try {\n const result = await client.call({ to: this.router, data: callData });\n output = result.data;\n } catch (e: unknown) {\n const errMsg = String(e);\n if (errMsg.includes(\"STF\") || errMsg.includes(\"insufficient\")) {\n throw DefiError.unsupported(\n `[${this.protocolName}] quote unavailable — no quoter contract configured. Swap simulation requires token balance. Add a quoter address to the protocol config.`,\n );\n }\n throw DefiError.rpcError(`[${this.protocolName}] swap simulation for quote failed: ${errMsg}`);\n }\n\n const amountOut =\n output && output.length >= 66\n ? BigInt(output.slice(0, 66))\n : 0n;\n\n return {\n protocol: this.protocolName,\n amount_out: amountOut,\n price_impact_bps: undefined,\n fee_bps: Math.floor(this.fee / 10),\n route: [`${params.token_in} -> ${params.token_out} (simulated)`],\n };\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n const pm = this.positionManager;\n if (!pm) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Position manager address not configured\");\n }\n\n // Sort tokens (Uniswap V3 requires token0 < token1)\n const [token0, token1, rawAmount0, rawAmount1] =\n params.token_a.toLowerCase() < params.token_b.toLowerCase()\n ? [params.token_a, params.token_b, params.amount_a, params.amount_b]\n : [params.token_b, params.token_a, params.amount_b, params.amount_a];\n\n // V3 NPM mint: getLiquidityForAmounts uses min(L0, L1), so if either is 0\n // then liquidity=0 → revert. Use 1 wei minimum for single-side LP.\n const amount0 = rawAmount0 === 0n && rawAmount1 > 0n ? 1n : rawAmount0;\n const amount1 = rawAmount1 === 0n && rawAmount0 > 0n ? 1n : rawAmount1;\n\n const data = encodeFunctionData({\n abi: positionManagerAbi,\n functionName: \"mint\",\n args: [\n {\n token0,\n token1,\n fee: this.fee,\n tickLower: -887220,\n tickUpper: 887220,\n amount0Desired: amount0,\n amount1Desired: amount1,\n amount0Min: 0n,\n amount1Min: 0n,\n recipient: params.recipient,\n deadline: BigInt(\"18446744073709551615\"),\n },\n ],\n });\n\n return {\n description: `[${this.protocolName}] Add liquidity`,\n to: pm,\n data,\n value: 0n,\n gas_estimate: 500_000,\n };\n }\n\n async buildRemoveLiquidity(_params: RemoveLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] remove_liquidity requires tokenId — use NFT position manager directly`,\n );\n }\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http, decodeFunctionResult, decodeAbiParameters } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts)\",\n \"function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB, uint256 liquidity)\",\n \"function removeLiquidity(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB)\",\n \"function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts)\",\n]);\n\nconst lbQuoterAbi = parseAbi([\n \"function findBestPathFromAmountIn(address[] calldata route, uint128 amountIn) external view returns ((address[] route, address[] pairs, uint256[] binSteps, uint256[] versions, uint128[] amounts, uint128[] virtualAmountsWithoutSlippage, uint128[] fees))\",\n]);\n\nexport class UniswapV2Adapter implements IDex {\n private readonly protocolName: string;\n private readonly router: Address;\n private readonly rpcUrl: string | undefined;\n private readonly lbQuoter: Address | undefined;\n private readonly lbIntermediaries: Address[];\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n this.lbQuoter = entry.contracts?.[\"lb_quoter\"];\n this.rpcUrl = rpcUrl;\n\n // Collect LB intermediary tokens from contracts with \"lb_mid_\" prefix\n this.lbIntermediaries = [];\n if (entry.contracts) {\n for (const [key, addr] of Object.entries(entry.contracts)) {\n if (key.startsWith(\"lb_mid_\")) {\n this.lbIntermediaries.push(addr);\n }\n }\n }\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const amountOutMin = 0n;\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n const path: Address[] = [params.token_in, params.token_out];\n\n const data = encodeFunctionData({\n abi,\n functionName: \"swapExactTokensForTokens\",\n args: [params.amount_in, amountOutMin, path, params.recipient, deadline],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} tokens via V2`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 150_000,\n };\n }\n\n async quote(params: QuoteParams): Promise<QuoteResult> {\n if (!this.rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL configured\");\n }\n\n // Try LB (Liquidity Book) quote first if lb_quoter is configured\n if (this.lbQuoter) {\n try {\n return await this.lbQuote(params);\n } catch {\n // Fall through to V2 quote\n }\n }\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const path: Address[] = [params.token_in, params.token_out];\n\n const result = await client.call({\n to: this.router,\n data: encodeFunctionData({\n abi,\n functionName: \"getAmountsOut\",\n args: [params.amount_in, path],\n }),\n });\n\n if (!result.data) {\n throw DefiError.rpcError(`[${this.protocolName}] getAmountsOut returned no data`);\n }\n\n const decoded = decodeFunctionResult({\n abi,\n functionName: \"getAmountsOut\",\n data: result.data,\n }) as unknown as bigint[];\n\n const amountOut = decoded[decoded.length - 1];\n\n return {\n protocol: this.protocolName,\n amount_out: amountOut,\n price_impact_bps: undefined,\n fee_bps: 30,\n route: [`${params.token_in} -> ${params.token_out}`],\n };\n }\n\n private async lbQuote(params: QuoteParams): Promise<QuoteResult> {\n const client = createPublicClient({ transport: http(this.rpcUrl!) });\n\n // Build candidate routes: direct + multi-hop through each intermediary\n const routes: Address[][] = [[params.token_in, params.token_out]];\n const tokenInLower = params.token_in.toLowerCase();\n const tokenOutLower = params.token_out.toLowerCase();\n for (const mid of this.lbIntermediaries) {\n if (mid.toLowerCase() !== tokenInLower && mid.toLowerCase() !== tokenOutLower) {\n routes.push([params.token_in, mid, params.token_out]);\n }\n }\n\n const lbResultParams = [\n {\n type: \"tuple\" as const,\n components: [\n { name: \"route\", type: \"address[]\" as const },\n { name: \"pairs\", type: \"address[]\" as const },\n { name: \"binSteps\", type: \"uint256[]\" as const },\n { name: \"versions\", type: \"uint256[]\" as const },\n { name: \"amounts\", type: \"uint128[]\" as const },\n { name: \"virtualAmountsWithoutSlippage\", type: \"uint128[]\" as const },\n { name: \"fees\", type: \"uint128[]\" as const },\n ],\n },\n ] as const;\n\n let bestOut = 0n;\n let bestRoute: Address[] = [];\n\n const results = await Promise.allSettled(\n routes.map(async (route) => {\n const result = await client.call({\n to: this.lbQuoter!,\n data: encodeFunctionData({\n abi: lbQuoterAbi,\n functionName: \"findBestPathFromAmountIn\",\n args: [route, params.amount_in],\n }),\n });\n if (!result.data) return { amountOut: 0n, route };\n const [quote] = decodeAbiParameters(lbResultParams, result.data);\n const amounts = quote.amounts;\n return { amountOut: amounts[amounts.length - 1], route };\n }),\n );\n\n for (const r of results) {\n if (r.status === \"fulfilled\" && r.value.amountOut > bestOut) {\n bestOut = r.value.amountOut;\n bestRoute = r.value.route;\n }\n }\n\n if (bestOut === 0n) {\n throw DefiError.rpcError(`[${this.protocolName}] LB quote returned zero for all routes`);\n }\n\n return {\n protocol: this.protocolName,\n amount_out: bestOut,\n price_impact_bps: undefined,\n fee_bps: undefined,\n route: [bestRoute.map((a) => a.slice(0, 10)).join(\" -> \") + \" (LB)\"],\n };\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi,\n functionName: \"addLiquidity\",\n args: [\n params.token_a,\n params.token_b,\n params.amount_a,\n params.amount_b,\n 0n,\n 0n,\n params.recipient,\n BigInt(\"18446744073709551615\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Add liquidity V2`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildRemoveLiquidity(params: RemoveLiquidityParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi,\n functionName: \"removeLiquidity\",\n args: [\n params.token_a,\n params.token_b,\n params.liquidity,\n 0n,\n 0n,\n params.recipient,\n BigInt(\"18446744073709551615\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Remove liquidity V2`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http, decodeAbiParameters, concatHex, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"struct ExactInputSingleParams { address tokenIn; address tokenOut; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 limitSqrtPrice; }\",\n \"function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut)\",\n]);\n\n// Algebra Integral quoter: path = tokenIn(20) + deployer(20) + tokenOut(20) per hop\n// Returns arrays for multi-hop results\nconst algebraQuoterAbi = parseAbi([\n \"function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256[] memory amountOutList, uint256[] memory amountInList, uint160[] memory sqrtPriceX96AfterList, uint32[] memory initializedTicksCrossedList, uint256 gasEstimate, uint16[] memory feeList)\",\n]);\n\n// Algebra V2 / NEST-style quoter: single-hop struct\n// selector: 0x5e5e6e0f quoteExactInputSingle((address,address,uint256,uint160))\n// returns: (uint256 amountOut, uint256 amountIn, uint160 sqrtPriceX96After)\nconst algebraSingleQuoterAbi = parseAbi([\n \"function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint160 limitSqrtPrice) params) external returns (uint256 amountOut, uint256 amountIn, uint160 sqrtPriceX96After)\",\n]);\n\n// Algebra NonfungiblePositionManager (no fee field, uses plugin instead)\nconst algebraPositionManagerAbi = parseAbi([\n \"struct MintParams { address token0; address token1; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; }\",\n \"function mint(MintParams calldata params) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)\",\n]);\n\nexport class AlgebraV3Adapter implements IDex {\n private readonly protocolName: string;\n private readonly router: Address;\n private readonly quoter: Address | undefined;\n private readonly positionManager: Address | undefined;\n private readonly rpcUrl: string | undefined;\n // NEST and similar forks expose quoteExactInputSingle((address,address,uint256,uint160))\n // instead of path-based quoteExactInput. Detected by presence of pool_deployer in config.\n private readonly useSingleQuoter: boolean;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n this.quoter = entry.contracts?.[\"quoter\"];\n this.positionManager = entry.contracts?.[\"position_manager\"];\n this.rpcUrl = rpcUrl;\n // pool_deployer present → NEST-style single-hop struct quoter\n this.useSingleQuoter = entry.contracts?.[\"pool_deployer\"] !== undefined;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n const amountOutMinimum = 0n;\n\n const data = encodeFunctionData({\n abi,\n functionName: \"exactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n recipient: params.recipient,\n deadline,\n amountIn: params.amount_in,\n amountOutMinimum,\n limitSqrtPrice: 0n,\n },\n ],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} tokenIn for tokenOut`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async quote(params: QuoteParams): Promise<QuoteResult> {\n if (!this.rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL configured\");\n }\n if (!this.quoter) {\n throw DefiError.unsupported(\n `[${this.protocolName}] No quoter contract configured`,\n );\n }\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n // NEST and similar forks: use single-hop struct quoter\n if (this.useSingleQuoter) {\n const result = await client.call({\n to: this.quoter,\n data: encodeFunctionData({\n abi: algebraSingleQuoterAbi,\n functionName: \"quoteExactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n amountIn: params.amount_in,\n limitSqrtPrice: 0n,\n },\n ],\n }),\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] quoteExactInputSingle failed: ${e}`);\n });\n\n if (!result.data || result.data.length < 66) {\n throw DefiError.rpcError(`[${this.protocolName}] quoter returned empty data`);\n }\n\n const [amountOut] = decodeAbiParameters(\n [\n { name: \"amountOut\", type: \"uint256\" },\n { name: \"amountIn\", type: \"uint256\" },\n { name: \"sqrtPriceX96After\", type: \"uint160\" },\n ],\n result.data,\n );\n\n return {\n protocol: this.protocolName,\n amount_out: amountOut as bigint,\n price_impact_bps: undefined,\n fee_bps: undefined,\n route: [`${params.token_in} -> ${params.token_out}`],\n };\n }\n\n // KittenSwap and standard Algebra Integral path: tokenIn(20) + deployer(20) + tokenOut(20) = 60 bytes\n // Standard pools use deployer=address(0) in path (CREATE2 salt without deployer prefix)\n const path = concatHex([params.token_in, zeroAddress as Address, params.token_out]);\n\n const result = await client.call({\n to: this.quoter,\n data: encodeFunctionData({\n abi: algebraQuoterAbi,\n functionName: \"quoteExactInput\",\n args: [path, params.amount_in],\n }),\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] quoteExactInput failed: ${e}`);\n });\n\n if (!result.data || result.data.length < 66) {\n throw DefiError.rpcError(`[${this.protocolName}] quoter returned empty data`);\n }\n\n // Decode first element: amountOutList is an array, take the last element\n const decoded = decodeAbiParameters(\n [\n { name: \"amountOutList\", type: \"uint256[]\" },\n { name: \"amountInList\", type: \"uint256[]\" },\n { name: \"sqrtPriceX96AfterList\", type: \"uint160[]\" },\n { name: \"initializedTicksCrossedList\", type: \"uint32[]\" },\n { name: \"gasEstimate\", type: \"uint256\" },\n { name: \"feeList\", type: \"uint16[]\" },\n ],\n result.data,\n );\n\n const amountOutList = decoded[0] as readonly bigint[];\n const feeList = decoded[5] as readonly number[];\n const amountOut = amountOutList[amountOutList.length - 1];\n const fee = feeList.length > 0 ? feeList[0] : undefined;\n\n return {\n protocol: this.protocolName,\n amount_out: amountOut,\n price_impact_bps: undefined,\n fee_bps: fee !== undefined ? Math.floor(fee / 10) : undefined,\n route: [`${params.token_in} -> ${params.token_out}`],\n };\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n const pm = this.positionManager;\n if (!pm) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Position manager address not configured\");\n }\n\n // Sort tokens (Algebra requires token0 < token1)\n const [token0, token1, rawAmount0, rawAmount1] =\n params.token_a.toLowerCase() < params.token_b.toLowerCase()\n ? [params.token_a, params.token_b, params.amount_a, params.amount_b]\n : [params.token_b, params.token_a, params.amount_b, params.amount_a];\n\n // Prevent liquidity=0 revert for single-side LP (same as V3)\n const amount0 = rawAmount0 === 0n && rawAmount1 > 0n ? 1n : rawAmount0;\n const amount1 = rawAmount1 === 0n && rawAmount0 > 0n ? 1n : rawAmount1;\n\n const data = encodeFunctionData({\n abi: algebraPositionManagerAbi,\n functionName: \"mint\",\n args: [\n {\n token0,\n token1,\n tickLower: -887220,\n tickUpper: 887220,\n amount0Desired: amount0,\n amount1Desired: amount1,\n amount0Min: 0n,\n amount1Min: 0n,\n recipient: params.recipient,\n deadline: BigInt(\"18446744073709551615\"),\n },\n ],\n });\n\n return {\n description: `[${this.protocolName}] Add liquidity`,\n to: pm,\n data,\n value: 0n,\n gas_estimate: 500_000,\n };\n }\n\n async buildRemoveLiquidity(_params: RemoveLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] remove_liquidity requires tokenId — use NFT position manager directly`,\n );\n }\n}\n","import { encodeFunctionData, parseAbi, zeroAddress } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"function swapSingleTokenExactIn(address pool, address tokenIn, address tokenOut, uint256 exactAmountIn, uint256 minAmountOut, uint256 deadline, bool wethIsEth, bytes calldata userData) external returns (uint256 amountOut)\",\n]);\n\nexport class BalancerV3Adapter implements IDex {\n private readonly protocolName: string;\n private readonly router: `0x${string}`;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract\");\n }\n this.router = router;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const minAmountOut = 0n;\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n\n // Balancer V3 requires a pool address. For now use a simplified single-pool swap.\n // In production, the pool would be resolved from the registry or an on-chain query.\n const data = encodeFunctionData({\n abi,\n functionName: \"swapSingleTokenExactIn\",\n args: [\n zeroAddress, // TODO: resolve pool from registry\n params.token_in,\n params.token_out,\n params.amount_in,\n minAmountOut,\n deadline,\n false,\n \"0x\",\n ],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} via Balancer V3`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async quote(_params: QuoteParams): Promise<QuoteResult> {\n throw DefiError.unsupported(`[${this.protocolName}] quote requires RPC`);\n }\n\n async buildAddLiquidity(_params: AddLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] add_liquidity requires pool-specific params`);\n }\n\n async buildRemoveLiquidity(_params: RemoveLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] remove_liquidity requires pool-specific params`);\n }\n}\n","import { encodeFunctionData, parseAbi } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst poolAbi = parseAbi([\n \"function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256)\",\n \"function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256)\",\n \"function add_liquidity(uint256[2] amounts, uint256 min_mint_amount) external returns (uint256)\",\n \"function remove_liquidity(uint256 amount, uint256[2] min_amounts) external returns (uint256[2])\",\n]);\n\nexport class CurveStableSwapAdapter implements IDex {\n private readonly protocolName: string;\n private readonly router: `0x${string}`;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n // Direct pool exchange: swap token at index 0 for token at index 1.\n // The `router` address is treated as the pool address for direct swaps.\n // Callers should set the pool address as the \"router\" contract in the registry\n // when targeting a specific Curve pool.\n // Without prior quote, set min output to 0. Use quote() first for slippage protection.\n const minDy = 0n;\n\n const data = encodeFunctionData({\n abi: poolAbi,\n functionName: \"exchange\",\n args: [0n, 1n, params.amount_in, minDy],\n });\n\n return {\n description: `[${this.protocolName}] Curve pool exchange ${params.amount_in} tokens (index 0 -> 1)`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async quote(_params: QuoteParams): Promise<QuoteResult> {\n throw DefiError.unsupported(`[${this.protocolName}] quote requires RPC connection`);\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n // Add liquidity to a 2-token Curve pool\n const data = encodeFunctionData({\n abi: poolAbi,\n functionName: \"add_liquidity\",\n args: [[params.amount_a, params.amount_b], 0n],\n });\n\n return {\n description: `[${this.protocolName}] Curve add liquidity`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 400_000,\n };\n }\n\n async buildRemoveLiquidity(params: RemoveLiquidityParams): Promise<DeFiTx> {\n // Remove liquidity from a 2-token Curve pool\n const data = encodeFunctionData({\n abi: poolAbi,\n functionName: \"remove_liquidity\",\n args: [params.liquidity, [0n, 0n]],\n });\n\n return {\n description: `[${this.protocolName}] Curve remove liquidity`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http, decodeAbiParameters } from \"viem\";\nimport type { Address, PublicClient } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"struct Route { address from; address to; bool stable; }\",\n \"function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, (address from, address to, bool stable)[] calldata routes, address to, uint256 deadline) external returns (uint256[] memory amounts)\",\n \"function getAmountsOut(uint256 amountIn, (address from, address to, bool stable)[] calldata routes) external view returns (uint256[] memory amounts)\",\n \"function addLiquidity(address tokenA, address tokenB, bool stable, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB, uint256 liquidity)\",\n \"function removeLiquidity(address tokenA, address tokenB, bool stable, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB)\",\n]);\n\n// Velodrome V2 / Aerodrome style: Route includes factory address\nconst abiV2 = parseAbi([\n \"function getAmountsOut(uint256 amountIn, (address from, address to, bool stable, address factory)[] calldata routes) external view returns (uint256[] memory amounts)\",\n]);\n\nexport class SolidlyAdapter implements IDex {\n private readonly protocolName: string;\n private readonly router: `0x${string}`;\n /** Default to volatile (false). True for stablecoin pairs. */\n private readonly defaultStable: boolean;\n private readonly rpcUrl: string | undefined;\n /** Factory address — present on Velodrome V2 / Aerodrome forks */\n private readonly factory: Address | undefined;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n this.defaultStable = false;\n this.rpcUrl = rpcUrl;\n this.factory = entry.contracts?.[\"factory\"];\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const amountOutMin = 0n;\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n\n const routes = [\n { from: params.token_in, to: params.token_out, stable: this.defaultStable },\n ];\n\n const data = encodeFunctionData({\n abi,\n functionName: \"swapExactTokensForTokens\",\n args: [params.amount_in, amountOutMin, routes, params.recipient, deadline],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} tokens via Solidly`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n private async callGetAmountsOut(\n client: PublicClient,\n callData: `0x${string}`,\n ): Promise<bigint> {\n const result = await client.call({ to: this.router, data: callData });\n if (!result.data) return 0n;\n const [amounts] = decodeAbiParameters(\n [{ name: \"amounts\", type: \"uint256[]\" }],\n result.data,\n );\n return amounts.length >= 2 ? amounts[amounts.length - 1] : 0n;\n }\n\n private encodeV1(params: QuoteParams, stable: boolean): `0x${string}` {\n return encodeFunctionData({\n abi,\n functionName: \"getAmountsOut\",\n args: [params.amount_in, [{ from: params.token_in, to: params.token_out, stable }]],\n });\n }\n\n private encodeV2(params: QuoteParams, stable: boolean): `0x${string}` {\n return encodeFunctionData({\n abi: abiV2,\n functionName: \"getAmountsOut\",\n args: [params.amount_in, [{ from: params.token_in, to: params.token_out, stable, factory: this.factory! }]],\n });\n }\n\n async quote(params: QuoteParams): Promise<QuoteResult> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n // Try all combinations: [volatile, stable] x [V1 ABI, V2 ABI (if factory present)]\n // Pick the best (highest amountOut)\n const candidates: Array<{ callData: `0x${string}`; stable: boolean }> = [\n { callData: this.encodeV1(params, false), stable: false },\n { callData: this.encodeV1(params, true), stable: true },\n ];\n if (this.factory) {\n candidates.unshift(\n { callData: this.encodeV2(params, false), stable: false },\n { callData: this.encodeV2(params, true), stable: true },\n );\n }\n\n const results = await Promise.allSettled(\n candidates.map((c) => this.callGetAmountsOut(client, c.callData)),\n );\n\n let bestOut = 0n;\n let bestStable = false;\n for (let i = 0; i < results.length; i++) {\n const r = results[i];\n if (r.status === \"fulfilled\" && r.value > bestOut) {\n bestOut = r.value;\n bestStable = candidates[i].stable;\n }\n }\n\n if (bestOut === 0n) {\n throw DefiError.rpcError(`[${this.protocolName}] getAmountsOut returned zero for all routes`);\n }\n\n return {\n protocol: this.protocolName,\n amount_out: bestOut,\n price_impact_bps: undefined,\n fee_bps: bestStable ? 4 : 20,\n route: [`${params.token_in} -> ${params.token_out} (stable: ${bestStable})`],\n };\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi,\n functionName: \"addLiquidity\",\n args: [\n params.token_a,\n params.token_b,\n this.defaultStable,\n params.amount_a,\n params.amount_b,\n 0n,\n 0n,\n params.recipient,\n BigInt(\"18446744073709551615\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Add liquidity (Solidly)`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRemoveLiquidity(params: RemoveLiquidityParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi,\n functionName: \"removeLiquidity\",\n args: [\n params.token_a,\n params.token_b,\n this.defaultStable,\n params.liquidity,\n 0n,\n 0n,\n params.recipient,\n BigInt(\"18446744073709551615\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Remove liquidity (Solidly)`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n}\n","import { encodeFunctionData, parseAbi, zeroAddress } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"function swap(address fromToken, address toToken, uint256 fromAmount, uint256 minToAmount, address to, address rebateTo) external payable returns (uint256 realToAmount)\",\n]);\n\nexport class WooFiAdapter implements IDex {\n private readonly protocolName: string;\n private readonly router: `0x${string}`;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract\");\n }\n this.router = router;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const minToAmount = 0n;\n\n const data = encodeFunctionData({\n abi,\n functionName: \"swap\",\n args: [\n params.token_in,\n params.token_out,\n params.amount_in,\n minToAmount,\n params.recipient,\n zeroAddress,\n ],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} via WOOFi`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async quote(_params: QuoteParams): Promise<QuoteResult> {\n throw DefiError.unsupported(`[${this.protocolName}] quote requires RPC`);\n }\n\n async buildAddLiquidity(_params: AddLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] WOOFi does not support LP positions via router`);\n }\n\n async buildRemoveLiquidity(_params: RemoveLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] WOOFi does not support LP positions via router`);\n }\n}\n","import { createPublicClient, encodeFunctionData, http, parseAbi, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IGaugeSystem,\n ProtocolEntry,\n RewardInfo,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst gaugeAbi = parseAbi([\n \"function deposit(uint256 amount) external\",\n \"function depositFor(uint256 amount, uint256 tokenId) external\",\n \"function withdraw(uint256 amount) external\",\n \"function getReward(address account) external\",\n \"function getReward(address account, address[] tokens) external\",\n \"function earned(address account) external view returns (uint256)\",\n \"function earned(address token, address account) external view returns (uint256)\",\n \"function rewardRate() external view returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function rewardsListLength() external view returns (uint256)\",\n \"function isReward(address token) external view returns (bool)\",\n]);\n\nconst veAbi = parseAbi([\n \"function create_lock(uint256 value, uint256 lock_duration) external returns (uint256)\",\n \"function increase_amount(uint256 tokenId, uint256 value) external\",\n \"function increase_unlock_time(uint256 tokenId, uint256 lock_duration) external\",\n \"function withdraw(uint256 tokenId) external\",\n \"function balanceOfNFT(uint256 tokenId) external view returns (uint256)\",\n \"function locked(uint256 tokenId) external view returns (uint256 amount, uint256 end)\",\n]);\n\nconst voterAbi = parseAbi([\n \"function vote(uint256 tokenId, address[] calldata pools, uint256[] calldata weights) external\",\n \"function claimBribes(address[] calldata bribes, address[][] calldata tokens, uint256 tokenId) external\",\n \"function claimFees(address[] calldata fees, address[][] calldata tokens, uint256 tokenId) external\",\n \"function gauges(address pool) external view returns (address)\",\n]);\n\nexport class SolidlyGaugeAdapter implements IGaugeSystem {\n private readonly protocolName: string;\n private readonly voter: Address;\n private readonly veToken: Address;\n private readonly rpcUrl: string | undefined;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const voter = entry.contracts?.[\"voter\"];\n if (!voter) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'voter' contract\");\n }\n const veToken = entry.contracts?.[\"ve_token\"];\n if (!veToken) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 've_token' contract\");\n }\n this.voter = voter;\n this.veToken = veToken;\n this.rpcUrl = rpcUrl;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n // IGauge\n\n async buildDeposit(gauge: Address, amount: bigint, tokenId?: bigint): Promise<DeFiTx> {\n if (tokenId !== undefined) {\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"depositFor\",\n args: [amount, tokenId],\n });\n return {\n description: `[${this.protocolName}] Deposit ${amount} LP to gauge (boost veNFT #${tokenId})`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"deposit\",\n args: [amount],\n });\n return {\n description: `[${this.protocolName}] Deposit ${amount} LP to gauge`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async buildWithdraw(gauge: Address, amount: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"withdraw\",\n args: [amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${amount} LP from gauge`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async buildClaimRewards(gauge: Address, account?: Address): Promise<DeFiTx> {\n // Ramses V2 gauges use getReward(address account, address[] tokens)\n // where account must equal msg.sender. Try to discover reward tokens via RPC.\n if (account && this.rpcUrl) {\n try {\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const listLen = await client.readContract({\n address: gauge,\n abi: gaugeAbi,\n functionName: \"rewardsListLength\",\n }) as bigint;\n if (listLen > 0n) {\n // Discover reward tokens by checking isReward against known tokens\n // For Ramses V2, use the voter to find reward tokens\n // Alternatively, scan storage: the gauge exposes earned(token, account)\n // We'll pass empty tokens array and let the gauge figure it out,\n // or pass a placeholder. Since we know RAM is the reward token\n // from the gauge context, we need to enumerate them.\n // Fallback: use getReward(account, []) — some implementations accept empty array\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"getReward\",\n args: [account, [] as Address[]],\n });\n return {\n description: `[${this.protocolName}] Claim gauge rewards`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n } catch {\n // fall through to default\n }\n }\n\n // Standard Solidly V2 gauge: getReward(address account)\n // account param will be overridden by msg.sender in most gauge implementations\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"getReward\",\n args: [account ?? zeroAddress],\n });\n return {\n description: `[${this.protocolName}] Claim gauge rewards`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async getPendingRewards(_gauge: Address, _user: Address): Promise<RewardInfo[]> {\n throw DefiError.unsupported(`[${this.protocolName}] get_pending_rewards requires RPC`);\n }\n\n // IVoteEscrow\n\n async buildCreateLock(amount: bigint, lockDuration: number): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: veAbi,\n functionName: \"create_lock\",\n args: [amount, BigInt(lockDuration)],\n });\n return {\n description: `[${this.protocolName}] Create veNFT lock: ${amount} tokens for ${lockDuration}s`,\n to: this.veToken,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildIncreaseAmount(tokenId: bigint, amount: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: veAbi,\n functionName: \"increase_amount\",\n args: [tokenId, amount],\n });\n return {\n description: `[${this.protocolName}] Increase veNFT #${tokenId} by ${amount}`,\n to: this.veToken,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async buildIncreaseUnlockTime(tokenId: bigint, lockDuration: number): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: veAbi,\n functionName: \"increase_unlock_time\",\n args: [tokenId, BigInt(lockDuration)],\n });\n return {\n description: `[${this.protocolName}] Extend veNFT #${tokenId} lock by ${lockDuration}s`,\n to: this.veToken,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async buildWithdrawExpired(tokenId: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: veAbi,\n functionName: \"withdraw\",\n args: [tokenId],\n });\n return {\n description: `[${this.protocolName}] Withdraw expired veNFT #${tokenId}`,\n to: this.veToken,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n // IVoter\n\n async buildVote(tokenId: bigint, pools: Address[], weights: bigint[]): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: voterAbi,\n functionName: \"vote\",\n args: [tokenId, pools, weights],\n });\n return {\n description: `[${this.protocolName}] Vote with veNFT #${tokenId}`,\n to: this.voter,\n data,\n value: 0n,\n gas_estimate: 500_000,\n };\n }\n\n async buildClaimBribes(bribes: Address[], tokenId: bigint): Promise<DeFiTx> {\n // claimBribes needs token arrays per bribe contract — simplified version\n const tokensPerBribe: Address[][] = bribes.map(() => []);\n const data = encodeFunctionData({\n abi: voterAbi,\n functionName: \"claimBribes\",\n args: [bribes, tokensPerBribe, tokenId],\n });\n return {\n description: `[${this.protocolName}] Claim bribes for veNFT #${tokenId}`,\n to: this.voter,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildClaimFees(fees: Address[], tokenId: bigint): Promise<DeFiTx> {\n const tokensPerFee: Address[][] = fees.map(() => []);\n const data = encodeFunctionData({\n abi: voterAbi,\n functionName: \"claimFees\",\n args: [fees, tokensPerFee, tokenId],\n });\n return {\n description: `[${this.protocolName}] Claim trading fees for veNFT #${tokenId}`,\n to: this.voter,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IGauge,\n ProtocolEntry,\n RewardInfo,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst masterchefAbi = parseAbi([\n \"function deposit(uint256 pid, uint256 amount) external\",\n \"function withdraw(uint256 pid, uint256 amount) external\",\n \"function claim(uint256[] calldata pids) external\",\n \"function pendingRewards(address account, uint256[] calldata pids) view returns (uint256[] memory moeRewards)\",\n \"function getNumberOfFarms() view returns (uint256)\",\n \"function getPidByPool(address pool) view returns (uint256)\",\n]);\n\nexport class MasterChefAdapter implements IGauge {\n private readonly protocolName: string;\n private readonly masterchef: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const masterchef = entry.contracts?.[\"masterchef\"];\n if (!masterchef) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'masterchef' contract\");\n }\n this.masterchef = masterchef;\n this.rpcUrl = rpcUrl;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n /**\n * Deposit LP tokens into a MasterChef farm.\n * `gauge` is the pool address (unused for calldata — MasterChef is the target).\n * `tokenId` carries the farm pid.\n */\n async buildDeposit(gauge: Address, amount: bigint, tokenId?: bigint): Promise<DeFiTx> {\n const pid = tokenId ?? 0n;\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"deposit\",\n args: [pid, amount],\n });\n return {\n description: `[${this.protocolName}] Deposit ${amount} LP to farm pid=${pid} (pool ${gauge})`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /**\n * Withdraw LP tokens from a MasterChef farm.\n * `gauge` is used to look up the pid description only; call site should pass pid via tokenId\n * on the deposit flow. Here pid defaults to 0 — callers should encode the pid in the gauge\n * address slot or wrap this adapter with a pid-aware helper.\n */\n async buildWithdraw(gauge: Address, amount: bigint): Promise<DeFiTx> {\n // IGauge interface does not carry tokenId on withdraw; default pid=0.\n // Callers that need a specific pid should call buildWithdrawPid directly.\n const pid = 0n;\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"withdraw\",\n args: [pid, amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${amount} LP from farm pid=${pid} (pool ${gauge})`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /** Withdraw LP tokens specifying a pid explicitly (MasterChef extension beyond IGauge). */\n async buildWithdrawPid(pid: bigint, amount: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"withdraw\",\n args: [pid, amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${amount} LP from farm pid=${pid}`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /** Claim pending MOE rewards. IGauge interface provides no pid — defaults to pid=0. */\n async buildClaimRewards(gauge: Address): Promise<DeFiTx> {\n const pid = 0n;\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"claim\",\n args: [[pid]],\n });\n return {\n description: `[${this.protocolName}] Claim MOE rewards for farm pid=${pid} (pool ${gauge})`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /** Claim pending MOE rewards for a specific pid (MasterChef extension beyond IGauge). */\n async buildClaimRewardsPid(pid: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"claim\",\n args: [[pid]],\n });\n return {\n description: `[${this.protocolName}] Claim MOE rewards for farm pid=${pid}`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /** Get pending MOE rewards for a user. Requires rpcUrl. */\n async getPendingRewards(_gauge: Address, user: Address): Promise<RewardInfo[]> {\n if (!this.rpcUrl) {\n throw DefiError.unsupported(`[${this.protocolName}] getPendingRewards requires RPC`);\n }\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const rewards = await client.readContract({\n address: this.masterchef,\n abi: masterchefAbi,\n functionName: \"pendingRewards\",\n args: [user, [0n]],\n });\n return (rewards as bigint[]).map((amount) => ({\n token: this.masterchef,\n symbol: \"MOE\",\n amount,\n }));\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n InterestRateMode,\n} from \"@hypurrquant/defi-core\";\n\nconst POOL_ABI = parseAbi([\n \"function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external\",\n \"function borrow(address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf) external\",\n \"function repay(address asset, uint256 amount, uint256 interestRateMode, address onBehalfOf) external returns (uint256)\",\n \"function withdraw(address asset, uint256 amount, address to) external returns (uint256)\",\n \"function getUserAccountData(address user) external view returns (uint256 totalCollateralBase, uint256 totalDebtBase, uint256 availableBorrowsBase, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)\",\n \"function getReserveData(address asset) external view returns (uint256 configuration, uint128 liquidityIndex, uint128 currentLiquidityRate, uint128 variableBorrowIndex, uint128 currentVariableBorrowRate, uint128 currentStableBorrowRate, uint40 lastUpdateTimestamp, uint16 id, address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress, uint128 accruedToTreasury, uint128 unbacked, uint128 isolationModeTotalDebt)\",\n]);\n\nconst ERC20_ABI = parseAbi([\n \"function totalSupply() external view returns (uint256)\",\n]);\n\nconst INCENTIVES_ABI = parseAbi([\n \"function getIncentivesController() external view returns (address)\",\n]);\n\nconst REWARDS_CONTROLLER_ABI = parseAbi([\n \"function getRewardsByAsset(address asset) external view returns (address[])\",\n \"function getRewardsData(address asset, address reward) external view returns (uint256 index, uint256 emissionsPerSecond, uint256 lastUpdateTimestamp, uint256 distributionEnd)\",\n]);\n\nconst POOL_PROVIDER_ABI = parseAbi([\n \"function ADDRESSES_PROVIDER() external view returns (address)\",\n]);\n\nconst ADDRESSES_PROVIDER_ABI = parseAbi([\n \"function getPriceOracle() external view returns (address)\",\n]);\n\nconst ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n \"function BASE_CURRENCY_UNIT() external view returns (uint256)\",\n]);\n\nconst ERC20_DECIMALS_ABI = parseAbi([\n \"function decimals() external view returns (uint8)\",\n]);\n\nfunction u256ToF64(v: bigint): number {\n const MAX_U128 = (1n << 128n) - 1n;\n if (v > MAX_U128) return Infinity;\n return Number(v);\n}\n\nexport class AaveV3Adapter implements ILending {\n private readonly protocolName: string;\n private readonly pool: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const pool = entry.contracts?.[\"pool\"];\n if (!pool) throw DefiError.contractError(`[${entry.name}] Missing 'pool' contract address`);\n this.pool = pool;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"supply\",\n args: [params.asset, params.amount, params.on_behalf_of, 0],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const rateMode = params.interest_rate_mode === InterestRateMode.Stable ? 1n : 2n;\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"borrow\",\n args: [params.asset, params.amount, rateMode, 0, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const rateMode = params.interest_rate_mode === InterestRateMode.Stable ? 1n : 2n;\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"repay\",\n args: [params.asset, params.amount, rateMode, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"withdraw\",\n args: [params.asset, params.amount, params.to],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.amount} from pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const result = await client.readContract({\n address: this.pool,\n abi: POOL_ABI,\n functionName: \"getReserveData\",\n args: [asset],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getReserveData failed: ${e}`);\n });\n\n const RAY = 1e27;\n const SECONDS_PER_YEAR = 31536000;\n\n // Convert ray rate to APY: ((1 + rate/SECONDS_PER_YEAR)^SECONDS_PER_YEAR - 1) * 100\n const toApy = (rayRate: bigint): number => {\n const rate = Number(rayRate) / RAY;\n return (Math.pow(1 + rate / SECONDS_PER_YEAR, SECONDS_PER_YEAR) - 1) * 100;\n };\n\n const supplyRate = toApy(result[2]);\n const variableRate = toApy(result[4]);\n const stableRate = toApy(result[5]);\n\n const aTokenAddress = result[8] as Address;\n const variableDebtTokenAddress = result[10] as Address;\n\n const [totalSupply, totalBorrow] = await Promise.all([\n client.readContract({\n address: aTokenAddress,\n abi: ERC20_ABI,\n functionName: \"totalSupply\",\n }).catch(() => 0n),\n client.readContract({\n address: variableDebtTokenAddress,\n abi: ERC20_ABI,\n functionName: \"totalSupply\",\n }).catch(() => 0n),\n ]);\n\n const utilization = totalSupply > 0n\n ? Number((totalBorrow * 10000n) / totalSupply) / 100\n : 0;\n\n // Fetch incentive/reward data (best-effort, never breaks base rates)\n const supplyRewardTokens: string[] = [];\n const borrowRewardTokens: string[] = [];\n const supplyEmissions: string[] = [];\n const borrowEmissions: string[] = [];\n\n try {\n const controllerAddr = await client.readContract({\n address: aTokenAddress,\n abi: INCENTIVES_ABI,\n functionName: \"getIncentivesController\",\n });\n\n if (controllerAddr && controllerAddr !== zeroAddress) {\n const [supplyRewards, borrowRewards] = await Promise.all([\n client.readContract({\n address: controllerAddr,\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsByAsset\",\n args: [aTokenAddress],\n }).catch(() => [] as Address[]),\n client.readContract({\n address: controllerAddr,\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsByAsset\",\n args: [variableDebtTokenAddress],\n }).catch(() => [] as Address[]),\n ]);\n\n // Fetch emissions data for supply rewards\n const supplyDataPromises = supplyRewards.map((reward) =>\n client.readContract({\n address: controllerAddr,\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsData\",\n args: [aTokenAddress, reward],\n }).catch(() => null),\n );\n const supplyData = await Promise.all(supplyDataPromises);\n for (let i = 0; i < supplyRewards.length; i++) {\n const data = supplyData[i];\n if (data && data[1] > 0n) {\n supplyRewardTokens.push(supplyRewards[i]);\n supplyEmissions.push(data[1].toString());\n }\n }\n\n // Fetch emissions data for borrow rewards\n const borrowDataPromises = borrowRewards.map((reward) =>\n client.readContract({\n address: controllerAddr,\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsData\",\n args: [variableDebtTokenAddress, reward],\n }).catch(() => null),\n );\n const borrowData = await Promise.all(borrowDataPromises);\n for (let i = 0; i < borrowRewards.length; i++) {\n const data = borrowData[i];\n if (data && data[1] > 0n) {\n borrowRewardTokens.push(borrowRewards[i]);\n borrowEmissions.push(data[1].toString());\n }\n }\n }\n } catch {\n // Incentives not supported by this deployment — silently ignore\n }\n\n // Calculate incentive APY from emissions using oracle prices\n let supplyIncentiveApy: number | undefined;\n let borrowIncentiveApy: number | undefined;\n\n const hasSupplyRewards = supplyRewardTokens.length > 0;\n const hasBorrowRewards = borrowRewardTokens.length > 0;\n\n if ((hasSupplyRewards || hasBorrowRewards) && totalSupply > 0n) {\n try {\n // Pool → AddressesProvider → Oracle\n const providerAddr = await client.readContract({\n address: this.pool,\n abi: POOL_PROVIDER_ABI,\n functionName: \"ADDRESSES_PROVIDER\",\n });\n const oracleAddr = await client.readContract({\n address: providerAddr,\n abi: ADDRESSES_PROVIDER_ABI,\n functionName: \"getPriceOracle\",\n });\n const [assetPrice, baseCurrencyUnit, assetDecimals] = await Promise.all([\n client.readContract({\n address: oracleAddr,\n abi: ORACLE_ABI,\n functionName: \"getAssetPrice\",\n args: [asset],\n }),\n client.readContract({\n address: oracleAddr,\n abi: ORACLE_ABI,\n functionName: \"BASE_CURRENCY_UNIT\",\n }),\n client.readContract({\n address: asset,\n abi: ERC20_DECIMALS_ABI,\n functionName: \"decimals\",\n }).catch(() => 18),\n ]);\n\n const priceUnit = Number(baseCurrencyUnit);\n const assetPriceF = Number(assetPrice) / priceUnit;\n const assetDecimalsDivisor = 10 ** assetDecimals;\n\n // Supply-side incentive APY\n if (hasSupplyRewards) {\n let totalSupplyIncentiveUsdPerYear = 0;\n const totalSupplyUsd = (Number(totalSupply) / assetDecimalsDivisor) * assetPriceF;\n\n for (let i = 0; i < supplyRewardTokens.length; i++) {\n const emissionPerSec = BigInt(supplyEmissions[i]);\n const [rewardPrice, rewardDecimals] = await Promise.all([\n client.readContract({\n address: oracleAddr,\n abi: ORACLE_ABI,\n functionName: \"getAssetPrice\",\n args: [supplyRewardTokens[i] as Address],\n }).catch(() => 0n),\n client.readContract({\n address: supplyRewardTokens[i] as Address,\n abi: ERC20_DECIMALS_ABI,\n functionName: \"decimals\",\n }).catch(() => 18),\n ]);\n if (rewardPrice > 0n) {\n const rewardPriceF = Number(rewardPrice) / priceUnit;\n const emissionPerYear = (Number(emissionPerSec) / (10 ** rewardDecimals)) * SECONDS_PER_YEAR;\n totalSupplyIncentiveUsdPerYear += emissionPerYear * rewardPriceF;\n }\n }\n if (totalSupplyUsd > 0) {\n supplyIncentiveApy = (totalSupplyIncentiveUsdPerYear / totalSupplyUsd) * 100;\n }\n }\n\n // Borrow-side incentive APY\n if (hasBorrowRewards && totalBorrow > 0n) {\n let totalBorrowIncentiveUsdPerYear = 0;\n const totalBorrowUsd = (Number(totalBorrow) / assetDecimalsDivisor) * assetPriceF;\n\n for (let i = 0; i < borrowRewardTokens.length; i++) {\n const emissionPerSec = BigInt(borrowEmissions[i]);\n const [rewardPrice, rewardDecimals] = await Promise.all([\n client.readContract({\n address: oracleAddr,\n abi: ORACLE_ABI,\n functionName: \"getAssetPrice\",\n args: [borrowRewardTokens[i] as Address],\n }).catch(() => 0n),\n client.readContract({\n address: borrowRewardTokens[i] as Address,\n abi: ERC20_DECIMALS_ABI,\n functionName: \"decimals\",\n }).catch(() => 18),\n ]);\n if (rewardPrice > 0n) {\n const rewardPriceF = Number(rewardPrice) / priceUnit;\n const emissionPerYear = (Number(emissionPerSec) / (10 ** rewardDecimals)) * SECONDS_PER_YEAR;\n totalBorrowIncentiveUsdPerYear += emissionPerYear * rewardPriceF;\n }\n }\n if (totalBorrowUsd > 0) {\n borrowIncentiveApy = (totalBorrowIncentiveUsdPerYear / totalBorrowUsd) * 100;\n }\n }\n } catch {\n // Oracle not available — skip incentive APY calculation\n }\n }\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyRate,\n borrow_variable_apy: variableRate,\n borrow_stable_apy: stableRate,\n utilization,\n total_supply: totalSupply,\n total_borrow: totalBorrow,\n ...(hasSupplyRewards && {\n supply_reward_tokens: supplyRewardTokens,\n supply_emissions_per_second: supplyEmissions,\n }),\n ...(hasBorrowRewards && {\n borrow_reward_tokens: borrowRewardTokens,\n borrow_emissions_per_second: borrowEmissions,\n }),\n ...(supplyIncentiveApy !== undefined && { supply_incentive_apy: supplyIncentiveApy }),\n ...(borrowIncentiveApy !== undefined && { borrow_incentive_apy: borrowIncentiveApy }),\n };\n }\n\n async getUserPosition(user: Address): Promise<UserPosition> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const result = await client.readContract({\n address: this.pool,\n abi: POOL_ABI,\n functionName: \"getUserAccountData\",\n args: [user],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getUserAccountData failed: ${e}`);\n });\n\n const [totalCollateralBase, totalDebtBase, , , ltv, healthFactor] = result;\n const MAX_UINT256 = 2n ** 256n - 1n;\n const hf = healthFactor >= MAX_UINT256 ? Infinity : Number(healthFactor) / 1e18;\n const collateralUsd = u256ToF64(totalCollateralBase) / 1e8;\n const debtUsd = u256ToF64(totalDebtBase) / 1e8;\n const ltvBps = u256ToF64(ltv);\n\n const supplies = collateralUsd > 0\n ? [{ asset: zeroAddress as Address, symbol: \"Total Collateral\", amount: totalCollateralBase, value_usd: collateralUsd }]\n : [];\n const borrows = debtUsd > 0\n ? [{ asset: zeroAddress as Address, symbol: \"Total Debt\", amount: totalDebtBase, value_usd: debtUsd }]\n : [];\n\n return {\n protocol: this.protocolName,\n user,\n supplies,\n borrows,\n health_factor: hf,\n net_apy: ltvBps / 100,\n };\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n InterestRateMode,\n} from \"@hypurrquant/defi-core\";\n\n// V2 uses deposit/borrow/repay/withdraw (same as V3 for borrow/repay/withdraw)\nconst POOL_ABI = parseAbi([\n \"function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external\",\n \"function borrow(address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf) external\",\n \"function repay(address asset, uint256 amount, uint256 rateMode, address onBehalfOf) external returns (uint256)\",\n \"function withdraw(address asset, uint256 amount, address to) external returns (uint256)\",\n \"function getUserAccountData(address user) external view returns (uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)\",\n // V2 getReserveData: 12 fields (no accruedToTreasury/unbacked/isolationModeTotalDebt)\n // positions: [0]=configuration, [1]=liquidityIndex, [2]=variableBorrowIndex,\n // [3]=currentLiquidityRate, [4]=currentVariableBorrowRate, [5]=currentStableBorrowRate,\n // [6]=lastUpdateTimestamp, [7]=aTokenAddress, [8]=stableDebtTokenAddress,\n // [9]=variableDebtTokenAddress, [10]=interestRateStrategyAddress, [11]=id\n \"function getReserveData(address asset) external view returns (uint256 configuration, uint128 liquidityIndex, uint128 variableBorrowIndex, uint128 currentLiquidityRate, uint128 currentVariableBorrowRate, uint128 currentStableBorrowRate, uint40 lastUpdateTimestamp, address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress, uint8 id)\",\n]);\n\nconst ERC20_ABI = parseAbi([\n \"function totalSupply() external view returns (uint256)\",\n]);\n\nfunction u256ToF64(v: bigint): number {\n const MAX_U128 = (1n << 128n) - 1n;\n if (v > MAX_U128) return Infinity;\n return Number(v);\n}\n\nexport class AaveV2Adapter implements ILending {\n private readonly protocolName: string;\n private readonly pool: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const pool = entry.contracts?.[\"pool\"];\n if (!pool) throw DefiError.contractError(`[${entry.name}] Missing 'pool' contract address`);\n this.pool = pool;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"deposit\",\n args: [params.asset, params.amount, params.on_behalf_of, 0],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const rateMode = params.interest_rate_mode === InterestRateMode.Stable ? 1n : 2n;\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"borrow\",\n args: [params.asset, params.amount, rateMode, 0, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const rateMode = params.interest_rate_mode === InterestRateMode.Stable ? 1n : 2n;\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"repay\",\n args: [params.asset, params.amount, rateMode, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"withdraw\",\n args: [params.asset, params.amount, params.to],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.amount} from pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const result = await client.readContract({\n address: this.pool,\n abi: POOL_ABI,\n functionName: \"getReserveData\",\n args: [asset],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getReserveData failed: ${e}`);\n });\n\n const RAY = 1e27;\n const SECONDS_PER_YEAR = 31536000;\n\n // Convert ray rate to APY: ((1 + rate/SECONDS_PER_YEAR)^SECONDS_PER_YEAR - 1) * 100\n const toApy = (rayRate: bigint): number => {\n const rate = Number(rayRate) / RAY;\n return (Math.pow(1 + rate / SECONDS_PER_YEAR, SECONDS_PER_YEAR) - 1) * 100;\n };\n\n // V2 field positions:\n // [3] = currentLiquidityRate, [4] = currentVariableBorrowRate, [5] = currentStableBorrowRate\n // [7] = aTokenAddress, [9] = variableDebtTokenAddress\n const supplyRate = toApy(result[3]);\n const variableRate = toApy(result[4]);\n const stableRate = toApy(result[5]);\n\n const aTokenAddress = result[7] as Address;\n const variableDebtTokenAddress = result[9] as Address;\n\n const [totalSupply, totalBorrow] = await Promise.all([\n client.readContract({\n address: aTokenAddress,\n abi: ERC20_ABI,\n functionName: \"totalSupply\",\n }).catch(() => 0n),\n client.readContract({\n address: variableDebtTokenAddress,\n abi: ERC20_ABI,\n functionName: \"totalSupply\",\n }).catch(() => 0n),\n ]);\n\n const utilization = totalSupply > 0n\n ? Number((totalBorrow * 10000n) / totalSupply) / 100\n : 0;\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyRate,\n borrow_variable_apy: variableRate,\n borrow_stable_apy: stableRate,\n utilization,\n total_supply: totalSupply,\n total_borrow: totalBorrow,\n };\n }\n\n async getUserPosition(user: Address): Promise<UserPosition> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const result = await client.readContract({\n address: this.pool,\n abi: POOL_ABI,\n functionName: \"getUserAccountData\",\n args: [user],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getUserAccountData failed: ${e}`);\n });\n\n const [totalCollateralBase, totalDebtBase, , , ltv, healthFactor] = result;\n const MAX_UINT256 = 2n ** 256n - 1n;\n const hf = healthFactor >= MAX_UINT256 ? Infinity : Number(healthFactor) / 1e18;\n // V2 returns values in ETH (18 decimals) vs V3's base currency (8 decimals)\n const collateralUsd = u256ToF64(totalCollateralBase) / 1e18;\n const debtUsd = u256ToF64(totalDebtBase) / 1e18;\n const ltvBps = u256ToF64(ltv);\n\n const supplies = collateralUsd > 0\n ? [{ asset: zeroAddress as Address, symbol: \"Total Collateral\", amount: totalCollateralBase, value_usd: collateralUsd }]\n : [];\n const borrows = debtUsd > 0\n ? [{ asset: zeroAddress as Address, symbol: \"Total Debt\", amount: totalDebtBase, value_usd: debtUsd }]\n : [];\n\n return {\n protocol: this.protocolName,\n user,\n supplies,\n borrows,\n health_factor: hf,\n net_apy: ltvBps / 100,\n };\n }\n}\n","import { createPublicClient, http, parseAbi } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { IOracle } from \"@hypurrquant/defi-core\";\nimport { DefiError, type ProtocolEntry, type PriceData } from \"@hypurrquant/defi-core\";\n\nconst ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n \"function getAssetsPrices(address[] calldata assets) external view returns (uint256[] memory)\",\n \"function BASE_CURRENCY_UNIT() external view returns (uint256)\",\n]);\n\nexport class AaveOracleAdapter implements IOracle {\n private readonly protocolName: string;\n private readonly oracle: Address;\n private readonly rpcUrl: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n if (!rpcUrl) throw DefiError.rpcError(`[${entry.name}] RPC URL required for oracle`);\n this.rpcUrl = rpcUrl;\n const oracle = entry.contracts?.[\"oracle\"];\n if (!oracle) throw DefiError.contractError(`[${entry.name}] Missing 'oracle' contract address`);\n this.oracle = oracle;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getPrice(asset: Address): Promise<PriceData> {\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const baseUnit = await client.readContract({\n address: this.oracle,\n abi: ORACLE_ABI,\n functionName: \"BASE_CURRENCY_UNIT\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] BASE_CURRENCY_UNIT failed: ${e}`);\n });\n\n const priceVal = await client.readContract({\n address: this.oracle,\n abi: ORACLE_ABI,\n functionName: \"getAssetPrice\",\n args: [asset],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getAssetPrice failed: ${e}`);\n });\n\n const priceF64 = baseUnit > 0n ? Number(priceVal) / Number(baseUnit) : 0;\n const priceUsd = baseUnit > 0n\n ? (priceVal * (10n ** 18n)) / baseUnit\n : 0n;\n\n return {\n source: `${this.protocolName} Oracle`,\n source_type: \"oracle\",\n asset,\n price_usd: priceUsd,\n price_f64: priceF64,\n };\n }\n\n async getPrices(assets: Address[]): Promise<PriceData[]> {\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const baseUnit = await client.readContract({\n address: this.oracle,\n abi: ORACLE_ABI,\n functionName: \"BASE_CURRENCY_UNIT\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] BASE_CURRENCY_UNIT failed: ${e}`);\n });\n\n const rawPrices = await client.readContract({\n address: this.oracle,\n abi: ORACLE_ABI,\n functionName: \"getAssetsPrices\",\n args: [assets],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getAssetsPrices failed: ${e}`);\n });\n\n return (rawPrices as bigint[]).map((priceVal, i) => {\n const priceF64 = baseUnit > 0n ? Number(priceVal) / Number(baseUnit) : 0;\n const priceUsd = baseUnit > 0n ? (priceVal * (10n ** 18n)) / baseUnit : 0n;\n return {\n source: `${this.protocolName} Oracle`,\n source_type: \"oracle\",\n asset: assets[i]!,\n price_usd: priceUsd,\n price_f64: priceF64,\n };\n });\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst CTOKEN_ABI = parseAbi([\n \"function supplyRatePerBlock() external view returns (uint256)\",\n \"function borrowRatePerBlock() external view returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function totalBorrows() external view returns (uint256)\",\n \"function mint(uint256 mintAmount) external returns (uint256)\",\n \"function redeem(uint256 redeemTokens) external returns (uint256)\",\n \"function borrow(uint256 borrowAmount) external returns (uint256)\",\n \"function repayBorrow(uint256 repayAmount) external returns (uint256)\",\n]);\n\n// ~3s blocks on BSC\nconst BSC_BLOCKS_PER_YEAR = 10_512_000;\n\nexport class CompoundV2Adapter implements ILending {\n private readonly protocolName: string;\n private readonly defaultVtoken: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const vtoken =\n contracts[\"vusdt\"] ??\n contracts[\"vusdc\"] ??\n contracts[\"vbnb\"] ??\n contracts[\"comptroller\"];\n if (!vtoken) throw DefiError.contractError(\"Missing vToken or comptroller address\");\n this.defaultVtoken = vtoken;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: CTOKEN_ABI,\n functionName: \"mint\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to Venus`,\n to: this.defaultVtoken,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: CTOKEN_ABI,\n functionName: \"borrow\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from Venus`,\n to: this.defaultVtoken,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: CTOKEN_ABI,\n functionName: \"repayBorrow\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to Venus`,\n to: this.defaultVtoken,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: CTOKEN_ABI,\n functionName: \"redeem\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw from Venus`,\n to: this.defaultVtoken,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [supplyRate, borrowRate, totalSupply, totalBorrows] = await Promise.all([\n client.readContract({ address: this.defaultVtoken, abi: CTOKEN_ABI, functionName: \"supplyRatePerBlock\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] supplyRatePerBlock failed: ${e}`); }),\n client.readContract({ address: this.defaultVtoken, abi: CTOKEN_ABI, functionName: \"borrowRatePerBlock\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] borrowRatePerBlock failed: ${e}`); }),\n client.readContract({ address: this.defaultVtoken, abi: CTOKEN_ABI, functionName: \"totalSupply\" }).catch(() => 0n),\n client.readContract({ address: this.defaultVtoken, abi: CTOKEN_ABI, functionName: \"totalBorrows\" }).catch(() => 0n),\n ]);\n\n const supplyPerBlock = Number(supplyRate) / 1e18;\n const borrowPerBlock = Number(borrowRate) / 1e18;\n const supplyApy = supplyPerBlock * BSC_BLOCKS_PER_YEAR * 100;\n const borrowApy = borrowPerBlock * BSC_BLOCKS_PER_YEAR * 100;\n\n const supplyF = Number(totalSupply);\n const borrowF = Number(totalBorrows);\n const utilization = supplyF > 0 ? (borrowF / supplyF) * 100 : 0;\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyApy,\n borrow_variable_apy: borrowApy,\n utilization,\n total_supply: totalSupply as bigint,\n total_borrow: totalBorrows as bigint,\n };\n }\n\n async getUserPosition(_user: Address): Promise<UserPosition> {\n throw DefiError.unsupported(\n `[${this.protocolName}] User position requires querying individual vToken balances`,\n );\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst COMET_ABI = parseAbi([\n \"function getUtilization() external view returns (uint256)\",\n \"function getSupplyRate(uint256 utilization) external view returns (uint64)\",\n \"function getBorrowRate(uint256 utilization) external view returns (uint64)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function totalBorrow() external view returns (uint256)\",\n \"function supply(address asset, uint256 amount) external\",\n \"function withdraw(address asset, uint256 amount) external\",\n]);\n\nconst SECONDS_PER_YEAR = 365.25 * 24 * 3600;\n\nexport class CompoundV3Adapter implements ILending {\n private readonly protocolName: string;\n private readonly comet: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const comet = contracts[\"comet_usdc\"] ?? contracts[\"comet\"] ?? contracts[\"comet_weth\"];\n if (!comet) throw DefiError.contractError(\"Missing 'comet_usdc' or 'comet' address\");\n this.comet = comet;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: COMET_ABI,\n functionName: \"supply\",\n args: [params.asset, params.amount],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to Comet`,\n to: this.comet,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n // In Compound V3, borrow = withdraw base asset\n const data = encodeFunctionData({\n abi: COMET_ABI,\n functionName: \"withdraw\",\n args: [params.asset, params.amount],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from Comet`,\n to: this.comet,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n // In Compound V3, repay = supply base asset\n const data = encodeFunctionData({\n abi: COMET_ABI,\n functionName: \"supply\",\n args: [params.asset, params.amount],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to Comet`,\n to: this.comet,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: COMET_ABI,\n functionName: \"withdraw\",\n args: [params.asset, params.amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw from Comet`,\n to: this.comet,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const utilization = await client.readContract({\n address: this.comet,\n abi: COMET_ABI,\n functionName: \"getUtilization\",\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] getUtilization failed: ${e}`); });\n\n const [supplyRate, borrowRate, totalSupply, totalBorrow] = await Promise.all([\n client.readContract({ address: this.comet, abi: COMET_ABI, functionName: \"getSupplyRate\", args: [utilization as bigint] }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] getSupplyRate failed: ${e}`); }),\n client.readContract({ address: this.comet, abi: COMET_ABI, functionName: \"getBorrowRate\", args: [utilization as bigint] }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] getBorrowRate failed: ${e}`); }),\n client.readContract({ address: this.comet, abi: COMET_ABI, functionName: \"totalSupply\" }).catch(() => 0n),\n client.readContract({ address: this.comet, abi: COMET_ABI, functionName: \"totalBorrow\" }).catch(() => 0n),\n ]);\n\n // Comet rates are per-second scaled by 1e18\n const supplyPerSec = Number(supplyRate) / 1e18;\n const borrowPerSec = Number(borrowRate) / 1e18;\n const supplyApy = supplyPerSec * SECONDS_PER_YEAR * 100;\n const borrowApy = borrowPerSec * SECONDS_PER_YEAR * 100;\n const utilPct = Number(utilization as bigint) / 1e18 * 100;\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyApy,\n borrow_variable_apy: borrowApy,\n utilization: utilPct,\n total_supply: totalSupply as bigint,\n total_borrow: totalBorrow as bigint,\n };\n }\n\n async getUserPosition(_user: Address): Promise<UserPosition> {\n throw DefiError.unsupported(\n `[${this.protocolName}] User position requires querying Comet balanceOf + borrowBalanceOf`,\n );\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst EULER_VAULT_ABI = parseAbi([\n \"function deposit(uint256 amount, address receiver) external returns (uint256)\",\n \"function withdraw(uint256 amount, address receiver, address owner) external returns (uint256)\",\n \"function borrow(uint256 amount, address receiver) external returns (uint256)\",\n \"function repay(uint256 amount, address receiver) external returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function totalBorrows() external view returns (uint256)\",\n \"function interestRate() external view returns (uint256)\",\n]);\n\nconst SECONDS_PER_YEAR = 365.25 * 24 * 3600;\n\nexport class EulerV2Adapter implements ILending {\n private readonly protocolName: string;\n private readonly euler: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const euler = contracts[\"evk_vault\"] ?? contracts[\"euler\"] ?? contracts[\"markets\"];\n if (!euler) throw DefiError.contractError(\"Missing 'evk_vault' or 'euler' contract address\");\n this.euler = euler;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: EULER_VAULT_ABI,\n functionName: \"deposit\",\n args: [params.amount, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Deposit ${params.amount} into Euler vault`,\n to: this.euler,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: EULER_VAULT_ABI,\n functionName: \"borrow\",\n args: [params.amount, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from Euler vault`,\n to: this.euler,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: EULER_VAULT_ABI,\n functionName: \"repay\",\n args: [params.amount, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to Euler vault`,\n to: this.euler,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: EULER_VAULT_ABI,\n functionName: \"withdraw\",\n args: [params.amount, params.to, params.to],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.amount} from Euler vault`,\n to: this.euler,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [totalSupply, totalBorrows, interestRate] = await Promise.all([\n client.readContract({ address: this.euler, abi: EULER_VAULT_ABI, functionName: \"totalSupply\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] totalSupply failed: ${e}`); }),\n client.readContract({ address: this.euler, abi: EULER_VAULT_ABI, functionName: \"totalBorrows\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] totalBorrows failed: ${e}`); }),\n client.readContract({ address: this.euler, abi: EULER_VAULT_ABI, functionName: \"interestRate\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] interestRate failed: ${e}`); }),\n ]);\n\n // Euler V2 interest rates per-second scaled by 1e27\n const rateF64 = Number(interestRate) / 1e27;\n const borrowApy = rateF64 * SECONDS_PER_YEAR * 100;\n\n const supplyF = Number(totalSupply);\n const borrowF = Number(totalBorrows);\n const utilization = supplyF > 0 ? (borrowF / supplyF) * 100 : 0;\n const supplyApy = borrowApy * (borrowF / Math.max(supplyF, 1));\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyApy,\n borrow_variable_apy: borrowApy,\n utilization,\n total_supply: totalSupply as bigint,\n total_borrow: totalBorrows as bigint,\n };\n }\n\n async getUserPosition(_user: Address): Promise<UserPosition> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Euler V2 user positions require querying individual vault balances. Use the vault address directly to check balanceOf(user) for supply positions.`,\n );\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst MORPHO_ABI = parseAbi([\n \"function market(bytes32 id) external view returns (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee)\",\n \"function idToMarketParams(bytes32 id) external view returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv)\",\n \"function supply((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) external returns (uint256 assetsSupplied, uint256 sharesSupplied)\",\n \"function borrow((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed)\",\n \"function repay((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) external returns (uint256 assetsRepaid, uint256 sharesRepaid)\",\n \"function withdraw((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn)\",\n]);\n\nconst META_MORPHO_ABI = parseAbi([\n \"function supplyQueueLength() external view returns (uint256)\",\n \"function supplyQueue(uint256 index) external view returns (bytes32)\",\n \"function totalAssets() external view returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n]);\n\nconst IRM_ABI = parseAbi([\n \"function borrowRateView((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee) market) external view returns (uint256)\",\n]);\n\nconst SECONDS_PER_YEAR = 365.25 * 24 * 3600;\n\ntype MarketParams = {\n loanToken: Address;\n collateralToken: Address;\n oracle: Address;\n irm: Address;\n lltv: bigint;\n};\n\nfunction defaultMarketParams(loanToken: Address = zeroAddress as Address): MarketParams {\n return {\n loanToken,\n collateralToken: zeroAddress as Address,\n oracle: zeroAddress as Address,\n irm: zeroAddress as Address,\n lltv: 0n,\n };\n}\n\nexport class MorphoBlueAdapter implements ILending {\n private readonly protocolName: string;\n private readonly morpho: Address;\n private readonly defaultVault?: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const morpho = contracts[\"morpho_blue\"];\n if (!morpho) throw DefiError.contractError(\"Missing 'morpho_blue' contract address\");\n this.morpho = morpho;\n this.defaultVault =\n contracts[\"fehype\"] ?? contracts[\"vault\"] ?? contracts[\"feusdc\"];\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const market = defaultMarketParams(params.asset);\n const data = encodeFunctionData({\n abi: MORPHO_ABI,\n functionName: \"supply\",\n args: [market, params.amount, 0n, params.on_behalf_of, \"0x\"],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to Morpho market`,\n to: this.morpho,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const market = defaultMarketParams(params.asset);\n const data = encodeFunctionData({\n abi: MORPHO_ABI,\n functionName: \"borrow\",\n args: [market, params.amount, 0n, params.on_behalf_of, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from Morpho market`,\n to: this.morpho,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const market = defaultMarketParams(params.asset);\n const data = encodeFunctionData({\n abi: MORPHO_ABI,\n functionName: \"repay\",\n args: [market, params.amount, 0n, params.on_behalf_of, \"0x\"],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to Morpho market`,\n to: this.morpho,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const market = defaultMarketParams(params.asset);\n const data = encodeFunctionData({\n abi: MORPHO_ABI,\n functionName: \"withdraw\",\n args: [market, params.amount, 0n, params.to, params.to],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.amount} from Morpho market`,\n to: this.morpho,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n if (!this.defaultVault) {\n throw DefiError.contractError(`[${this.protocolName}] No MetaMorpho vault configured for rate query`);\n }\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const queueLen = await client.readContract({\n address: this.defaultVault,\n abi: META_MORPHO_ABI,\n functionName: \"supplyQueueLength\",\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] supplyQueueLength failed: ${e}`); });\n\n if ((queueLen as bigint) === 0n) {\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: 0,\n borrow_variable_apy: 0,\n utilization: 0,\n total_supply: 0n,\n total_borrow: 0n,\n };\n }\n\n const marketId = await client.readContract({\n address: this.defaultVault,\n abi: META_MORPHO_ABI,\n functionName: \"supplyQueue\",\n args: [0n],\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] supplyQueue(0) failed: ${e}`); }) as `0x${string}`;\n\n const mkt = await client.readContract({\n address: this.morpho,\n abi: MORPHO_ABI,\n functionName: \"market\",\n args: [marketId],\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] market() failed: ${e}`); });\n\n const [totalSupplyAssets, totalSupplyShares, totalBorrowAssets, totalBorrowShares, lastUpdate, fee] = mkt as [bigint, bigint, bigint, bigint, bigint, bigint];\n\n const supplyF = Number(totalSupplyAssets);\n const borrowF = Number(totalBorrowAssets);\n const util = supplyF > 0 ? borrowF / supplyF : 0;\n\n const params2 = await client.readContract({\n address: this.morpho,\n abi: MORPHO_ABI,\n functionName: \"idToMarketParams\",\n args: [marketId],\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] idToMarketParams failed: ${e}`); });\n\n const [loanToken, collateralToken, oracle, irm, lltv] = params2 as [Address, Address, Address, Address, bigint];\n\n const irmMarketParams: MarketParams = { loanToken, collateralToken, oracle, irm, lltv };\n const irmMarket = { totalSupplyAssets, totalSupplyShares, totalBorrowAssets, totalBorrowShares, lastUpdate, fee };\n\n const borrowRatePerSec = await client.readContract({\n address: irm,\n abi: IRM_ABI,\n functionName: \"borrowRateView\",\n args: [irmMarketParams, irmMarket],\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] borrowRateView failed: ${e}`); }) as bigint;\n\n const ratePerSec = Number(borrowRatePerSec) / 1e18;\n const borrowApy = ratePerSec * SECONDS_PER_YEAR * 100;\n const feePct = Number(fee) / 1e18;\n const supplyApy = borrowApy * util * (1 - feePct);\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyApy,\n borrow_variable_apy: borrowApy,\n utilization: util * 100,\n total_supply: totalSupplyAssets,\n total_borrow: totalBorrowAssets,\n };\n }\n\n async getUserPosition(_user: Address): Promise<UserPosition> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Morpho Blue user positions are per-market — use vault deposit/withdraw instead`,\n );\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ICdp } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type OpenCdpParams,\n type AdjustCdpParams,\n type CloseCdpParams,\n type CdpInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst BORROWER_OPS_ABI = parseAbi([\n \"function openTrove(address _owner, uint256 _ownerIndex, uint256 _collAmount, uint256 _boldAmount, uint256 _upperHint, uint256 _lowerHint, uint256 _annualInterestRate, uint256 _maxUpfrontFee, address _addManager, address _removeManager, address _receiver) external returns (uint256)\",\n \"function adjustTrove(uint256 _troveId, uint256 _collChange, bool _isCollIncrease, uint256 _debtChange, bool _isDebtIncrease, uint256 _upperHint, uint256 _lowerHint, uint256 _maxUpfrontFee) external\",\n \"function closeTrove(uint256 _troveId) external\",\n]);\n\nconst TROVE_MANAGER_ABI = parseAbi([\n \"function getLatestTroveData(uint256 _troveId) external view returns (uint256 entireDebt, uint256 entireColl, uint256 redistDebtGain, uint256 redistCollGain, uint256 accruedInterest, uint256 recordedDebt, uint256 annualInterestRate, uint256 accruedBatchManagementFee, uint256 weightedRecordedDebt, uint256 lastInterestRateAdjTime)\",\n]);\n\nconst HINT_HELPERS_ABI = parseAbi([\n \"function getApproxHint(uint256 _collIndex, uint256 _interestRate, uint256 _numTrials, uint256 _inputRandomSeed) external view returns (uint256 hintId, uint256 diff, uint256 latestRandomSeed)\",\n]);\n\nconst SORTED_TROVES_ABI = parseAbi([\n \"function findInsertPosition(uint256 _annualInterestRate, uint256 _prevId, uint256 _nextId) external view returns (uint256 prevId, uint256 nextId)\",\n]);\n\nexport class FelixCdpAdapter implements ICdp {\n private readonly protocolName: string;\n private readonly borrowerOperations: Address;\n private readonly troveManager?: Address;\n private readonly hintHelpers?: Address;\n private readonly sortedTroves?: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const bo = contracts[\"borrower_operations\"];\n if (!bo) throw DefiError.contractError(\"Missing 'borrower_operations' contract\");\n this.borrowerOperations = bo;\n this.troveManager = contracts[\"trove_manager\"];\n this.hintHelpers = contracts[\"hint_helpers\"];\n this.sortedTroves = contracts[\"sorted_troves\"];\n }\n\n name(): string {\n return this.protocolName;\n }\n\n private async getHints(interestRate: bigint): Promise<[bigint, bigint]> {\n if (!this.hintHelpers || !this.sortedTroves || !this.rpcUrl) {\n return [0n, 0n];\n }\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const approxResult = await client.readContract({\n address: this.hintHelpers,\n abi: HINT_HELPERS_ABI,\n functionName: \"getApproxHint\",\n args: [0n, interestRate, 15n, 42n],\n }).catch(() => null);\n\n if (!approxResult) return [0n, 0n];\n const [hintId] = approxResult as [bigint, bigint, bigint];\n\n const insertResult = await client.readContract({\n address: this.sortedTroves,\n abi: SORTED_TROVES_ABI,\n functionName: \"findInsertPosition\",\n args: [interestRate, hintId, hintId],\n }).catch(() => null);\n\n if (!insertResult) return [0n, 0n];\n const [prevId, nextId] = insertResult as [bigint, bigint];\n return [prevId, nextId];\n }\n\n async buildOpen(params: OpenCdpParams): Promise<DeFiTx> {\n const interestRate = 50000000000000000n; // 5% default\n const [upperHint, lowerHint] = await this.getHints(interestRate);\n const hasHints = upperHint !== 0n || lowerHint !== 0n;\n\n const data = encodeFunctionData({\n abi: BORROWER_OPS_ABI,\n functionName: \"openTrove\",\n args: [\n params.recipient,\n 0n,\n params.collateral_amount,\n params.debt_amount,\n upperHint,\n lowerHint,\n interestRate,\n BigInt(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"), // U256::MAX\n params.recipient,\n params.recipient,\n params.recipient,\n ],\n });\n\n return {\n description: `[${this.protocolName}] Open trove: collateral=${params.collateral_amount}, debt=${params.debt_amount} (hints=${hasHints ? \"optimized\" : \"none\"})`,\n to: this.borrowerOperations,\n data,\n value: 0n,\n gas_estimate: hasHints ? 500_000 : 5_000_000,\n };\n }\n\n async buildAdjust(params: AdjustCdpParams): Promise<DeFiTx> {\n const collChange = params.collateral_delta ?? 0n;\n const debtChange = params.debt_delta ?? 0n;\n\n const data = encodeFunctionData({\n abi: BORROWER_OPS_ABI,\n functionName: \"adjustTrove\",\n args: [\n params.cdp_id,\n collChange,\n params.add_collateral,\n debtChange,\n params.add_debt,\n 0n,\n 0n,\n BigInt(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Adjust trove ${params.cdp_id}`,\n to: this.borrowerOperations,\n data,\n value: 0n,\n gas_estimate: 400_000,\n };\n }\n\n async buildClose(params: CloseCdpParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: BORROWER_OPS_ABI,\n functionName: \"closeTrove\",\n args: [params.cdp_id],\n });\n\n return {\n description: `[${this.protocolName}] Close trove ${params.cdp_id}`,\n to: this.borrowerOperations,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async getCdpInfo(cdpId: bigint): Promise<CdpInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(`[${this.protocolName}] getCdpInfo requires RPC — set HYPEREVM_RPC_URL`);\n if (!this.troveManager) throw DefiError.contractError(`[${this.protocolName}] trove_manager contract not configured`);\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const data = await client.readContract({\n address: this.troveManager,\n abi: TROVE_MANAGER_ABI,\n functionName: \"getLatestTroveData\",\n args: [cdpId],\n }).catch((e: unknown) => {\n throw DefiError.invalidParam(`[${this.protocolName}] Trove ${cdpId} not found: ${e}`);\n });\n\n const [entireDebt, entireColl] = data as [bigint, bigint, bigint, bigint, bigint, bigint, bigint, bigint, bigint, bigint];\n\n if (entireDebt === 0n && entireColl === 0n) {\n throw DefiError.invalidParam(`[${this.protocolName}] Trove ${cdpId} does not exist`);\n }\n\n const collRatio = entireDebt > 0n ? Number(entireColl) / Number(entireDebt) : 0;\n\n return {\n protocol: this.protocolName,\n cdp_id: cdpId,\n collateral: {\n token: zeroAddress as Address,\n symbol: \"WHYPE\",\n amount: entireColl,\n decimals: 18,\n },\n debt: {\n token: zeroAddress as Address,\n symbol: \"feUSD\",\n amount: entireDebt,\n decimals: 18,\n },\n collateral_ratio: collRatio,\n };\n }\n}\n","import { createPublicClient, http, parseAbi } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { IOracle } from \"@hypurrquant/defi-core\";\nimport { DefiError, type ProtocolEntry, type PriceData } from \"@hypurrquant/defi-core\";\n\nconst PRICE_FEED_ABI = parseAbi([\n \"function fetchPrice() external view returns (uint256 price, bool isNewOracleFailureDetected)\",\n \"function lastGoodPrice() external view returns (uint256)\",\n]);\n\nexport class FelixOracleAdapter implements IOracle {\n private readonly protocolName: string;\n private readonly priceFeed: Address;\n private readonly asset: Address;\n private readonly rpcUrl: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n if (!rpcUrl) throw DefiError.rpcError(`[${entry.name}] RPC URL required for oracle`);\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const feed = contracts[\"price_feed\"];\n if (!feed) throw DefiError.contractError(`[${entry.name}] Missing 'price_feed' contract address`);\n this.priceFeed = feed;\n // The asset address is stored under \"asset\" or falls back to zero (WHYPE native)\n this.asset = contracts[\"asset\"] ?? (\"0x0000000000000000000000000000000000000000\" as Address);\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getPrice(asset: Address): Promise<PriceData> {\n if (asset !== this.asset && this.asset !== \"0x0000000000000000000000000000000000000000\") {\n throw DefiError.unsupported(`[${this.protocolName}] Felix PriceFeed only supports asset ${this.asset}`);\n }\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n let priceVal: bigint;\n try {\n const result = await client.readContract({\n address: this.priceFeed,\n abi: PRICE_FEED_ABI,\n functionName: \"fetchPrice\",\n });\n const [price] = result as [bigint, boolean];\n priceVal = price;\n } catch {\n // Fall back to lastGoodPrice\n priceVal = await client.readContract({\n address: this.priceFeed,\n abi: PRICE_FEED_ABI,\n functionName: \"lastGoodPrice\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] lastGoodPrice failed: ${e}`);\n }) as bigint;\n }\n\n // Felix prices are already in 18-decimal USD\n const priceF64 = Number(priceVal) / 1e18;\n\n return {\n source: \"Felix PriceFeed\",\n source_type: \"oracle\",\n asset,\n price_usd: priceVal,\n price_f64: priceF64,\n };\n }\n\n async getPrices(assets: Address[]): Promise<PriceData[]> {\n const results: PriceData[] = [];\n for (const asset of assets) {\n try {\n results.push(await this.getPrice(asset));\n } catch {\n // Skip unsupported assets\n }\n }\n return results;\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { IVault } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type VaultInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst ERC4626_ABI = parseAbi([\n \"function asset() external view returns (address)\",\n \"function totalAssets() external view returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function convertToShares(uint256 assets) external view returns (uint256)\",\n \"function convertToAssets(uint256 shares) external view returns (uint256)\",\n \"function deposit(uint256 assets, address receiver) external returns (uint256 shares)\",\n \"function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares)\",\n]);\n\nexport class ERC4626VaultAdapter implements IVault {\n private readonly protocolName: string;\n private readonly vaultAddress: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const vault = entry.contracts?.[\"vault\"];\n if (!vault) throw DefiError.contractError(\"Missing 'vault' contract address\");\n this.vaultAddress = vault;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildDeposit(assets: bigint, receiver: Address): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: ERC4626_ABI,\n functionName: \"deposit\",\n args: [assets, receiver],\n });\n return {\n description: `[${this.protocolName}] Deposit ${assets} assets into vault`,\n to: this.vaultAddress,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async buildWithdraw(assets: bigint, receiver: Address, owner: Address): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: ERC4626_ABI,\n functionName: \"withdraw\",\n args: [assets, receiver, owner],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${assets} assets from vault`,\n to: this.vaultAddress,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async totalAssets(): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n return client.readContract({\n address: this.vaultAddress,\n abi: ERC4626_ABI,\n functionName: \"totalAssets\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] totalAssets failed: ${e}`);\n }) as Promise<bigint>;\n }\n\n async convertToShares(assets: bigint): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n return client.readContract({\n address: this.vaultAddress,\n abi: ERC4626_ABI,\n functionName: \"convertToShares\",\n args: [assets],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] convertToShares failed: ${e}`);\n }) as Promise<bigint>;\n }\n\n async convertToAssets(shares: bigint): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n return client.readContract({\n address: this.vaultAddress,\n abi: ERC4626_ABI,\n functionName: \"convertToAssets\",\n args: [shares],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] convertToAssets failed: ${e}`);\n }) as Promise<bigint>;\n }\n\n async getVaultInfo(): Promise<VaultInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [totalAssets, totalSupply, asset] = await Promise.all([\n client.readContract({ address: this.vaultAddress, abi: ERC4626_ABI, functionName: \"totalAssets\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] totalAssets failed: ${e}`); }),\n client.readContract({ address: this.vaultAddress, abi: ERC4626_ABI, functionName: \"totalSupply\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] totalSupply failed: ${e}`); }),\n client.readContract({ address: this.vaultAddress, abi: ERC4626_ABI, functionName: \"asset\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] asset failed: ${e}`); }),\n ]);\n\n return {\n protocol: this.protocolName,\n vault_address: this.vaultAddress,\n asset: asset as Address,\n total_assets: totalAssets as bigint,\n total_supply: totalSupply as bigint,\n };\n }\n}\n","import { parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILiquidStaking } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type StakeParams,\n type UnstakeParams,\n type StakingInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst GENERIC_LST_ABI = parseAbi([\n \"function stake() external payable returns (uint256)\",\n \"function unstake(uint256 amount) external returns (uint256)\",\n]);\n\nexport class GenericLstAdapter implements ILiquidStaking {\n private readonly protocolName: string;\n private readonly staking: Address;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const staking = entry.contracts?.[\"staking\"];\n if (!staking) throw DefiError.contractError(\"Missing 'staking' contract\");\n this.staking = staking;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildStake(params: StakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({ abi: GENERIC_LST_ABI, functionName: \"stake\" });\n return {\n description: `[${this.protocolName}] Stake ${params.amount} HYPE`,\n to: this.staking,\n data,\n value: params.amount,\n gas_estimate: 200_000,\n };\n }\n\n async buildUnstake(params: UnstakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: GENERIC_LST_ABI,\n functionName: \"unstake\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Unstake ${params.amount}`,\n to: this.staking,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async getInfo(): Promise<StakingInfo> {\n throw DefiError.unsupported(`[${this.protocolName}] getInfo requires RPC`);\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILiquidStaking } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type StakeParams,\n type UnstakeParams,\n type StakingInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst STHYPE_ABI = parseAbi([\n \"function submit(address referral) external payable returns (uint256)\",\n \"function requestWithdrawals(uint256[] amounts, address owner) external returns (uint256[] requestIds)\",\n]);\n\nconst ERC20_ABI = parseAbi([\n \"function totalSupply() external view returns (uint256)\",\n]);\n\nexport class StHypeAdapter implements ILiquidStaking {\n private readonly protocolName: string;\n private readonly staking: Address;\n private readonly sthypeToken?: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const staking = entry.contracts?.[\"staking\"];\n if (!staking) throw DefiError.contractError(\"Missing 'staking' contract\");\n this.staking = staking;\n this.sthypeToken = entry.contracts?.[\"sthype_token\"];\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildStake(params: StakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: STHYPE_ABI,\n functionName: \"submit\",\n args: [zeroAddress as Address],\n });\n return {\n description: `[${this.protocolName}] Stake ${params.amount} HYPE for stHYPE`,\n to: this.staking,\n data,\n value: params.amount,\n gas_estimate: 200_000,\n };\n }\n\n async buildUnstake(params: UnstakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: STHYPE_ABI,\n functionName: \"requestWithdrawals\",\n args: [[params.amount], params.recipient],\n });\n return {\n description: `[${this.protocolName}] Request unstake ${params.amount} stHYPE`,\n to: this.staking,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async getInfo(): Promise<StakingInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const tokenAddr = this.sthypeToken ?? this.staking;\n\n const totalSupply = await client.readContract({\n address: tokenAddr,\n abi: ERC20_ABI,\n functionName: \"totalSupply\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] totalSupply failed: ${e}`);\n }) as bigint;\n\n return {\n protocol: this.protocolName,\n staked_token: zeroAddress as Address,\n liquid_token: tokenAddr,\n exchange_rate: 1.0,\n total_staked: totalSupply,\n };\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILiquidStaking } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type StakeParams,\n type UnstakeParams,\n type StakingInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst KINETIQ_ABI = parseAbi([\n \"function stake() external payable returns (uint256)\",\n \"function requestUnstake(uint256 amount) external returns (uint256)\",\n \"function totalStaked() external view returns (uint256)\",\n]);\n\nconst ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n]);\n\n// WHYPE address on HyperEVM\nconst WHYPE: Address = \"0x5555555555555555555555555555555555555555\";\n// HyperLend oracle address (Aave V3 compatible)\nconst HYPERLEND_ORACLE: Address = \"0xc9fb4fbe842d57ea1df3e641a281827493a63030\";\n\nexport class KinetiqAdapter implements ILiquidStaking {\n private readonly protocolName: string;\n private readonly staking: Address;\n private readonly liquidToken: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const staking = entry.contracts?.[\"staking\"];\n if (!staking) throw DefiError.contractError(\"Missing 'staking' contract address\");\n this.staking = staking;\n this.liquidToken = entry.contracts?.[\"khype_token\"] ?? staking;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildStake(params: StakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({ abi: KINETIQ_ABI, functionName: \"stake\" });\n return {\n description: `[${this.protocolName}] Stake ${params.amount} HYPE for kHYPE`,\n to: this.staking,\n data,\n value: params.amount,\n gas_estimate: 300_000,\n };\n }\n\n async buildUnstake(params: UnstakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: KINETIQ_ABI,\n functionName: \"requestUnstake\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Request unstake ${params.amount} kHYPE`,\n to: this.staking,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async getInfo(): Promise<StakingInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const totalStaked = await client.readContract({\n address: this.staking,\n abi: KINETIQ_ABI,\n functionName: \"totalStaked\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] totalStaked failed: ${e}`);\n }) as bigint;\n\n const [khypePrice, hypePrice] = await Promise.all([\n client.readContract({ address: HYPERLEND_ORACLE, abi: ORACLE_ABI, functionName: \"getAssetPrice\", args: [this.liquidToken] }).catch(() => 0n),\n client.readContract({ address: HYPERLEND_ORACLE, abi: ORACLE_ABI, functionName: \"getAssetPrice\", args: [WHYPE] }).catch(() => 0n),\n ]);\n\n const rateF64 =\n (hypePrice as bigint) > 0n && (khypePrice as bigint) > 0n\n ? Number((khypePrice as bigint) * 10n ** 18n / (hypePrice as bigint)) / 1e18\n : 1.0;\n\n return {\n protocol: this.protocolName,\n staked_token: zeroAddress as Address,\n liquid_token: this.liquidToken,\n exchange_rate: rateF64,\n total_staked: totalStaked,\n };\n }\n}\n","import type { Address } from \"viem\";\nimport type { IYieldSource } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type YieldInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nexport class PendleAdapter implements IYieldSource {\n private readonly protocolName: string;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n if (!entry.contracts?.[\"router\"]) {\n throw DefiError.contractError(\"Missing 'router' contract\");\n }\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getYields(): Promise<YieldInfo[]> {\n throw DefiError.unsupported(`[${this.protocolName}] getYields requires RPC`);\n }\n\n async buildDeposit(_pool: string, _amount: bigint, _recipient: Address): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Pendle deposit requires market address and token routing params. Use Pendle-specific CLI.`,\n );\n }\n\n async buildWithdraw(_pool: string, _amount: bigint, _recipient: Address): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Pendle withdraw requires market-specific params`,\n );\n }\n}\n","import type { Address } from \"viem\";\nimport type { IYieldSource } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type YieldInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nexport class GenericYieldAdapter implements IYieldSource {\n private readonly protocolName: string;\n private readonly interfaceName: string;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n this.interfaceName = entry.interface;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getYields(): Promise<YieldInfo[]> {\n throw DefiError.unsupported(`[${this.protocolName}] getYields requires RPC`);\n }\n\n async buildDeposit(_pool: string, _amount: bigint, _recipient: Address): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Yield interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'pendle_v2' (Pendle). Protocols like Steer (managed liquidity), ` +\n `Liminal (yield optimization), and Altura (gaming yield) need custom deposit logic.`,\n );\n }\n\n async buildWithdraw(_pool: string, _amount: bigint, _recipient: Address): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Yield interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'pendle_v2' (Pendle). Protocols like Steer (managed liquidity), ` +\n `Liminal (yield optimization), and Altura (gaming yield) need custom withdraw logic.`,\n );\n }\n}\n","import { parseAbi, encodeFunctionData } from \"viem\";\nimport type { IDerivatives } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type DerivativesPositionParams,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\n\nconst HLP_ABI = parseAbi([\n \"function deposit(uint256 amount) external returns (uint256)\",\n \"function withdraw(uint256 shares) external returns (uint256)\",\n]);\n\nexport class HlpVaultAdapter implements IDerivatives {\n private readonly protocolName: string;\n private readonly vault: Address;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const vault = entry.contracts?.[\"vault\"];\n if (!vault) throw DefiError.contractError(\"Missing 'vault' contract\");\n this.vault = vault;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildOpenPosition(params: DerivativesPositionParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: HLP_ABI,\n functionName: \"deposit\",\n args: [params.collateral],\n });\n return {\n description: `[${this.protocolName}] Deposit ${params.collateral} into HLP vault`,\n to: this.vault,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async buildClosePosition(params: DerivativesPositionParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: HLP_ABI,\n functionName: \"withdraw\",\n args: [params.size],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.size} from HLP vault`,\n to: this.vault,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n}\n","import type { IDerivatives } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type DerivativesPositionParams,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nexport class GenericDerivativesAdapter implements IDerivatives {\n private readonly protocolName: string;\n private readonly interfaceName: string;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n this.interfaceName = entry.interface;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildOpenPosition(_params: DerivativesPositionParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Derivatives interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'hlp_vault' (HLP Vault). Protocols like Rumpel need custom position management logic.`,\n );\n }\n\n async buildClosePosition(_params: DerivativesPositionParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Derivatives interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'hlp_vault' (HLP Vault). Protocols like Rumpel need custom position management logic.`,\n );\n }\n}\n","import { parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { IOptions } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type OptionParams,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst RYSK_ABI = parseAbi([\n \"function openOption(address underlying, uint256 strikePrice, uint256 expiry, bool isCall, uint256 amount) external returns (uint256 premium)\",\n \"function closeOption(address underlying, uint256 strikePrice, uint256 expiry, bool isCall, uint256 amount) external returns (uint256 payout)\",\n]);\n\nexport class RyskAdapter implements IOptions {\n private readonly protocolName: string;\n private readonly controller: Address;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const controller = entry.contracts?.[\"controller\"];\n if (!controller) throw DefiError.contractError(\"Missing 'controller' contract\");\n this.controller = controller;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildBuy(params: OptionParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: RYSK_ABI,\n functionName: \"openOption\",\n args: [\n params.underlying,\n params.strike_price,\n BigInt(params.expiry),\n params.is_call,\n params.amount,\n ],\n });\n return {\n description: `[${this.protocolName}] Buy ${params.is_call ? \"call\" : \"put\"} ${params.amount} option, strike=${params.strike_price}, expiry=${params.expiry}`,\n to: this.controller,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildSell(params: OptionParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: RYSK_ABI,\n functionName: \"closeOption\",\n args: [\n params.underlying,\n params.strike_price,\n BigInt(params.expiry),\n params.is_call,\n params.amount,\n ],\n });\n return {\n description: `[${this.protocolName}] Sell/close ${params.is_call ? \"call\" : \"put\"} ${params.amount} option`,\n to: this.controller,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n}\n","import type { IOptions } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type OptionParams,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nexport class GenericOptionsAdapter implements IOptions {\n private readonly protocolName: string;\n private readonly interfaceName: string;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n this.interfaceName = entry.interface;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildBuy(_params: OptionParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Options interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'rysk' (Rysk Finance). Other options protocols need custom strike/expiry handling.`,\n );\n }\n\n async buildSell(_params: OptionParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Options interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'rysk' (Rysk Finance). Other options protocols need custom strike/expiry handling.`,\n );\n }\n}\n","import { createPublicClient, http, parseAbi } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { INft, NftCollectionInfo, NftTokenInfo } from \"@hypurrquant/defi-core\";\nimport { DefiError, type ProtocolEntry } from \"@hypurrquant/defi-core\";\n\nconst ERC721_ABI = parseAbi([\n \"function name() returns (string)\",\n \"function symbol() returns (string)\",\n \"function totalSupply() returns (uint256)\",\n \"function ownerOf(uint256 tokenId) returns (address)\",\n \"function balanceOf(address owner) returns (uint256)\",\n \"function tokenURI(uint256 tokenId) returns (string)\",\n]);\n\nexport class ERC721Adapter implements INft {\n private readonly protocolName: string;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getCollectionInfo(collection: Address): Promise<NftCollectionInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [collectionName, symbol, totalSupply] = await Promise.all([\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"name\" })\n .catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] name failed: ${e}`);\n }),\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"symbol\" })\n .catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] symbol failed: ${e}`);\n }),\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"totalSupply\" })\n .catch(() => undefined),\n ]);\n\n return {\n address: collection,\n name: collectionName as string,\n symbol: symbol as string,\n total_supply: totalSupply as bigint | undefined,\n };\n }\n\n async getTokenInfo(collection: Address, tokenId: bigint): Promise<NftTokenInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [owner, tokenUri] = await Promise.all([\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"ownerOf\", args: [tokenId] })\n .catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] ownerOf failed: ${e}`);\n }),\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"tokenURI\", args: [tokenId] })\n .catch(() => undefined),\n ]);\n\n return {\n collection,\n token_id: tokenId,\n owner: owner as Address,\n token_uri: tokenUri as string | undefined,\n };\n }\n\n async getBalance(owner: Address, collection: Address): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n return client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"balanceOf\", args: [owner] })\n .catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] balanceOf failed: ${e}`);\n }) as Promise<bigint>;\n }\n}\n","import type { Address } from \"viem\";\n\nimport type { IDex, PriceData, QuoteParams } from \"@hypurrquant/defi-core\";\n\n/**\n * Utility for deriving spot prices from DEX quoters.\n * Quotes 1 unit of the token against a quote token (e.g. USDC) to derive price.\n */\nexport class DexSpotPrice {\n /**\n * Get the spot price for `token` denominated in `quoteToken` (e.g. USDC).\n *\n * `tokenDecimals` — decimals of the input token (to know how much \"1 unit\" is)\n * `quoteDecimals` — decimals of the quote token (to convert the output to number)\n */\n static async getPrice(\n dex: IDex,\n token: Address,\n tokenDecimals: number,\n quoteToken: Address,\n quoteDecimals: number,\n ): Promise<PriceData> {\n const amountIn = 10n ** BigInt(tokenDecimals); // 1 token\n\n const quoteParams: QuoteParams = {\n protocol: \"\",\n token_in: token,\n token_out: quoteToken,\n amount_in: amountIn,\n };\n\n const quote = await dex.quote(quoteParams);\n\n // Convert to USD price (assuming quoteToken is a USD stablecoin)\n const priceF64 = Number(quote.amount_out) / 10 ** quoteDecimals;\n\n // Normalize to 18-decimal representation\n let priceUsd: bigint;\n if (quoteDecimals < 18) {\n priceUsd = quote.amount_out * 10n ** BigInt(18 - quoteDecimals);\n } else if (quoteDecimals > 18) {\n priceUsd = quote.amount_out / 10n ** BigInt(quoteDecimals - 18);\n } else {\n priceUsd = quote.amount_out;\n }\n\n return {\n source: `dex:${dex.name()}`,\n source_type: \"dex_spot\",\n asset: token,\n price_usd: priceUsd,\n price_f64: priceF64,\n block_number: undefined,\n timestamp: undefined,\n };\n }\n}\n","#!/usr/bin/env node\n/**\n * MCP (Model Context Protocol) server for defi-cli.\n *\n * Exposes DeFi operations as MCP tools: lending, DEX, bridge, vault, staking,\n * price queries, exploit detection, and portfolio overview.\n * Transactions default to dry-run mode unless DEFI_PRIVATE_KEY is set and\n * broadcast is explicitly requested via the `broadcast` parameter.\n */\n\nimport \"dotenv/config\";\nimport { createRequire } from \"node:module\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { z } from \"zod\";\nimport { Registry, InterestRateMode } from \"@hypurrquant/defi-core\";\nimport { createLending, createDex, createVault, createLiquidStaking } from \"@hypurrquant/defi-protocols\";\nimport { Executor } from \"./executor.js\";\nimport type { Address } from \"viem\";\n\n// ── JSON envelope helpers ──\n\nfunction ok(data: unknown, meta?: Record<string, unknown>) {\n return JSON.stringify({ ok: true, data, meta }, null, 2);\n}\n\nfunction err(error: string, meta?: Record<string, unknown>) {\n return JSON.stringify({ ok: false, error, meta }, null, 2);\n}\n\n// ── Registry helper ──\n\nfunction getRegistry() {\n return Registry.loadEmbedded();\n}\n\nfunction resolveToken(registry: Registry, chainName: string, token: string): Address {\n if (token.startsWith(\"0x\")) return token as Address;\n return registry.resolveToken(chainName, token).address as Address;\n}\n\nfunction makeExecutor(broadcast: boolean, rpcUrl: string, explorerUrl?: string): Executor {\n return new Executor(broadcast, rpcUrl, explorerUrl);\n}\n\n// ── MCP Server ──\n\nconst _require = createRequire(import.meta.url);\nconst _pkg = _require(\"../package.json\") as { version: string };\n\nconst server = new McpServer(\n { name: \"defi-cli\", version: _pkg.version },\n { capabilities: { tools: {}, resources: {}, prompts: {} } },\n);\n\n// ============================================================\n// defi_status — chain and protocol status\n// ============================================================\n\nserver.tool(\n \"defi_status\",\n \"Show chain and protocol status: lists all protocols deployed on a chain with contract addresses and categories\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm). E.g. hyperevm, ethereum, arbitrum, base\"),\n },\n async ({ chain }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocols = registry.getProtocolsForChain(chainName);\n\n const data = {\n chain: chainName,\n chain_id: chainConfig.chain_id,\n rpc_url: chainConfig.effectiveRpcUrl(),\n protocols: protocols.map(p => ({\n slug: p.slug,\n name: p.name,\n category: p.category,\n interface: p.interface,\n contracts: p.contracts ?? {},\n })),\n summary: {\n total_protocols: protocols.length,\n },\n };\n\n return { content: [{ type: \"text\", text: ok(data, { chain: chainName }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e)) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_lending_rates — get lending rates for a protocol\n// ============================================================\n\nserver.tool(\n \"defi_lending_rates\",\n \"Get current supply and borrow rates for an asset on a lending protocol (e.g. Aave V3)\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n protocol: z.string().describe(\"Protocol slug, e.g. aave-v3, felix\"),\n asset: z.string().describe(\"Token symbol (e.g. USDC) or address (0x...)\"),\n },\n async ({ chain, protocol, asset }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocolConfig = registry.getProtocol(protocol);\n const adapter = createLending(protocolConfig, chainConfig.effectiveRpcUrl());\n const assetAddr = resolveToken(registry, chainName, asset);\n const rates = await adapter.getRates(assetAddr);\n return { content: [{ type: \"text\", text: ok(rates, { chain: chainName, protocol, asset }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { protocol, asset }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_lending_supply — supply to lending protocol\n// ============================================================\n\nserver.tool(\n \"defi_lending_supply\",\n \"Supply an asset to a lending protocol. Defaults to dry-run (no broadcast). Set broadcast=true to send transaction (requires DEFI_PRIVATE_KEY env var)\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n protocol: z.string().describe(\"Protocol slug, e.g. aave-v3\"),\n asset: z.string().describe(\"Token symbol or address\"),\n amount: z.string().describe(\"Amount in wei (as string to avoid precision loss)\"),\n on_behalf_of: z.string().optional().describe(\"Supply on behalf of this address (default: DEFI_WALLET_ADDRESS env var)\"),\n broadcast: z.boolean().optional().describe(\"Set true to broadcast the transaction (default: false = dry run)\"),\n },\n async ({ chain, protocol, asset, amount, on_behalf_of, broadcast }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocolConfig = registry.getProtocol(protocol);\n const adapter = createLending(protocolConfig, chainConfig.effectiveRpcUrl());\n const assetAddr = resolveToken(registry, chainName, asset);\n const onBehalfOf = (on_behalf_of ?? process.env[\"DEFI_WALLET_ADDRESS\"] ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildSupply({ protocol: protocolConfig.name, asset: assetAddr, amount: BigInt(amount), on_behalf_of: onBehalfOf });\n const executor = makeExecutor(broadcast ?? false, chainConfig.effectiveRpcUrl(), chainConfig.explorer_url);\n const result = await executor.execute(tx);\n return { content: [{ type: \"text\", text: ok(result, { chain: chainName, protocol, asset, broadcast: broadcast ?? false }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { protocol, asset }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_lending_withdraw — withdraw from lending protocol\n// ============================================================\n\nserver.tool(\n \"defi_lending_withdraw\",\n \"Withdraw a supplied asset from a lending protocol. Defaults to dry-run. Set broadcast=true to send transaction\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n protocol: z.string().describe(\"Protocol slug, e.g. aave-v3\"),\n asset: z.string().describe(\"Token symbol or address\"),\n amount: z.string().describe(\"Amount in wei to withdraw\"),\n to: z.string().optional().describe(\"Recipient address (default: DEFI_WALLET_ADDRESS)\"),\n broadcast: z.boolean().optional().describe(\"Set true to broadcast (default: false)\"),\n },\n async ({ chain, protocol, asset, amount, to, broadcast }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocolConfig = registry.getProtocol(protocol);\n const adapter = createLending(protocolConfig, chainConfig.effectiveRpcUrl());\n const assetAddr = resolveToken(registry, chainName, asset);\n const toAddr = (to ?? process.env[\"DEFI_WALLET_ADDRESS\"] ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildWithdraw({ protocol: protocolConfig.name, asset: assetAddr, amount: BigInt(amount), to: toAddr });\n const executor = makeExecutor(broadcast ?? false, chainConfig.effectiveRpcUrl(), chainConfig.explorer_url);\n const result = await executor.execute(tx);\n return { content: [{ type: \"text\", text: ok(result, { chain: chainName, protocol, asset, broadcast: broadcast ?? false }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { protocol, asset }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_dex_quote — get swap quote\n// ============================================================\n\nserver.tool(\n \"defi_dex_quote\",\n \"Get a DEX swap quote without executing. Returns expected output amount and price impact\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n protocol: z.string().describe(\"Protocol slug, e.g. uniswap-v3, algebra-v3\"),\n token_in: z.string().describe(\"Input token symbol or address\"),\n token_out: z.string().describe(\"Output token symbol or address\"),\n amount_in: z.string().describe(\"Amount of input token in wei\"),\n },\n async ({ chain, protocol, token_in, token_out, amount_in }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocolConfig = registry.getProtocol(protocol);\n const adapter = createDex(protocolConfig, chainConfig.effectiveRpcUrl());\n const tokenIn = resolveToken(registry, chainName, token_in);\n const tokenOut = resolveToken(registry, chainName, token_out);\n const result = await adapter.quote({ protocol: protocolConfig.name, token_in: tokenIn, token_out: tokenOut, amount_in: BigInt(amount_in) });\n return { content: [{ type: \"text\", text: ok(result, { chain: chainName, protocol, token_in, token_out }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { protocol, token_in, token_out }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_dex_swap — execute swap\n// ============================================================\n\nserver.tool(\n \"defi_dex_swap\",\n \"Execute a token swap on a DEX. Defaults to dry-run. Set broadcast=true to send transaction\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n protocol: z.string().describe(\"Protocol slug, e.g. uniswap-v3\"),\n token_in: z.string().describe(\"Input token symbol or address\"),\n token_out: z.string().describe(\"Output token symbol or address\"),\n amount_in: z.string().describe(\"Amount of input token in wei\"),\n slippage_bps: z.number().optional().describe(\"Slippage tolerance in basis points (default: 50 = 0.5%)\"),\n recipient: z.string().optional().describe(\"Recipient address (default: DEFI_WALLET_ADDRESS)\"),\n broadcast: z.boolean().optional().describe(\"Set true to broadcast (default: false)\"),\n },\n async ({ chain, protocol, token_in, token_out, amount_in, slippage_bps, recipient, broadcast }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocolConfig = registry.getProtocol(protocol);\n const adapter = createDex(protocolConfig, chainConfig.effectiveRpcUrl());\n const tokenIn = resolveToken(registry, chainName, token_in);\n const tokenOut = resolveToken(registry, chainName, token_out);\n const recipientAddr = (recipient ?? process.env[\"DEFI_WALLET_ADDRESS\"] ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildSwap({\n protocol: protocolConfig.name,\n token_in: tokenIn,\n token_out: tokenOut,\n amount_in: BigInt(amount_in),\n slippage: { bps: slippage_bps ?? 50 },\n recipient: recipientAddr,\n });\n const executor = makeExecutor(broadcast ?? false, chainConfig.effectiveRpcUrl(), chainConfig.explorer_url);\n const result = await executor.execute(tx);\n return { content: [{ type: \"text\", text: ok(result, { chain: chainName, protocol, token_in, token_out, broadcast: broadcast ?? false }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { protocol, token_in, token_out }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_dex_lp_add — add liquidity\n// ============================================================\n\nserver.tool(\n \"defi_dex_lp_add\",\n \"Add liquidity to a DEX pool. Defaults to dry-run. Set broadcast=true to send transaction\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n protocol: z.string().describe(\"Protocol slug, e.g. uniswap-v3\"),\n token_a: z.string().describe(\"First token symbol or address\"),\n token_b: z.string().describe(\"Second token symbol or address\"),\n amount_a: z.string().describe(\"Amount of token A in wei\"),\n amount_b: z.string().describe(\"Amount of token B in wei\"),\n recipient: z.string().optional().describe(\"Recipient address for LP tokens\"),\n broadcast: z.boolean().optional().describe(\"Set true to broadcast (default: false)\"),\n },\n async ({ chain, protocol, token_a, token_b, amount_a, amount_b, recipient, broadcast }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocolConfig = registry.getProtocol(protocol);\n const adapter = createDex(protocolConfig, chainConfig.effectiveRpcUrl());\n const tokenA = resolveToken(registry, chainName, token_a);\n const tokenB = resolveToken(registry, chainName, token_b);\n const recipientAddr = (recipient ?? process.env[\"DEFI_WALLET_ADDRESS\"] ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildAddLiquidity({\n protocol: protocolConfig.name,\n token_a: tokenA,\n token_b: tokenB,\n amount_a: BigInt(amount_a),\n amount_b: BigInt(amount_b),\n recipient: recipientAddr,\n });\n const executor = makeExecutor(broadcast ?? false, chainConfig.effectiveRpcUrl(), chainConfig.explorer_url);\n const result = await executor.execute(tx);\n return { content: [{ type: \"text\", text: ok(result, { chain: chainName, protocol, token_a, token_b, broadcast: broadcast ?? false }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { protocol }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_dex_lp_remove — remove liquidity\n// ============================================================\n\nserver.tool(\n \"defi_dex_lp_remove\",\n \"Remove liquidity from a DEX pool. Defaults to dry-run. Set broadcast=true to send transaction\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n protocol: z.string().describe(\"Protocol slug, e.g. uniswap-v3\"),\n token_a: z.string().describe(\"First token symbol or address\"),\n token_b: z.string().describe(\"Second token symbol or address\"),\n liquidity: z.string().describe(\"Liquidity amount to remove in wei\"),\n recipient: z.string().optional().describe(\"Recipient address for returned tokens\"),\n broadcast: z.boolean().optional().describe(\"Set true to broadcast (default: false)\"),\n },\n async ({ chain, protocol, token_a, token_b, liquidity, recipient, broadcast }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocolConfig = registry.getProtocol(protocol);\n const adapter = createDex(protocolConfig, chainConfig.effectiveRpcUrl());\n const tokenA = resolveToken(registry, chainName, token_a);\n const tokenB = resolveToken(registry, chainName, token_b);\n const recipientAddr = (recipient ?? process.env[\"DEFI_WALLET_ADDRESS\"] ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildRemoveLiquidity({\n protocol: protocolConfig.name,\n token_a: tokenA,\n token_b: tokenB,\n liquidity: BigInt(liquidity),\n recipient: recipientAddr,\n });\n const executor = makeExecutor(broadcast ?? false, chainConfig.effectiveRpcUrl(), chainConfig.explorer_url);\n const result = await executor.execute(tx);\n return { content: [{ type: \"text\", text: ok(result, { chain: chainName, protocol, token_a, token_b, broadcast: broadcast ?? false }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { protocol }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_bridge — cross-chain bridge quote\n// ============================================================\n\nserver.tool(\n \"defi_bridge\",\n \"Get a cross-chain bridge quote via LI.FI, deBridge DLN, or Circle CCTP. Returns estimated output amount and fees\",\n {\n from_chain: z.string().describe(\"Source chain name, e.g. ethereum, arbitrum, base\"),\n to_chain: z.string().describe(\"Destination chain name, e.g. hyperevm, arbitrum\"),\n token: z.string().optional().describe(\"Token symbol to bridge (default: USDC). Use native for native token\"),\n amount: z.string().describe(\"Amount in human-readable units, e.g. '100' for 100 USDC\"),\n recipient: z.string().optional().describe(\"Recipient address on destination chain\"),\n },\n async ({ from_chain, to_chain, token, amount, recipient }) => {\n try {\n const tokenSymbol = token ?? \"USDC\";\n const recipientAddr = recipient ?? process.env[\"DEFI_WALLET_ADDRESS\"] ?? \"0x0000000000000000000000000000000000000001\";\n\n // Use LI.FI API for a quote\n const LIFI_API = \"https://li.quest/v1\";\n const registry = getRegistry();\n\n let fromChainId: number | undefined;\n let toChainId: number | undefined;\n try {\n fromChainId = registry.getChain(from_chain).chain_id;\n } catch { /* use name */ }\n try {\n toChainId = registry.getChain(to_chain).chain_id;\n } catch { /* use name */ }\n\n const params = new URLSearchParams({\n fromChain: fromChainId ? String(fromChainId) : from_chain,\n toChain: toChainId ? String(toChainId) : to_chain,\n fromToken: tokenSymbol,\n toToken: tokenSymbol,\n fromAmount: String(Math.round(parseFloat(amount) * 1e6)), // USDC decimals\n toAddress: recipientAddr,\n });\n\n const res = await fetch(`${LIFI_API}/quote?${params}`, {\n headers: { Accept: \"application/json\" },\n });\n\n if (!res.ok) {\n const text = await res.text();\n throw new Error(`LI.FI quote failed (${res.status}): ${text.slice(0, 200)}`);\n }\n\n const data = await res.json() as Record<string, unknown>;\n const estimate = data.estimate as Record<string, unknown> | undefined;\n\n const quote = {\n from_chain,\n to_chain,\n token: tokenSymbol,\n amount_in: amount,\n amount_out: estimate?.toAmount ? String(Number(estimate.toAmount as string) / 1e6) : \"unknown\",\n fee_costs: estimate?.feeCosts ?? [],\n gas_costs: estimate?.gasCosts ?? [],\n execution_duration_seconds: estimate?.executionDuration ?? \"unknown\",\n tool: (data.tool as string) ?? \"unknown\",\n raw: data,\n };\n\n return { content: [{ type: \"text\", text: ok(quote, { from_chain, to_chain, token: tokenSymbol }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { from_chain, to_chain }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_vault_info — vault information\n// ============================================================\n\nserver.tool(\n \"defi_vault_info\",\n \"Get vault information: TVL, APY, total shares, and underlying asset details\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n protocol: z.string().describe(\"Protocol slug for the vault\"),\n },\n async ({ chain, protocol }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocolConfig = registry.getProtocol(protocol);\n const adapter = createVault(protocolConfig, chainConfig.effectiveRpcUrl());\n const info = await adapter.getVaultInfo();\n return { content: [{ type: \"text\", text: ok(info, { chain: chainName, protocol }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { protocol }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_staking_info — staking information\n// ============================================================\n\nserver.tool(\n \"defi_staking_info\",\n \"Get liquid staking protocol info: exchange rate, APY, total staked\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n protocol: z.string().describe(\"Protocol slug for the staking protocol\"),\n },\n async ({ chain, protocol }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocolConfig = registry.getProtocol(protocol);\n const adapter = createLiquidStaking(protocolConfig, chainConfig.effectiveRpcUrl());\n const info = await adapter.getInfo();\n return { content: [{ type: \"text\", text: ok(info, { chain: chainName, protocol }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { protocol }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_price — asset price query\n// ============================================================\n\nserver.tool(\n \"defi_price\",\n \"Query asset price from on-chain oracles (Aave V3) and/or DEX spot prices\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n asset: z.string().describe(\"Token symbol (e.g. WBTC) or address (0x...)\"),\n source: z.enum([\"oracle\", \"dex\", \"all\"]).optional().describe(\"Price source: oracle, dex, or all (default: all)\"),\n },\n async ({ chain, asset, source }) => {\n try {\n const chainName = (chain ?? \"hyperevm\").toLowerCase();\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const rpcUrl = chainConfig.effectiveRpcUrl();\n const srcMode = source ?? \"all\";\n\n let assetAddr: Address;\n let assetSymbol: string;\n try {\n if (/^0x[0-9a-fA-F]{40}$/.test(asset)) {\n assetAddr = asset as Address;\n assetSymbol = asset;\n } else {\n const token = registry.resolveToken(chainName, asset);\n assetAddr = token.address as Address;\n assetSymbol = token.symbol;\n }\n } catch (e) {\n return { content: [{ type: \"text\", text: err(`Could not resolve asset: ${asset}`) }], isError: true };\n }\n\n const { ProtocolCategory } = await import(\"@hypurrquant/defi-core\");\n const { createOracleFromLending } = await import(\"@hypurrquant/defi-protocols\");\n\n const prices: Array<{ source: string; source_type: string; price: number }> = [];\n\n if (srcMode === \"all\" || srcMode === \"oracle\") {\n const lendingProtos = registry.getProtocolsForChain(chainName)\n .filter(p => p.category === ProtocolCategory.Lending);\n await Promise.all(lendingProtos.map(async (p) => {\n try {\n const oracle = createOracleFromLending(p, rpcUrl);\n const price = await oracle.getPrice(assetAddr);\n if (price.price_f64 > 0) prices.push({ source: p.slug, source_type: \"oracle\", price: price.price_f64 });\n } catch { /* skip */ }\n }));\n }\n\n if (srcMode === \"all\" || srcMode === \"dex\") {\n const { DexSpotPrice } = await import(\"@hypurrquant/defi-protocols\");\n const USDC_SYMBOL = \"USDC\";\n let usdcAddr: Address | undefined;\n let usdcDecimals = 6;\n try {\n const usdcToken = registry.resolveToken(chainName, USDC_SYMBOL);\n usdcAddr = usdcToken.address as Address;\n usdcDecimals = usdcToken.decimals;\n } catch { /* no USDC on chain */ }\n\n // Determine asset decimals from registry if resolved by symbol, else default 18\n let assetDecimals = 18;\n if (!/^0x[0-9a-fA-F]{40}$/.test(asset)) {\n try { assetDecimals = registry.resolveToken(chainName, asset).decimals; } catch { /* default 18 */ }\n }\n\n if (usdcAddr && assetAddr.toLowerCase() !== usdcAddr.toLowerCase()) {\n const dexProtos = registry.getProtocolsForChain(chainName)\n .filter(p => p.category === ProtocolCategory.Dex);\n await Promise.all(dexProtos.map(async (p) => {\n try {\n const dex = createDex(p, rpcUrl);\n const priceData = await DexSpotPrice.getPrice(dex, assetAddr, assetDecimals, usdcAddr!, usdcDecimals);\n if (priceData.price_f64 > 0) prices.push({ source: p.slug, source_type: \"dex\", price: priceData.price_f64 });\n } catch { /* skip */ }\n }));\n }\n }\n\n if (prices.length === 0) {\n return { content: [{ type: \"text\", text: err(`No price data found for ${assetSymbol} on ${chainName}`) }], isError: true };\n }\n\n const priceValues = prices.map(p => p.price);\n const avg = priceValues.reduce((a, b) => a + b, 0) / priceValues.length;\n const min = Math.min(...priceValues);\n const max = Math.max(...priceValues);\n const spread = max > 0 ? ((max - min) / max) * 100 : 0;\n\n const report = {\n asset: assetSymbol,\n asset_address: assetAddr,\n prices,\n average_price: Math.round(avg * 100) / 100,\n max_spread_pct: Math.round(spread * 100) / 100,\n };\n\n return { content: [{ type: \"text\", text: ok(report, { chain: chainName, asset: assetSymbol, source: srcMode }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { asset }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_scan — exploit / price manipulation detection\n// ============================================================\n\nserver.tool(\n \"defi_scan\",\n \"Scan for potential price manipulation or exploit opportunities by comparing oracle prices vs DEX spot prices across lending protocols\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n min_spread_pct: z.number().optional().describe(\"Minimum oracle-vs-dex spread % to flag (default: 5)\"),\n },\n async ({ chain, min_spread_pct }) => {\n try {\n const chainName = (chain ?? \"hyperevm\").toLowerCase();\n const minSpread = min_spread_pct ?? 5;\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const rpcUrl = chainConfig.effectiveRpcUrl();\n\n const { ProtocolCategory } = await import(\"@hypurrquant/defi-core\");\n const { createOracleFromLending, DexSpotPrice } = await import(\"@hypurrquant/defi-protocols\");\n\n const tokens = registry.tokens.get(chainName) ?? [];\n const lendingProtos = registry.getProtocolsForChain(chainName)\n .filter(p => p.category === ProtocolCategory.Lending);\n const dexProtos = registry.getProtocolsForChain(chainName)\n .filter(p => p.category === ProtocolCategory.Dex);\n\n let usdcAddr: Address | undefined;\n try {\n usdcAddr = registry.resolveToken(chainName, \"USDC\").address as Address;\n } catch { /* no USDC */ }\n\n const findings: Array<{\n token: string;\n address: string;\n oracle_price: number;\n dex_price: number;\n spread_pct: number;\n verdict: string;\n }> = [];\n\n for (const token of tokens.slice(0, 20)) {\n const addr = token.address as Address;\n if (!usdcAddr || addr.toLowerCase() === usdcAddr.toLowerCase()) continue;\n\n let oraclePrice = 0;\n let dexPrice = 0;\n\n for (const p of lendingProtos) {\n try {\n const oracle = createOracleFromLending(p, rpcUrl);\n const priceData = await oracle.getPrice(addr);\n if (priceData.price_f64 > 0) { oraclePrice = priceData.price_f64; break; }\n } catch { /* skip */ }\n }\n\n for (const p of dexProtos) {\n try {\n const dex = createDex(p, rpcUrl);\n const priceData = await DexSpotPrice.getPrice(dex, addr, token.decimals, usdcAddr!, 6);\n if (priceData.price_f64 > 0) { dexPrice = priceData.price_f64; break; }\n } catch { /* skip */ }\n }\n\n if (oraclePrice > 0 && dexPrice > 0) {\n const spread = Math.abs(oraclePrice - dexPrice) / Math.max(oraclePrice, dexPrice) * 100;\n if (spread >= minSpread) {\n findings.push({\n token: token.symbol,\n address: addr,\n oracle_price: Math.round(oraclePrice * 10000) / 10000,\n dex_price: Math.round(dexPrice * 10000) / 10000,\n spread_pct: Math.round(spread * 100) / 100,\n verdict: spread >= 20 ? \"HIGH_RISK\" : spread >= 10 ? \"MEDIUM_RISK\" : \"LOW_RISK\",\n });\n }\n }\n }\n\n findings.sort((a, b) => b.spread_pct - a.spread_pct);\n\n return {\n content: [{\n type: \"text\",\n text: ok(\n { chain: chainName, findings, scanned_tokens: Math.min(tokens.length, 20), min_spread_pct: minSpread },\n { finding_count: findings.length },\n ),\n }],\n };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e)) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_portfolio — portfolio overview\n// ============================================================\n\nserver.tool(\n \"defi_portfolio\",\n \"Get a portfolio overview for a wallet address: lending positions, token balances, and health factors across all protocols on a chain\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n address: z.string().describe(\"Wallet address to query (0x...)\"),\n },\n async ({ chain, address }) => {\n try {\n const chainName = (chain ?? \"hyperevm\").toLowerCase();\n\n if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {\n return { content: [{ type: \"text\", text: err(`Invalid address: ${address}`) }], isError: true };\n }\n\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const rpcUrl = chainConfig.effectiveRpcUrl();\n const user = address as Address;\n\n const { ProtocolCategory, multicallRead } = await import(\"@hypurrquant/defi-core\");\n const { createLending: _createLending } = await import(\"@hypurrquant/defi-protocols\");\n const { encodeFunctionData, parseAbi } = await import(\"viem\");\n\n const POOL_ABI = parseAbi([\n \"function getUserAccountData(address user) external view returns (uint256 totalCollateralBase, uint256 totalDebtBase, uint256 availableBorrowsBase, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)\",\n ]);\n\n const lendingProtos = registry.getProtocolsForChain(chainName)\n .filter(p => p.category === ProtocolCategory.Lending);\n\n const lendingPositions: Array<{\n protocol: string;\n total_collateral_usd: number;\n total_debt_usd: number;\n available_borrows_usd: number;\n health_factor: number;\n ltv: number;\n }> = [];\n\n for (const p of lendingProtos) {\n const poolAddr = (p.contracts as Record<string, string> | undefined)?.pool;\n if (!poolAddr) continue;\n try {\n const callData = encodeFunctionData({ abi: POOL_ABI, functionName: \"getUserAccountData\", args: [user] });\n const results = await multicallRead(rpcUrl, [[poolAddr as Address, callData as `0x${string}`]]);\n const raw = results[0];\n if (!raw || raw.length < 2 + 6 * 64) continue;\n const hex = raw.slice(2);\n const decodeU256 = (offset: number) => BigInt(\"0x\" + hex.slice(offset * 64, offset * 64 + 64));\n const totalCollateral = Number(decodeU256(0)) / 1e8;\n const totalDebt = Number(decodeU256(1)) / 1e8;\n const availableBorrows = Number(decodeU256(2)) / 1e8;\n const ltv = Number(decodeU256(4)) / 100;\n const hfRaw = decodeU256(5);\n const healthFactor = hfRaw >= BigInt(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\") / 2n\n ? 999999\n : Math.round(Number(hfRaw) / 1e16) / 100;\n\n if (totalCollateral > 0 || totalDebt > 0) {\n lendingPositions.push({\n protocol: p.slug,\n total_collateral_usd: Math.round(totalCollateral * 100) / 100,\n total_debt_usd: Math.round(totalDebt * 100) / 100,\n available_borrows_usd: Math.round(availableBorrows * 100) / 100,\n health_factor: healthFactor,\n ltv,\n });\n }\n } catch { /* skip */ }\n }\n\n const totalCollateralUsd = lendingPositions.reduce((s, p) => s + p.total_collateral_usd, 0);\n const totalDebtUsd = lendingPositions.reduce((s, p) => s + p.total_debt_usd, 0);\n\n const portfolio = {\n address,\n chain: chainName,\n lending_positions: lendingPositions,\n summary: {\n total_collateral_usd: Math.round(totalCollateralUsd * 100) / 100,\n total_debt_usd: Math.round(totalDebtUsd * 100) / 100,\n net_position_usd: Math.round((totalCollateralUsd - totalDebtUsd) * 100) / 100,\n active_protocols: lendingPositions.length,\n },\n };\n\n return { content: [{ type: \"text\", text: ok(portfolio, { chain: chainName, address }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { address }) }], isError: true };\n }\n },\n);\n\n// ── Start server ──\n\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\n","import { createPublicClient, createWalletClient, http } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type { ActionResult, DeFiTx, TxStatus } from \"@hypurrquant/defi-core\";\n\n/** Gas buffer multiplier: 120% over estimated gas (20% headroom) */\nconst GAS_BUFFER_BPS = 12000n;\n\n/** Default max priority fee (tip) in wei — 0.1 gwei */\nconst DEFAULT_PRIORITY_FEE_WEI = 100_000_000n;\n\nexport class Executor {\n readonly dryRun: boolean;\n readonly rpcUrl: string | undefined;\n readonly explorerUrl: string | undefined;\n\n constructor(broadcast: boolean, rpcUrl?: string, explorerUrl?: string) {\n this.dryRun = !broadcast;\n this.rpcUrl = rpcUrl;\n this.explorerUrl = explorerUrl;\n }\n\n /** Apply 20% buffer to a gas estimate */\n private static applyGasBuffer(gas: bigint): bigint {\n return (gas * GAS_BUFFER_BPS) / 10000n;\n }\n\n /** Fetch EIP-1559 fee params from the network. Returns [maxFeePerGas, maxPriorityFeePerGas]. */\n private async fetchEip1559Fees(rpcUrl: string): Promise<[bigint, bigint]> {\n try {\n const client = createPublicClient({ transport: http(rpcUrl) });\n const gasPrice = await client.getGasPrice();\n let priorityFee = DEFAULT_PRIORITY_FEE_WEI;\n try {\n priorityFee = await client.estimateMaxPriorityFeePerGas();\n } catch {\n // fallback to default\n }\n const maxFee = gasPrice * 2n + priorityFee;\n return [maxFee, priorityFee];\n } catch {\n return [0n, 0n];\n }\n }\n\n /** Estimate gas dynamically with buffer, falling back to a hardcoded estimate */\n private async estimateGasWithBuffer(\n rpcUrl: string,\n tx: DeFiTx,\n from: `0x${string}`,\n ): Promise<bigint> {\n try {\n const client = createPublicClient({ transport: http(rpcUrl) });\n const estimated = await client.estimateGas({\n to: tx.to,\n data: tx.data,\n value: tx.value,\n account: from,\n });\n if (estimated > 0n) return Executor.applyGasBuffer(estimated);\n } catch {\n // fallback\n }\n return tx.gas_estimate ? BigInt(tx.gas_estimate) : 0n;\n }\n\n /** Simulate a transaction via eth_call + eth_estimateGas */\n private async simulate(tx: DeFiTx): Promise<ActionResult> {\n const rpcUrl = this.rpcUrl;\n if (!rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL — cannot simulate. Set HYPEREVM_RPC_URL.\");\n }\n\n const client = createPublicClient({ transport: http(rpcUrl) });\n\n const privateKey = process.env[\"DEFI_PRIVATE_KEY\"];\n const from: `0x${string}` = privateKey\n ? privateKeyToAccount(privateKey as `0x${string}`).address\n : \"0x0000000000000000000000000000000000000001\";\n\n try {\n await client.call({ to: tx.to, data: tx.data, value: tx.value, account: from });\n\n const gasEstimate = await this.estimateGasWithBuffer(rpcUrl, tx, from);\n const [maxFee, priorityFee] = await this.fetchEip1559Fees(rpcUrl);\n\n return {\n tx_hash: undefined,\n status: \"simulated\" as TxStatus,\n gas_used: gasEstimate > 0n ? Number(gasEstimate) : undefined,\n description: tx.description,\n details: {\n to: tx.to,\n from,\n data: tx.data,\n value: tx.value.toString(),\n gas_estimate: gasEstimate.toString(),\n max_fee_per_gas_gwei: (Number(maxFee) / 1e9).toFixed(4),\n max_priority_fee_gwei: (Number(priorityFee) / 1e9).toFixed(4),\n mode: \"simulated\",\n result: \"success\",\n },\n };\n } catch (e: unknown) {\n const errMsg = String(e);\n const revertReason = extractRevertReason(errMsg);\n\n return {\n tx_hash: undefined,\n status: \"simulation_failed\" as TxStatus,\n gas_used: tx.gas_estimate,\n description: tx.description,\n details: {\n to: tx.to,\n from,\n data: tx.data,\n value: tx.value.toString(),\n mode: \"simulated\",\n result: \"revert\",\n revert_reason: revertReason,\n },\n };\n }\n }\n\n async execute(tx: DeFiTx): Promise<ActionResult> {\n if (this.dryRun) {\n if (this.rpcUrl) {\n return this.simulate(tx);\n }\n\n return {\n tx_hash: undefined,\n status: \"dry_run\" as TxStatus,\n gas_used: tx.gas_estimate,\n description: tx.description,\n details: {\n to: tx.to,\n data: tx.data,\n value: tx.value.toString(),\n mode: \"dry_run\",\n },\n };\n }\n\n // === Broadcast mode ===\n const privateKey = process.env[\"DEFI_PRIVATE_KEY\"];\n if (!privateKey) {\n throw DefiError.invalidParam(\n \"DEFI_PRIVATE_KEY environment variable not set. Required for --broadcast.\",\n );\n }\n\n const account = privateKeyToAccount(privateKey as `0x${string}`);\n\n const rpcUrl = this.rpcUrl;\n if (!rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL configured for broadcasting\");\n }\n\n const publicClient = createPublicClient({ transport: http(rpcUrl) });\n const walletClient = createWalletClient({ account, transport: http(rpcUrl) });\n\n // Dynamic gas estimation with buffer\n const gasLimit = await this.estimateGasWithBuffer(rpcUrl, tx, account.address);\n\n // EIP-1559 gas pricing\n const [maxFeePerGas, maxPriorityFeePerGas] = await this.fetchEip1559Fees(rpcUrl);\n\n process.stderr.write(`Broadcasting transaction to ${rpcUrl}...\\n`);\n if (gasLimit > 0n) {\n process.stderr.write(` Gas limit: ${gasLimit} (with 20% buffer)\\n`);\n }\n\n const txHash = await walletClient.sendTransaction({\n chain: null,\n to: tx.to,\n data: tx.data,\n value: tx.value,\n gas: gasLimit > 0n ? gasLimit : undefined,\n maxFeePerGas: maxFeePerGas > 0n ? maxFeePerGas : undefined,\n maxPriorityFeePerGas: maxPriorityFeePerGas > 0n ? maxPriorityFeePerGas : undefined,\n });\n\n const txUrl = this.explorerUrl ? `${this.explorerUrl}/tx/${txHash}` : undefined;\n process.stderr.write(`Transaction sent: ${txHash}\\n`);\n if (txUrl) process.stderr.write(`Explorer: ${txUrl}\\n`);\n process.stderr.write(\"Waiting for confirmation...\\n\");\n\n const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash });\n\n const status = receipt.status === \"success\" ? \"confirmed\" : \"failed\";\n\n return {\n tx_hash: txHash,\n status: status as TxStatus,\n gas_used: receipt.gasUsed ? Number(receipt.gasUsed) : undefined,\n description: tx.description,\n details: {\n to: tx.to,\n from: account.address,\n block_number: receipt.blockNumber?.toString(),\n gas_limit: gasLimit.toString(),\n gas_used: receipt.gasUsed?.toString(),\n explorer_url: txUrl,\n mode: \"broadcast\",\n },\n };\n }\n}\n\n/** Extract a human-readable revert reason from an RPC error message */\nfunction extractRevertReason(err: string): string {\n for (const marker of [\"execution reverted:\", \"revert:\", \"Error(\"]) {\n const pos = err.indexOf(marker);\n if (pos !== -1) return err.slice(pos);\n }\n return err.length > 200 ? err.slice(0, 200) + \"...\" : err;\n}\n"],"mappings":";;;;;;;;;;;;;AA2BA,SAAS,kBAAkB,QAAQ,KAAK;AACpC,MAAI,QAAQ,OAAO,MAAM,GAAG,GAAG,EAAE,MAAM,aAAa;AACpD,SAAO,CAAC,MAAM,QAAQ,MAAM,IAAI,EAAE,SAAS,CAAC;AAChD;AACA,SA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AAM,qBAAqB,GAAG,IAAI;AAAA,UAC7D,gBAAgB,KAAK,MAAM,eAAe,GAAG,IAAI;AAAA,UACjD,kBAAkB,KAAK,OAAO,qBAAqB,gBAAgB,GAAG,IAAI;AAAA,UAC1E,kBAAkB,iBAAiB;AAAA,QACrC;AAAA,MACF;AAEA,aAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,GAAG,WAAW,EAAE,OAAO,WAAW,QAAQ,CAAC,EAAE,CAAC,EAAE;AAAA,IAC3F,SAAS,GAAG;AACV,aAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,IAAI,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,GAAG,EAAE,QAAQ,CAAC,EAAE,CAAC,GAAG,SAAS,KAAK;AAAA,IAC1H;AAAA,EACF;AACF;AAIA,IAAM,YAAY,IAAI,qBAAqB;AAC3C,MAAM,OAAO,QAAQ,SAAS;","names":["endPtr","encodeFunctionData","parseAbi","TxStatus","InterestRateMode","ProtocolCategory","encodeFunctionData","parseAbi","createPublicClient","http","decodeFunctionResult","decodeAbiParameters","zeroAddress","u256ToF64","DefiError","abi","POOL_ABI","ERC20_ABI","ORACLE_ABI","SECONDS_PER_YEAR","init_dist","client","amountOut","best","result","data","InterestRateMode","init_dist","init_dist","createPublicClient","http","err","ProtocolCategory","createOracleFromLending","DexSpotPrice","multicallRead","encodeFunctionData","parseAbi","POOL_ABI","decodeU256"]}
1
+ {"version":3,"sources":["../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/error.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/util.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/date.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/primitive.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/extract.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/struct.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/parse.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/stringify.js","../../../node_modules/.pnpm/smol-toml@1.6.0/node_modules/smol-toml/dist/index.js","../../defi-core/src/types.ts","../../defi-core/src/error.ts","../../defi-core/src/json.ts","../../defi-core/src/erc20.ts","../../defi-core/src/provider.ts","../../defi-core/src/multicall.ts","../../defi-core/src/registry/chain.ts","../../defi-core/src/registry/protocol.ts","../../defi-core/src/registry/registry.ts","../../defi-protocols/src/factory.ts","../../defi-protocols/src/dex/uniswap_v3.ts","../../defi-protocols/src/dex/uniswap_v2.ts","../../defi-protocols/src/dex/algebra_v3.ts","../../defi-protocols/src/dex/balancer_v3.ts","../../defi-protocols/src/dex/curve.ts","../../defi-protocols/src/dex/solidly.ts","../../defi-protocols/src/dex/woofi.ts","../../defi-protocols/src/dex/solidly_gauge.ts","../../defi-protocols/src/dex/masterchef.ts","../../defi-protocols/src/lending/aave_v3.ts","../../defi-protocols/src/lending/aave_v2.ts","../../defi-protocols/src/lending/aave_oracle.ts","../../defi-protocols/src/lending/compound_v2.ts","../../defi-protocols/src/lending/compound_v3.ts","../../defi-protocols/src/lending/euler_v2.ts","../../defi-protocols/src/lending/morpho.ts","../../defi-protocols/src/cdp/felix.ts","../../defi-protocols/src/cdp/felix_oracle.ts","../../defi-protocols/src/vault/erc4626.ts","../../defi-protocols/src/liquid_staking/generic_lst.ts","../../defi-protocols/src/liquid_staking/sthype.ts","../../defi-protocols/src/liquid_staking/kinetiq.ts","../../defi-protocols/src/yield_source/pendle.ts","../../defi-protocols/src/yield_source/generic_yield.ts","../../defi-protocols/src/derivatives/hlp.ts","../../defi-protocols/src/derivatives/generic_derivatives.ts","../../defi-protocols/src/options/rysk.ts","../../defi-protocols/src/options/generic_options.ts","../../defi-protocols/src/nft/erc721.ts","../../defi-protocols/src/dex/dex_price.ts","../src/mcp-server.ts","../src/executor.ts"],"sourcesContent":["/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nfunction getLineColFromPtr(string, ptr) {\n let lines = string.slice(0, ptr).split(/\\r\\n|\\n|\\r/g);\n return [lines.length, lines.pop().length + 1];\n}\nfunction makeCodeBlock(string, line, column) {\n let lines = string.split(/\\r\\n|\\n|\\r/g);\n let codeblock = '';\n let numberLen = (Math.log10(line + 1) | 0) + 1;\n for (let i = line - 1; i <= line + 1; i++) {\n let l = lines[i - 1];\n if (!l)\n continue;\n codeblock += i.toString().padEnd(numberLen, ' ');\n codeblock += ': ';\n codeblock += l;\n codeblock += '\\n';\n if (i === line) {\n codeblock += ' '.repeat(numberLen + column + 2);\n codeblock += '^\\n';\n }\n }\n return codeblock;\n}\nexport class TomlError extends Error {\n line;\n column;\n codeblock;\n constructor(message, options) {\n const [line, column] = getLineColFromPtr(options.toml, options.ptr);\n const codeblock = makeCodeBlock(options.toml, line, column);\n super(`Invalid TOML document: ${message}\\n\\n${codeblock}`, options);\n this.line = line;\n this.column = column;\n this.codeblock = codeblock;\n }\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { TomlError } from './error.js';\nfunction isEscaped(str, ptr) {\n let i = 0;\n while (str[ptr - ++i] === '\\\\')\n ;\n return --i && (i % 2);\n}\nexport function indexOfNewline(str, start = 0, end = str.length) {\n let idx = str.indexOf('\\n', start);\n if (str[idx - 1] === '\\r')\n idx--;\n return idx <= end ? idx : -1;\n}\nexport function skipComment(str, ptr) {\n for (let i = ptr; i < str.length; i++) {\n let c = str[i];\n if (c === '\\n')\n return i;\n if (c === '\\r' && str[i + 1] === '\\n')\n return i + 1;\n if ((c < '\\x20' && c !== '\\t') || c === '\\x7f') {\n throw new TomlError('control characters are not allowed in comments', {\n toml: str,\n ptr: ptr,\n });\n }\n }\n return str.length;\n}\nexport function skipVoid(str, ptr, banNewLines, banComments) {\n let c;\n while ((c = str[ptr]) === ' ' || c === '\\t' || (!banNewLines && (c === '\\n' || c === '\\r' && str[ptr + 1] === '\\n')))\n ptr++;\n return banComments || c !== '#'\n ? ptr\n : skipVoid(str, skipComment(str, ptr), banNewLines);\n}\nexport function skipUntil(str, ptr, sep, end, banNewLines = false) {\n if (!end) {\n ptr = indexOfNewline(str, ptr);\n return ptr < 0 ? str.length : ptr;\n }\n for (let i = ptr; i < str.length; i++) {\n let c = str[i];\n if (c === '#') {\n i = indexOfNewline(str, i);\n }\n else if (c === sep) {\n return i + 1;\n }\n else if (c === end || (banNewLines && (c === '\\n' || (c === '\\r' && str[i + 1] === '\\n')))) {\n return i;\n }\n }\n throw new TomlError('cannot find end of structure', {\n toml: str,\n ptr: ptr\n });\n}\nexport function getStringEnd(str, seek) {\n let first = str[seek];\n let target = first === str[seek + 1] && str[seek + 1] === str[seek + 2]\n ? str.slice(seek, seek + 3)\n : first;\n seek += target.length - 1;\n do\n seek = str.indexOf(target, ++seek);\n while (seek > -1 && first !== \"'\" && isEscaped(str, seek));\n if (seek > -1) {\n seek += target.length;\n if (target.length > 1) {\n if (str[seek] === first)\n seek++;\n if (str[seek] === first)\n seek++;\n }\n }\n return seek;\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nlet DATE_TIME_RE = /^(\\d{4}-\\d{2}-\\d{2})?[T ]?(?:(\\d{2}):\\d{2}(?::\\d{2}(?:\\.\\d+)?)?)?(Z|[-+]\\d{2}:\\d{2})?$/i;\nexport class TomlDate extends Date {\n #hasDate = false;\n #hasTime = false;\n #offset = null;\n constructor(date) {\n let hasDate = true;\n let hasTime = true;\n let offset = 'Z';\n if (typeof date === 'string') {\n let match = date.match(DATE_TIME_RE);\n if (match) {\n if (!match[1]) {\n hasDate = false;\n date = `0000-01-01T${date}`;\n }\n hasTime = !!match[2];\n // Make sure to use T instead of a space. Breaks in case of extreme values otherwise.\n hasTime && date[10] === ' ' && (date = date.replace(' ', 'T'));\n // Do not allow rollover hours.\n if (match[2] && +match[2] > 23) {\n date = '';\n }\n else {\n offset = match[3] || null;\n date = date.toUpperCase();\n if (!offset && hasTime)\n date += 'Z';\n }\n }\n else {\n date = '';\n }\n }\n super(date);\n if (!isNaN(this.getTime())) {\n this.#hasDate = hasDate;\n this.#hasTime = hasTime;\n this.#offset = offset;\n }\n }\n isDateTime() {\n return this.#hasDate && this.#hasTime;\n }\n isLocal() {\n return !this.#hasDate || !this.#hasTime || !this.#offset;\n }\n isDate() {\n return this.#hasDate && !this.#hasTime;\n }\n isTime() {\n return this.#hasTime && !this.#hasDate;\n }\n isValid() {\n return this.#hasDate || this.#hasTime;\n }\n toISOString() {\n let iso = super.toISOString();\n // Local Date\n if (this.isDate())\n return iso.slice(0, 10);\n // Local Time\n if (this.isTime())\n return iso.slice(11, 23);\n // Local DateTime\n if (this.#offset === null)\n return iso.slice(0, -1);\n // Offset DateTime\n if (this.#offset === 'Z')\n return iso;\n // This part is quite annoying: JS strips the original timezone from the ISO string representation\n // Instead of using a \"modified\" date and \"Z\", we restore the representation \"as authored\"\n let offset = (+(this.#offset.slice(1, 3)) * 60) + +(this.#offset.slice(4, 6));\n offset = this.#offset[0] === '-' ? offset : -offset;\n let offsetDate = new Date(this.getTime() - (offset * 60e3));\n return offsetDate.toISOString().slice(0, -1) + this.#offset;\n }\n static wrapAsOffsetDateTime(jsDate, offset = 'Z') {\n let date = new TomlDate(jsDate);\n date.#offset = offset;\n return date;\n }\n static wrapAsLocalDateTime(jsDate) {\n let date = new TomlDate(jsDate);\n date.#offset = null;\n return date;\n }\n static wrapAsLocalDate(jsDate) {\n let date = new TomlDate(jsDate);\n date.#hasTime = false;\n date.#offset = null;\n return date;\n }\n static wrapAsLocalTime(jsDate) {\n let date = new TomlDate(jsDate);\n date.#hasDate = false;\n date.#offset = null;\n return date;\n }\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { skipVoid } from './util.js';\nimport { TomlDate } from './date.js';\nimport { TomlError } from './error.js';\nlet INT_REGEX = /^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\\d(_?\\d)*))$/;\nlet FLOAT_REGEX = /^[+-]?\\d(_?\\d)*(\\.\\d(_?\\d)*)?([eE][+-]?\\d(_?\\d)*)?$/;\nlet LEADING_ZERO = /^[+-]?0[0-9_]/;\nlet ESCAPE_REGEX = /^[0-9a-f]{2,8}$/i;\nlet ESC_MAP = {\n b: '\\b',\n t: '\\t',\n n: '\\n',\n f: '\\f',\n r: '\\r',\n e: '\\x1b',\n '\"': '\"',\n '\\\\': '\\\\',\n};\nexport function parseString(str, ptr = 0, endPtr = str.length) {\n let isLiteral = str[ptr] === '\\'';\n let isMultiline = str[ptr++] === str[ptr] && str[ptr] === str[ptr + 1];\n if (isMultiline) {\n endPtr -= 2;\n if (str[ptr += 2] === '\\r')\n ptr++;\n if (str[ptr] === '\\n')\n ptr++;\n }\n let tmp = 0;\n let isEscape;\n let parsed = '';\n let sliceStart = ptr;\n while (ptr < endPtr - 1) {\n let c = str[ptr++];\n if (c === '\\n' || (c === '\\r' && str[ptr] === '\\n')) {\n if (!isMultiline) {\n throw new TomlError('newlines are not allowed in strings', {\n toml: str,\n ptr: ptr - 1,\n });\n }\n }\n else if ((c < '\\x20' && c !== '\\t') || c === '\\x7f') {\n throw new TomlError('control characters are not allowed in strings', {\n toml: str,\n ptr: ptr - 1,\n });\n }\n if (isEscape) {\n isEscape = false;\n if (c === 'x' || c === 'u' || c === 'U') {\n // Unicode escape\n let code = str.slice(ptr, (ptr += (c === 'x' ? 2 : c === 'u' ? 4 : 8)));\n if (!ESCAPE_REGEX.test(code)) {\n throw new TomlError('invalid unicode escape', {\n toml: str,\n ptr: tmp,\n });\n }\n try {\n parsed += String.fromCodePoint(parseInt(code, 16));\n }\n catch {\n throw new TomlError('invalid unicode escape', {\n toml: str,\n ptr: tmp,\n });\n }\n }\n else if (isMultiline && (c === '\\n' || c === ' ' || c === '\\t' || c === '\\r')) {\n // Multiline escape\n ptr = skipVoid(str, ptr - 1, true);\n if (str[ptr] !== '\\n' && str[ptr] !== '\\r') {\n throw new TomlError('invalid escape: only line-ending whitespace may be escaped', {\n toml: str,\n ptr: tmp,\n });\n }\n ptr = skipVoid(str, ptr);\n }\n else if (c in ESC_MAP) {\n // Classic escape\n parsed += ESC_MAP[c];\n }\n else {\n throw new TomlError('unrecognized escape sequence', {\n toml: str,\n ptr: tmp,\n });\n }\n sliceStart = ptr;\n }\n else if (!isLiteral && c === '\\\\') {\n tmp = ptr - 1;\n isEscape = true;\n parsed += str.slice(sliceStart, tmp);\n }\n }\n return parsed + str.slice(sliceStart, endPtr - 1);\n}\nexport function parseValue(value, toml, ptr, integersAsBigInt) {\n // Constant values\n if (value === 'true')\n return true;\n if (value === 'false')\n return false;\n if (value === '-inf')\n return -Infinity;\n if (value === 'inf' || value === '+inf')\n return Infinity;\n if (value === 'nan' || value === '+nan' || value === '-nan')\n return NaN;\n // Avoid FP representation of -0\n if (value === '-0')\n return integersAsBigInt ? 0n : 0;\n // Numbers\n let isInt = INT_REGEX.test(value);\n if (isInt || FLOAT_REGEX.test(value)) {\n if (LEADING_ZERO.test(value)) {\n throw new TomlError('leading zeroes are not allowed', {\n toml: toml,\n ptr: ptr,\n });\n }\n value = value.replace(/_/g, '');\n let numeric = +value;\n if (isNaN(numeric)) {\n throw new TomlError('invalid number', {\n toml: toml,\n ptr: ptr,\n });\n }\n if (isInt) {\n if ((isInt = !Number.isSafeInteger(numeric)) && !integersAsBigInt) {\n throw new TomlError('integer value cannot be represented losslessly', {\n toml: toml,\n ptr: ptr,\n });\n }\n if (isInt || integersAsBigInt === true)\n numeric = BigInt(value);\n }\n return numeric;\n }\n const date = new TomlDate(value);\n if (!date.isValid()) {\n throw new TomlError('invalid value', {\n toml: toml,\n ptr: ptr,\n });\n }\n return date;\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parseString, parseValue } from './primitive.js';\nimport { parseArray, parseInlineTable } from './struct.js';\nimport { skipVoid, skipUntil, skipComment, getStringEnd } from './util.js';\nimport { TomlError } from './error.js';\nfunction sliceAndTrimEndOf(str, startPtr, endPtr) {\n let value = str.slice(startPtr, endPtr);\n let commentIdx = value.indexOf('#');\n if (commentIdx > -1) {\n // The call to skipComment allows to \"validate\" the comment\n // (absence of control characters)\n skipComment(str, commentIdx);\n value = value.slice(0, commentIdx);\n }\n return [value.trimEnd(), commentIdx];\n}\nexport function extractValue(str, ptr, end, depth, integersAsBigInt) {\n if (depth === 0) {\n throw new TomlError('document contains excessively nested structures. aborting.', {\n toml: str,\n ptr: ptr\n });\n }\n let c = str[ptr];\n if (c === '[' || c === '{') {\n let [value, endPtr] = c === '['\n ? parseArray(str, ptr, depth, integersAsBigInt)\n : parseInlineTable(str, ptr, depth, integersAsBigInt);\n if (end) {\n endPtr = skipVoid(str, endPtr);\n if (str[endPtr] === ',')\n endPtr++;\n else if (str[endPtr] !== end) {\n throw new TomlError('expected comma or end of structure', {\n toml: str,\n ptr: endPtr,\n });\n }\n }\n return [value, endPtr];\n }\n let endPtr;\n if (c === '\"' || c === \"'\") {\n endPtr = getStringEnd(str, ptr);\n let parsed = parseString(str, ptr, endPtr);\n if (end) {\n endPtr = skipVoid(str, endPtr);\n if (str[endPtr] && str[endPtr] !== ',' && str[endPtr] !== end && str[endPtr] !== '\\n' && str[endPtr] !== '\\r') {\n throw new TomlError('unexpected character encountered', {\n toml: str,\n ptr: endPtr,\n });\n }\n endPtr += (+(str[endPtr] === ','));\n }\n return [parsed, endPtr];\n }\n endPtr = skipUntil(str, ptr, ',', end);\n let slice = sliceAndTrimEndOf(str, ptr, endPtr - (+(str[endPtr - 1] === ',')));\n if (!slice[0]) {\n throw new TomlError('incomplete key-value declaration: no value specified', {\n toml: str,\n ptr: ptr\n });\n }\n if (end && slice[1] > -1) {\n endPtr = skipVoid(str, ptr + slice[1]);\n endPtr += +(str[endPtr] === ',');\n }\n return [\n parseValue(slice[0], str, ptr, integersAsBigInt),\n endPtr,\n ];\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parseString } from './primitive.js';\nimport { extractValue } from './extract.js';\nimport { getStringEnd, indexOfNewline, skipComment, skipVoid } from './util.js';\nimport { TomlError } from './error.js';\nlet KEY_PART_RE = /^[a-zA-Z0-9-_]+[ \\t]*$/;\nexport function parseKey(str, ptr, end = '=') {\n let dot = ptr - 1;\n let parsed = [];\n let endPtr = str.indexOf(end, ptr);\n if (endPtr < 0) {\n throw new TomlError('incomplete key-value: cannot find end of key', {\n toml: str,\n ptr: ptr,\n });\n }\n do {\n let c = str[ptr = ++dot];\n // If it's whitespace, ignore\n if (c !== ' ' && c !== '\\t') {\n // If it's a string\n if (c === '\"' || c === '\\'') {\n if (c === str[ptr + 1] && c === str[ptr + 2]) {\n throw new TomlError('multiline strings are not allowed in keys', {\n toml: str,\n ptr: ptr,\n });\n }\n let eos = getStringEnd(str, ptr);\n if (eos < 0) {\n throw new TomlError('unfinished string encountered', {\n toml: str,\n ptr: ptr,\n });\n }\n dot = str.indexOf('.', eos);\n let strEnd = str.slice(eos, dot < 0 || dot > endPtr ? endPtr : dot);\n let newLine = indexOfNewline(strEnd);\n if (newLine > -1) {\n throw new TomlError('newlines are not allowed in keys', {\n toml: str,\n ptr: ptr + dot + newLine,\n });\n }\n if (strEnd.trimStart()) {\n throw new TomlError('found extra tokens after the string part', {\n toml: str,\n ptr: eos,\n });\n }\n if (endPtr < eos) {\n endPtr = str.indexOf(end, eos);\n if (endPtr < 0) {\n throw new TomlError('incomplete key-value: cannot find end of key', {\n toml: str,\n ptr: ptr,\n });\n }\n }\n parsed.push(parseString(str, ptr, eos));\n }\n else {\n // Normal raw key part consumption and validation\n dot = str.indexOf('.', ptr);\n let part = str.slice(ptr, dot < 0 || dot > endPtr ? endPtr : dot);\n if (!KEY_PART_RE.test(part)) {\n throw new TomlError('only letter, numbers, dashes and underscores are allowed in keys', {\n toml: str,\n ptr: ptr,\n });\n }\n parsed.push(part.trimEnd());\n }\n }\n // Until there's no more dot\n } while (dot + 1 && dot < endPtr);\n return [parsed, skipVoid(str, endPtr + 1, true, true)];\n}\nexport function parseInlineTable(str, ptr, depth, integersAsBigInt) {\n let res = {};\n let seen = new Set();\n let c;\n ptr++;\n while ((c = str[ptr++]) !== '}' && c) {\n if (c === ',') {\n throw new TomlError('expected value, found comma', {\n toml: str,\n ptr: ptr - 1,\n });\n }\n else if (c === '#')\n ptr = skipComment(str, ptr);\n else if (c !== ' ' && c !== '\\t' && c !== '\\n' && c !== '\\r') {\n let k;\n let t = res;\n let hasOwn = false;\n let [key, keyEndPtr] = parseKey(str, ptr - 1);\n for (let i = 0; i < key.length; i++) {\n if (i)\n t = hasOwn ? t[k] : (t[k] = {});\n k = key[i];\n if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== 'object' || seen.has(t[k]))) {\n throw new TomlError('trying to redefine an already defined value', {\n toml: str,\n ptr: ptr,\n });\n }\n if (!hasOwn && k === '__proto__') {\n Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });\n }\n }\n if (hasOwn) {\n throw new TomlError('trying to redefine an already defined value', {\n toml: str,\n ptr: ptr,\n });\n }\n let [value, valueEndPtr] = extractValue(str, keyEndPtr, '}', depth - 1, integersAsBigInt);\n seen.add(value);\n t[k] = value;\n ptr = valueEndPtr;\n }\n }\n if (!c) {\n throw new TomlError('unfinished table encountered', {\n toml: str,\n ptr: ptr,\n });\n }\n return [res, ptr];\n}\nexport function parseArray(str, ptr, depth, integersAsBigInt) {\n let res = [];\n let c;\n ptr++;\n while ((c = str[ptr++]) !== ']' && c) {\n if (c === ',') {\n throw new TomlError('expected value, found comma', {\n toml: str,\n ptr: ptr - 1,\n });\n }\n else if (c === '#')\n ptr = skipComment(str, ptr);\n else if (c !== ' ' && c !== '\\t' && c !== '\\n' && c !== '\\r') {\n let e = extractValue(str, ptr - 1, ']', depth - 1, integersAsBigInt);\n res.push(e[0]);\n ptr = e[1];\n }\n }\n if (!c) {\n throw new TomlError('unfinished array encountered', {\n toml: str,\n ptr: ptr,\n });\n }\n return [res, ptr];\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parseKey } from './struct.js';\nimport { extractValue } from './extract.js';\nimport { skipVoid } from './util.js';\nimport { TomlError } from './error.js';\nfunction peekTable(key, table, meta, type) {\n let t = table;\n let m = meta;\n let k;\n let hasOwn = false;\n let state;\n for (let i = 0; i < key.length; i++) {\n if (i) {\n t = hasOwn ? t[k] : (t[k] = {});\n m = (state = m[k]).c;\n if (type === 0 /* Type.DOTTED */ && (state.t === 1 /* Type.EXPLICIT */ || state.t === 2 /* Type.ARRAY */)) {\n return null;\n }\n if (state.t === 2 /* Type.ARRAY */) {\n let l = t.length - 1;\n t = t[l];\n m = m[l].c;\n }\n }\n k = key[i];\n if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 /* Type.DOTTED */ && m[k]?.d) {\n return null;\n }\n if (!hasOwn) {\n if (k === '__proto__') {\n Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });\n Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });\n }\n m[k] = {\n t: i < key.length - 1 && type === 2 /* Type.ARRAY */\n ? 3 /* Type.ARRAY_DOTTED */\n : type,\n d: false,\n i: 0,\n c: {},\n };\n }\n }\n state = m[k];\n if (state.t !== type && !(type === 1 /* Type.EXPLICIT */ && state.t === 3 /* Type.ARRAY_DOTTED */)) {\n // Bad key type!\n return null;\n }\n if (type === 2 /* Type.ARRAY */) {\n if (!state.d) {\n state.d = true;\n t[k] = [];\n }\n t[k].push(t = {});\n state.c[state.i++] = (state = { t: 1 /* Type.EXPLICIT */, d: false, i: 0, c: {} });\n }\n if (state.d) {\n // Redefining a table!\n return null;\n }\n state.d = true;\n if (type === 1 /* Type.EXPLICIT */) {\n t = hasOwn ? t[k] : (t[k] = {});\n }\n else if (type === 0 /* Type.DOTTED */ && hasOwn) {\n return null;\n }\n return [k, t, state.c];\n}\nexport function parse(toml, { maxDepth = 1000, integersAsBigInt } = {}) {\n let res = {};\n let meta = {};\n let tbl = res;\n let m = meta;\n for (let ptr = skipVoid(toml, 0); ptr < toml.length;) {\n if (toml[ptr] === '[') {\n let isTableArray = toml[++ptr] === '[';\n let k = parseKey(toml, ptr += +isTableArray, ']');\n if (isTableArray) {\n if (toml[k[1] - 1] !== ']') {\n throw new TomlError('expected end of table declaration', {\n toml: toml,\n ptr: k[1] - 1,\n });\n }\n k[1]++;\n }\n let p = peekTable(k[0], res, meta, isTableArray ? 2 /* Type.ARRAY */ : 1 /* Type.EXPLICIT */);\n if (!p) {\n throw new TomlError('trying to redefine an already defined table or value', {\n toml: toml,\n ptr: ptr,\n });\n }\n m = p[2];\n tbl = p[1];\n ptr = k[1];\n }\n else {\n let k = parseKey(toml, ptr);\n let p = peekTable(k[0], tbl, m, 0 /* Type.DOTTED */);\n if (!p) {\n throw new TomlError('trying to redefine an already defined table or value', {\n toml: toml,\n ptr: ptr,\n });\n }\n let v = extractValue(toml, k[1], void 0, maxDepth, integersAsBigInt);\n p[1][p[0]] = v[0];\n ptr = v[1];\n }\n ptr = skipVoid(toml, ptr, true);\n if (toml[ptr] && toml[ptr] !== '\\n' && toml[ptr] !== '\\r') {\n throw new TomlError('each key-value declaration must be followed by an end-of-line', {\n toml: toml,\n ptr: ptr\n });\n }\n ptr = skipVoid(toml, ptr);\n }\n return res;\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nlet BARE_KEY = /^[a-z0-9-_]+$/i;\nfunction extendedTypeOf(obj) {\n let type = typeof obj;\n if (type === 'object') {\n if (Array.isArray(obj))\n return 'array';\n if (obj instanceof Date)\n return 'date';\n }\n return type;\n}\nfunction isArrayOfTables(obj) {\n for (let i = 0; i < obj.length; i++) {\n if (extendedTypeOf(obj[i]) !== 'object')\n return false;\n }\n return obj.length != 0;\n}\nfunction formatString(s) {\n return JSON.stringify(s).replace(/\\x7f/g, '\\\\u007f');\n}\nfunction stringifyValue(val, type, depth, numberAsFloat) {\n if (depth === 0) {\n throw new Error('Could not stringify the object: maximum object depth exceeded');\n }\n if (type === 'number') {\n if (isNaN(val))\n return 'nan';\n if (val === Infinity)\n return 'inf';\n if (val === -Infinity)\n return '-inf';\n if (numberAsFloat && Number.isInteger(val))\n return val.toFixed(1);\n return val.toString();\n }\n if (type === 'bigint' || type === 'boolean') {\n return val.toString();\n }\n if (type === 'string') {\n return formatString(val);\n }\n if (type === 'date') {\n if (isNaN(val.getTime())) {\n throw new TypeError('cannot serialize invalid date');\n }\n return val.toISOString();\n }\n if (type === 'object') {\n return stringifyInlineTable(val, depth, numberAsFloat);\n }\n if (type === 'array') {\n return stringifyArray(val, depth, numberAsFloat);\n }\n}\nfunction stringifyInlineTable(obj, depth, numberAsFloat) {\n let keys = Object.keys(obj);\n if (keys.length === 0)\n return '{}';\n let res = '{ ';\n for (let i = 0; i < keys.length; i++) {\n let k = keys[i];\n if (i)\n res += ', ';\n res += BARE_KEY.test(k) ? k : formatString(k);\n res += ' = ';\n res += stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1, numberAsFloat);\n }\n return res + ' }';\n}\nfunction stringifyArray(array, depth, numberAsFloat) {\n if (array.length === 0)\n return '[]';\n let res = '[ ';\n for (let i = 0; i < array.length; i++) {\n if (i)\n res += ', ';\n if (array[i] === null || array[i] === void 0) {\n throw new TypeError('arrays cannot contain null or undefined values');\n }\n res += stringifyValue(array[i], extendedTypeOf(array[i]), depth - 1, numberAsFloat);\n }\n return res + ' ]';\n}\nfunction stringifyArrayTable(array, key, depth, numberAsFloat) {\n if (depth === 0) {\n throw new Error('Could not stringify the object: maximum object depth exceeded');\n }\n let res = '';\n for (let i = 0; i < array.length; i++) {\n res += `${res && '\\n'}[[${key}]]\\n`;\n res += stringifyTable(0, array[i], key, depth, numberAsFloat);\n }\n return res;\n}\nfunction stringifyTable(tableKey, obj, prefix, depth, numberAsFloat) {\n if (depth === 0) {\n throw new Error('Could not stringify the object: maximum object depth exceeded');\n }\n let preamble = '';\n let tables = '';\n let keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n let k = keys[i];\n if (obj[k] !== null && obj[k] !== void 0) {\n let type = extendedTypeOf(obj[k]);\n if (type === 'symbol' || type === 'function') {\n throw new TypeError(`cannot serialize values of type '${type}'`);\n }\n let key = BARE_KEY.test(k) ? k : formatString(k);\n if (type === 'array' && isArrayOfTables(obj[k])) {\n tables += (tables && '\\n') + stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat);\n }\n else if (type === 'object') {\n let tblKey = prefix ? `${prefix}.${key}` : key;\n tables += (tables && '\\n') + stringifyTable(tblKey, obj[k], tblKey, depth - 1, numberAsFloat);\n }\n else {\n preamble += key;\n preamble += ' = ';\n preamble += stringifyValue(obj[k], type, depth, numberAsFloat);\n preamble += '\\n';\n }\n }\n }\n if (tableKey && (preamble || !tables)) // Create table only if necessary\n preamble = preamble ? `[${tableKey}]\\n${preamble}` : `[${tableKey}]`;\n return preamble && tables\n ? `${preamble}\\n${tables}`\n : preamble || tables;\n}\nexport function stringify(obj, { maxDepth = 1000, numbersAsFloat = false } = {}) {\n if (extendedTypeOf(obj) !== 'object') {\n throw new TypeError('stringify can only be called with an object');\n }\n let str = stringifyTable(0, obj, '', maxDepth, numbersAsFloat);\n if (str[str.length - 1] !== '\\n')\n return str + '\\n';\n return str;\n}\n","/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parse } from './parse.js';\nimport { stringify } from './stringify.js';\nimport { TomlDate } from './date.js';\nimport { TomlError } from './error.js';\nexport default { parse, stringify, TomlDate, TomlError };\nexport { parse, stringify, TomlDate, TomlError };\n","import type { Address, Hex } from \"viem\";\n\n// === Transaction Types ===\n\n/** A built DeFi transaction ready for simulation or broadcast */\nexport interface DeFiTx {\n description: string;\n to: Address;\n data: Hex;\n value: bigint;\n gas_estimate?: number;\n /** ERC20 approvals to check and send before broadcasting this tx */\n approvals?: Array<{\n token: Address;\n spender: Address;\n amount: bigint;\n }>;\n}\n\n/** Result of executing or simulating a transaction */\nexport interface ActionResult {\n tx_hash?: string;\n status: TxStatus;\n gas_used?: number;\n description: string;\n details: Record<string, unknown>;\n}\n\n/** Transaction status (serde: snake_case) */\nexport enum TxStatus {\n DryRun = \"dry_run\",\n Simulated = \"simulated\",\n SimulationFailed = \"simulation_failed\",\n Pending = \"pending\",\n Confirmed = \"confirmed\",\n Failed = \"failed\",\n}\n\n// === Token Types ===\n\n/** Token amount with decimals-aware formatting */\nexport interface TokenAmount {\n token: Address;\n symbol: string;\n amount: bigint;\n decimals: number;\n}\n\nexport function formatHuman(t: TokenAmount): string {\n const divisor = 10n ** BigInt(t.decimals);\n const whole = t.amount / divisor;\n const frac = t.amount % divisor;\n return `${whole}.${frac.toString().padStart(t.decimals, \"0\")} ${t.symbol}`;\n}\n\n/** Slippage tolerance in basis points */\nexport interface Slippage {\n bps: number;\n}\n\nexport function newSlippage(bps: number): Slippage {\n return { bps };\n}\n\nexport function defaultSwapSlippage(): Slippage {\n return { bps: 50 };\n}\n\nexport function applyMinSlippage(slippage: Slippage, amount: bigint): bigint {\n return (amount * BigInt(10000 - slippage.bps)) / 10000n;\n}\n\n// === Oracle / Price Types ===\n\nexport interface PriceData {\n source: string;\n source_type: string;\n asset: Address;\n price_usd: bigint;\n price_f64: number;\n block_number?: number;\n timestamp?: number;\n}\n\n// === DEX Types ===\n\nexport interface SwapParams {\n protocol: string;\n token_in: Address;\n token_out: Address;\n amount_in: bigint;\n slippage: Slippage;\n recipient: Address;\n deadline?: number;\n}\n\nexport interface QuoteParams {\n protocol: string;\n token_in: Address;\n token_out: Address;\n amount_in: bigint;\n}\n\nexport interface QuoteResult {\n protocol: string;\n amount_out: bigint;\n price_impact_bps?: number;\n fee_bps?: number;\n route: string[];\n}\n\nexport interface AddLiquidityParams {\n protocol: string;\n token_a: Address;\n token_b: Address;\n amount_a: bigint;\n amount_b: bigint;\n recipient: Address;\n}\n\nexport interface RemoveLiquidityParams {\n protocol: string;\n token_a: Address;\n token_b: Address;\n liquidity: bigint;\n recipient: Address;\n}\n\n// === Lending Types ===\n\nexport interface SupplyParams {\n protocol: string;\n asset: Address;\n amount: bigint;\n on_behalf_of: Address;\n}\n\nexport interface BorrowParams {\n protocol: string;\n asset: Address;\n amount: bigint;\n interest_rate_mode: InterestRateMode;\n on_behalf_of: Address;\n}\n\n/** Interest rate mode (serde: snake_case) */\nexport enum InterestRateMode {\n Variable = \"variable\",\n Stable = \"stable\",\n}\n\nexport interface RepayParams {\n protocol: string;\n asset: Address;\n amount: bigint;\n interest_rate_mode: InterestRateMode;\n on_behalf_of: Address;\n}\n\nexport interface WithdrawParams {\n protocol: string;\n asset: Address;\n amount: bigint;\n to: Address;\n}\n\nexport interface LendingRates {\n protocol: string;\n asset: Address;\n supply_apy: number;\n borrow_variable_apy: number;\n borrow_stable_apy?: number;\n utilization: number;\n total_supply: bigint;\n total_borrow: bigint;\n /** Reward token addresses for supply-side incentives */\n supply_reward_tokens?: string[];\n /** Reward token addresses for borrow-side incentives */\n borrow_reward_tokens?: string[];\n /** Emissions per second per supply reward token (raw uint256 as string) */\n supply_emissions_per_second?: string[];\n /** Emissions per second per borrow reward token (raw uint256 as string) */\n borrow_emissions_per_second?: string[];\n /** Supply-side incentive APY (%) from reward token emissions */\n supply_incentive_apy?: number;\n /** Borrow-side incentive APY (%) from reward token emissions (negative = subsidized) */\n borrow_incentive_apy?: number;\n}\n\nexport interface UserPosition {\n protocol: string;\n user: Address;\n supplies: PositionAsset[];\n borrows: PositionAsset[];\n health_factor?: number;\n net_apy?: number;\n}\n\nexport interface PositionAsset {\n asset: Address;\n symbol: string;\n amount: bigint;\n value_usd?: number;\n}\n\n// === CDP Types ===\n\nexport interface OpenCdpParams {\n protocol: string;\n collateral: Address;\n collateral_amount: bigint;\n debt_amount: bigint;\n recipient: Address;\n}\n\nexport interface AdjustCdpParams {\n protocol: string;\n cdp_id: bigint;\n collateral_delta?: bigint;\n debt_delta?: bigint;\n add_collateral: boolean;\n add_debt: boolean;\n}\n\nexport interface CloseCdpParams {\n protocol: string;\n cdp_id: bigint;\n}\n\nexport interface CdpInfo {\n protocol: string;\n cdp_id: bigint;\n collateral: TokenAmount;\n debt: TokenAmount;\n collateral_ratio: number;\n liquidation_price?: number;\n}\n\n// === Liquid Staking Types ===\n\nexport interface StakeParams {\n protocol: string;\n amount: bigint;\n recipient: Address;\n}\n\nexport interface UnstakeParams {\n protocol: string;\n amount: bigint;\n recipient: Address;\n}\n\nexport interface StakingInfo {\n protocol: string;\n staked_token: Address;\n liquid_token: Address;\n exchange_rate: number;\n apy?: number;\n total_staked: bigint;\n}\n\n// === Vault Types (ERC-4626) ===\n\nexport interface VaultInfo {\n protocol: string;\n vault_address: Address;\n asset: Address;\n total_assets: bigint;\n total_supply: bigint;\n apy?: number;\n}\n\n// === Derivatives Types ===\n\nexport interface DerivativesPositionParams {\n protocol: string;\n market: string;\n size: bigint;\n collateral: bigint;\n is_long: boolean;\n}\n\n// === Options Types ===\n\nexport interface OptionParams {\n protocol: string;\n underlying: Address;\n strike_price: bigint;\n expiry: number;\n is_call: boolean;\n amount: bigint;\n}\n\n// === ve(3,3) Types ===\n\nexport interface RewardInfo {\n token: Address;\n symbol: string;\n amount: bigint;\n value_usd?: number;\n}\n\nexport interface GaugeInfo {\n gauge: Address;\n pool: Address;\n total_staked: bigint;\n reward_rate: bigint;\n rewards: RewardInfo[];\n}\n\nexport interface VeNftInfo {\n token_id: bigint;\n amount: bigint;\n unlock_time: number;\n voting_power: bigint;\n}\n\n// === Yield Types ===\n\nexport interface YieldInfo {\n protocol: string;\n pool: string;\n apy: number;\n tvl: bigint;\n tokens: Address[];\n}\n\n// === Portfolio Tracker Types ===\nexport interface PortfolioSnapshot {\n timestamp: number;\n chain: string;\n wallet: string;\n tokens: TokenBalance[];\n defi_positions: DefiPosition[];\n total_value_usd: number;\n}\n\nexport interface TokenBalance {\n token: string;\n symbol: string;\n balance: bigint;\n value_usd: number;\n price_usd: number;\n}\n\nexport interface DefiPosition {\n protocol: string;\n type: \"lending_supply\" | \"lending_borrow\" | \"lp\" | \"staking\" | \"vault\";\n asset: string;\n amount: bigint;\n value_usd: number;\n}\n\nexport interface PortfolioPnL {\n period: string;\n start_value_usd: number;\n end_value_usd: number;\n pnl_usd: number;\n pnl_pct: number;\n token_changes: TokenChange[];\n}\n\nexport interface TokenChange {\n symbol: string;\n balance_change: bigint;\n value_change_usd: number;\n}\n","import type { Address } from \"viem\";\n\nexport type DefiErrorCode =\n | \"PROTOCOL_NOT_FOUND\"\n | \"TOKEN_NOT_FOUND\"\n | \"CHAIN_NOT_FOUND\"\n | \"INSUFFICIENT_BALANCE\"\n | \"INSUFFICIENT_ALLOWANCE\"\n | \"SLIPPAGE_EXCEEDED\"\n | \"SIMULATION_FAILED\"\n | \"ABI_ERROR\"\n | \"REGISTRY_ERROR\"\n | \"RPC_ERROR\"\n | \"PROVIDER_ERROR\"\n | \"CONTRACT_ERROR\"\n | \"INVALID_PARAM\"\n | \"UNSUPPORTED\"\n | \"INTERNAL\";\n\nexport class DefiError extends Error {\n readonly code: DefiErrorCode;\n\n constructor(code: DefiErrorCode, message: string) {\n super(message);\n this.name = \"DefiError\";\n this.code = code;\n }\n\n static protocolNotFound(name: string): DefiError {\n return new DefiError(\"PROTOCOL_NOT_FOUND\", `Protocol not found: ${name}`);\n }\n\n static tokenNotFound(name: string): DefiError {\n return new DefiError(\"TOKEN_NOT_FOUND\", `Token not found: ${name}`);\n }\n\n static chainNotFound(name: string): DefiError {\n return new DefiError(\"CHAIN_NOT_FOUND\", `Chain not found: ${name}`);\n }\n\n static insufficientBalance(needed: string, available: string): DefiError {\n return new DefiError(\n \"INSUFFICIENT_BALANCE\",\n `Insufficient balance: need ${needed}, have ${available}`,\n );\n }\n\n static insufficientAllowance(spender: Address): DefiError {\n return new DefiError(\n \"INSUFFICIENT_ALLOWANCE\",\n `Insufficient allowance for spender ${spender}`,\n );\n }\n\n static slippageExceeded(expected: string, actual: string): DefiError {\n return new DefiError(\n \"SLIPPAGE_EXCEEDED\",\n `Slippage exceeded: expected ${expected}, got ${actual}`,\n );\n }\n\n static simulationFailed(reason: string): DefiError {\n return new DefiError(\n \"SIMULATION_FAILED\",\n `Transaction simulation failed: ${reason}`,\n );\n }\n\n static abiError(reason: string): DefiError {\n return new DefiError(\"ABI_ERROR\", `ABI encoding error: ${reason}`);\n }\n\n static registryError(reason: string): DefiError {\n return new DefiError(\"REGISTRY_ERROR\", `Registry error: ${reason}`);\n }\n\n static rpcError(reason: string): DefiError {\n return new DefiError(\"RPC_ERROR\", `RPC error: ${reason}`);\n }\n\n static providerError(reason: string): DefiError {\n return new DefiError(\"PROVIDER_ERROR\", `Provider error: ${reason}`);\n }\n\n static contractError(reason: string): DefiError {\n return new DefiError(\"CONTRACT_ERROR\", `Contract error: ${reason}`);\n }\n\n static invalidParam(reason: string): DefiError {\n return new DefiError(\"INVALID_PARAM\", `Invalid parameter: ${reason}`);\n }\n\n static unsupported(operation: string): DefiError {\n return new DefiError(\n \"UNSUPPORTED\",\n `Unsupported operation: ${operation}`,\n );\n }\n\n static internal(reason: string): DefiError {\n return new DefiError(\"INTERNAL\", `Internal error: ${reason}`);\n }\n\n toJSON() {\n return { error: this.message };\n }\n}\n\nexport type Result<T> = T;\n","/**\n * BigInt JSON serialization utilities.\n *\n * Rust's alloy U256 (backed by ruint) serializes to JSON as 0x-prefixed\n * lowercase hex strings (e.g., \"0x75bcd15\"). We must match this exactly\n * for behavioral parity.\n */\n\n/** JSON replacer for Rust parity — bigint becomes 0x-hex string */\nexport function jsonReplacer(_key: string, value: unknown): unknown {\n if (typeof value === \"bigint\") {\n return \"0x\" + value.toString(16);\n }\n return value;\n}\n\n/** JSON replacer for SDK consumers — bigint becomes decimal string */\nexport function jsonReplacerDecimal(_key: string, value: unknown): unknown {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n}\n\n/** Stringify with decimal bigint handling */\nexport function jsonStringify(data: unknown, pretty = true): string {\n return pretty\n ? JSON.stringify(data, jsonReplacerDecimal, 2)\n : JSON.stringify(data, jsonReplacerDecimal);\n}\n\n/** Parse a 0x-hex or decimal string to bigint */\nexport function parseBigInt(value: string): bigint {\n if (value.startsWith(\"0x\") || value.startsWith(\"0X\")) {\n return BigInt(value);\n }\n return BigInt(value);\n}\n","import type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, parseAbi } from \"viem\";\nimport type { DeFiTx } from \"./types.js\";\n\nconst erc20Abi = parseAbi([\n \"function name() view returns (string)\",\n \"function symbol() view returns (string)\",\n \"function decimals() view returns (uint8)\",\n \"function totalSupply() view returns (uint256)\",\n \"function balanceOf(address account) view returns (uint256)\",\n \"function transfer(address to, uint256 amount) returns (bool)\",\n \"function allowance(address owner, address spender) view returns (uint256)\",\n \"function approve(address spender, uint256 amount) returns (bool)\",\n \"function transferFrom(address from, address to, uint256 amount) returns (bool)\",\n]);\n\nexport { erc20Abi };\n\nexport function buildApprove(\n token: Address,\n spender: Address,\n amount: bigint,\n): DeFiTx {\n const data = encodeFunctionData({\n abi: erc20Abi,\n functionName: \"approve\",\n args: [spender, amount],\n });\n return {\n description: `Approve ${spender} to spend ${amount} of token ${token}`,\n to: token,\n data,\n value: 0n,\n gas_estimate: 60_000,\n };\n}\n\nexport function buildTransfer(\n token: Address,\n to: Address,\n amount: bigint,\n): DeFiTx {\n const data = encodeFunctionData({\n abi: erc20Abi,\n functionName: \"transfer\",\n args: [to, amount],\n });\n return {\n description: `Transfer ${amount} of token ${token} to ${to}`,\n to: token,\n data,\n value: 0n,\n gas_estimate: 65_000,\n };\n}\n","import { createPublicClient, http, type PublicClient } from \"viem\";\n\nconst providerCache = new Map<string, PublicClient>();\n\nexport function getProvider(rpcUrl: string): PublicClient {\n const cached = providerCache.get(rpcUrl);\n if (cached) return cached;\n\n const client = createPublicClient({ transport: http(rpcUrl) });\n providerCache.set(rpcUrl, client);\n return client;\n}\n\nexport function clearProviderCache(): void {\n providerCache.clear();\n}\n","import type { Address, Hex } from \"viem\";\nimport { encodeFunctionData, decodeFunctionResult, parseAbi } from \"viem\";\nimport type { DeFiTx } from \"./types.js\";\nimport { getProvider } from \"./provider.js\";\n\nexport const MULTICALL3_ADDRESS: Address =\n \"0xcA11bde05977b3631167028862bE2a173976CA11\";\n\nconst multicall3Abi = parseAbi([\n \"struct Call3 { address target; bool allowFailure; bytes callData; }\",\n \"struct Result { bool success; bytes returnData; }\",\n \"function aggregate3(Call3[] calls) returns (Result[] returnData)\",\n]);\n\nexport function buildMulticall(calls: Array<[Address, Hex]>): DeFiTx {\n const mcCalls = calls.map(([target, callData]) => ({\n target,\n allowFailure: true,\n callData,\n }));\n\n const data = encodeFunctionData({\n abi: multicall3Abi,\n functionName: \"aggregate3\",\n args: [mcCalls],\n });\n\n return {\n description: `Multicall3 batch (${calls.length} calls)`,\n to: MULTICALL3_ADDRESS,\n data,\n value: 0n,\n };\n}\n\nexport async function multicallRead(\n rpcUrl: string,\n calls: Array<[Address, Hex]>,\n): Promise<(Hex | null)[]> {\n const client = getProvider(rpcUrl);\n\n const mcCalls = calls.map(([target, callData]) => ({\n target,\n allowFailure: true,\n callData,\n }));\n\n const result = await client.call({\n to: MULTICALL3_ADDRESS,\n data: encodeFunctionData({\n abi: multicall3Abi,\n functionName: \"aggregate3\",\n args: [mcCalls],\n }),\n });\n\n if (!result.data) return calls.map(() => null);\n\n const decoded = decodeFunctionResult({\n abi: multicall3Abi,\n functionName: \"aggregate3\",\n data: result.data,\n }) as Array<{ success: boolean; returnData: Hex }>;\n\n return decoded.map((r) => (r.success ? r.returnData : null));\n}\n\nexport function decodeU256(data: Hex | null): bigint {\n if (!data || data.length < 66) return 0n;\n return BigInt(data.slice(0, 66));\n}\n\nexport function decodeU128(data: Hex | null): bigint {\n if (!data || data.length < 66) return 0n;\n const val = BigInt(data.slice(0, 66));\n return val & ((1n << 128n) - 1n);\n}\n","export class ChainConfig {\n name!: string;\n chain_id!: number;\n rpc_url!: string;\n explorer_url?: string;\n native_token!: string;\n wrapped_native?: string;\n multicall3?: string;\n\n effectiveRpcUrl(): string {\n const chainEnv = this.name.toUpperCase().replace(/ /g, \"_\") + \"_RPC_URL\";\n return (\n process.env[chainEnv] ??\n process.env[\"HYPEREVM_RPC_URL\"] ??\n this.rpc_url\n );\n }\n}\n","import type { Address } from \"viem\";\n\nexport enum ProtocolCategory {\n Dex = \"dex\",\n Lending = \"lending\",\n Cdp = \"cdp\",\n Bridge = \"bridge\",\n LiquidStaking = \"liquid_staking\",\n YieldSource = \"yield_source\",\n YieldAggregator = \"yield_aggregator\",\n Vault = \"vault\",\n Derivatives = \"derivatives\",\n Options = \"options\",\n LiquidityManager = \"liquidity_manager\",\n Nft = \"nft\",\n Other = \"other\",\n}\n\nexport function protocolCategoryLabel(category: ProtocolCategory): string {\n switch (category) {\n case ProtocolCategory.Dex:\n return \"DEX\";\n case ProtocolCategory.Lending:\n return \"Lending\";\n case ProtocolCategory.Cdp:\n return \"CDP\";\n case ProtocolCategory.Bridge:\n return \"Bridge\";\n case ProtocolCategory.LiquidStaking:\n return \"Liquid Staking\";\n case ProtocolCategory.YieldSource:\n return \"Yield Source\";\n case ProtocolCategory.YieldAggregator:\n return \"Yield Aggregator\";\n case ProtocolCategory.Vault:\n return \"Vault\";\n case ProtocolCategory.Derivatives:\n return \"Derivatives\";\n case ProtocolCategory.Options:\n return \"Options\";\n case ProtocolCategory.LiquidityManager:\n return \"Liquidity Manager\";\n case ProtocolCategory.Nft:\n return \"NFT\";\n case ProtocolCategory.Other:\n return \"Other\";\n }\n}\n\nexport interface ProtocolEntry {\n name: string;\n slug: string;\n category: ProtocolCategory;\n interface: string;\n chain: string;\n native?: boolean;\n contracts?: Record<string, Address>;\n description?: string;\n}\n","import { readFileSync, readdirSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { parse } from \"smol-toml\";\nimport { ChainConfig } from \"./chain.js\";\nimport type { TokenEntry } from \"./token.js\";\nimport { type ProtocolEntry, ProtocolCategory } from \"./protocol.js\";\n\nimport { existsSync } from \"fs\";\n\nconst __dirname = fileURLToPath(new URL(\".\", import.meta.url));\n\n// Resolve config dir: works from src/ (vitest), dist/ (built), and npm bundle (npx)\nfunction findConfigDir(): string {\n const candidates = [\n resolve(__dirname, \"../../../config\"), // from dist/registry/ (monorepo build)\n resolve(__dirname, \"../../../../config\"), // from src/registry/ (vitest)\n resolve(__dirname, \"../config\"), // from dist/ (npm bundle — config at package root)\n resolve(__dirname, \"../../config\"), // from dist/subdir (npm bundle variant)\n ];\n for (const dir of candidates) {\n if (existsSync(resolve(dir, \"chains.toml\"))) return dir;\n }\n throw new Error(`Config directory not found. Searched: ${candidates.join(\", \")}`);\n}\n\nconst CONFIG_DIR = findConfigDir();\n\nfunction readToml(relPath: string): string {\n return readFileSync(resolve(CONFIG_DIR, relPath), \"utf-8\");\n}\n\ninterface ChainConfigWrapper {\n chain: Record<string, ChainConfig>;\n}\n\ninterface TokensWrapper {\n token: TokenEntry[];\n}\n\ninterface ProtocolWrapper {\n protocol: ProtocolEntry;\n}\n\nexport class Registry {\n chains: Map<string, ChainConfig>;\n tokens: Map<string, TokenEntry[]>;\n protocols: ProtocolEntry[];\n\n private constructor(\n chains: Map<string, ChainConfig>,\n tokens: Map<string, TokenEntry[]>,\n protocols: ProtocolEntry[],\n ) {\n this.chains = chains;\n this.tokens = tokens;\n this.protocols = protocols;\n }\n\n static loadEmbedded(): Registry {\n const chains = Registry.loadChains();\n const tokens = Registry.loadTokens();\n const protocols = Registry.loadProtocols();\n return new Registry(chains, tokens, protocols);\n }\n\n private static loadChains(): Map<string, ChainConfig> {\n const raw = parse(readToml(\"chains.toml\")) as unknown as ChainConfigWrapper;\n const map = new Map<string, ChainConfig>();\n for (const [key, data] of Object.entries(raw.chain)) {\n const cfg = Object.assign(new ChainConfig(), data);\n map.set(key, cfg);\n }\n return map;\n }\n\n private static loadTokens(): Map<string, TokenEntry[]> {\n // Dynamically discover all token files in config/tokens/\n const map = new Map<string, TokenEntry[]>();\n const tokensDir = resolve(CONFIG_DIR, \"tokens\");\n try {\n const files = readdirSync(tokensDir).filter(f => f.endsWith(\".toml\"));\n for (const file of files) {\n const chain = file.replace(\".toml\", \"\");\n try {\n const raw = parse(readToml(`tokens/${file}`)) as unknown as TokensWrapper;\n map.set(chain, raw.token);\n } catch { /* skip invalid token files */ }\n }\n } catch { /* tokens dir may not exist */ }\n return map;\n }\n\n private static loadProtocols(): ProtocolEntry[] {\n // Dynamically discover all protocol TOML files across all categories\n const protocols: ProtocolEntry[] = [];\n const protocolsDir = resolve(CONFIG_DIR, \"protocols\");\n const categories = [\"dex\", \"lending\", \"cdp\", \"vault\", \"liquid_staking\", \"yield_aggregator\", \"yield_source\", \"derivatives\", \"options\", \"nft\", \"bridge\"];\n\n for (const category of categories) {\n const catDir = resolve(protocolsDir, category);\n try {\n if (!existsSync(catDir)) continue;\n const files = readdirSync(catDir).filter(f => f.endsWith(\".toml\"));\n for (const file of files) {\n try {\n const raw = parse(readToml(`protocols/${category}/${file}`)) as unknown as ProtocolWrapper;\n protocols.push(raw.protocol);\n } catch { /* skip invalid protocol files */ }\n }\n } catch { /* category dir may not exist */ }\n }\n return protocols;\n }\n\n getChain(name: string): ChainConfig {\n const chain = this.chains.get(name);\n if (!chain) throw new Error(`Chain not found: ${name}`);\n return chain;\n }\n\n getProtocol(name: string): ProtocolEntry {\n const protocol = this.protocols.find(\n (p) =>\n p.name.toLowerCase() === name.toLowerCase() ||\n p.slug.toLowerCase() === name.toLowerCase(),\n );\n if (!protocol) throw new Error(`Protocol not found: ${name}`);\n return protocol;\n }\n\n getProtocolsByCategory(category: ProtocolCategory): ProtocolEntry[] {\n return this.protocols.filter((p) => p.category === category);\n }\n\n getProtocolsForChain(chain: string): ProtocolEntry[] {\n return this.protocols.filter(\n (p) => p.chain.toLowerCase() === chain.toLowerCase(),\n );\n }\n\n resolveToken(chain: string, symbol: string): TokenEntry {\n const tokens = this.tokens.get(chain);\n if (!tokens) throw new Error(`Chain not found: ${chain}`);\n const token = tokens.find(\n (t) => t.symbol.toLowerCase() === symbol.toLowerCase(),\n );\n if (!token) throw new Error(`Token not found: ${symbol}`);\n return token;\n }\n}\n","import { DefiError } from \"@hypurrquant/defi-core\";\nimport type { ProtocolEntry } from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\n\n// DEX adapters\nimport { UniswapV3Adapter } from \"./dex/uniswap_v3.js\";\nimport { UniswapV2Adapter } from \"./dex/uniswap_v2.js\";\nimport { AlgebraV3Adapter } from \"./dex/algebra_v3.js\";\nimport { BalancerV3Adapter } from \"./dex/balancer_v3.js\";\nimport { CurveStableSwapAdapter } from \"./dex/curve.js\";\nimport { SolidlyAdapter } from \"./dex/solidly.js\";\nimport { WooFiAdapter } from \"./dex/woofi.js\";\nimport { SolidlyGaugeAdapter } from \"./dex/solidly_gauge.js\";\nimport { MasterChefAdapter } from \"./dex/masterchef.js\";\n\n// Trait interfaces\nimport type { IDex } from \"@hypurrquant/defi-core\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport type { ICdp } from \"@hypurrquant/defi-core\";\nimport type { IVault } from \"@hypurrquant/defi-core\";\nimport type { ILiquidStaking } from \"@hypurrquant/defi-core\";\nimport type { IGaugeSystem } from \"@hypurrquant/defi-core\";\nimport type { IGauge } from \"@hypurrquant/defi-core\";\nimport type { IYieldSource } from \"@hypurrquant/defi-core\";\nimport type { IDerivatives } from \"@hypurrquant/defi-core\";\nimport type { IOptions } from \"@hypurrquant/defi-core\";\nimport type { IOracle } from \"@hypurrquant/defi-core\";\nimport type { INft } from \"@hypurrquant/defi-core\";\n\n// Lending adapters\nimport { AaveV3Adapter } from \"./lending/aave_v3.js\";\nimport { AaveV2Adapter } from \"./lending/aave_v2.js\";\nimport { AaveOracleAdapter } from \"./lending/aave_oracle.js\";\nimport { CompoundV2Adapter } from \"./lending/compound_v2.js\";\nimport { CompoundV3Adapter } from \"./lending/compound_v3.js\";\nimport { EulerV2Adapter } from \"./lending/euler_v2.js\";\nimport { MorphoBlueAdapter } from \"./lending/morpho.js\";\n\n// CDP adapters\nimport { FelixCdpAdapter } from \"./cdp/felix.js\";\nimport { FelixOracleAdapter } from \"./cdp/felix_oracle.js\";\n\n// Vault adapters\nimport { ERC4626VaultAdapter } from \"./vault/erc4626.js\";\n\n// Liquid staking adapters\nimport { GenericLstAdapter } from \"./liquid_staking/generic_lst.js\";\nimport { StHypeAdapter } from \"./liquid_staking/sthype.js\";\nimport { KinetiqAdapter } from \"./liquid_staking/kinetiq.js\";\n\n// Yield source adapters\nimport { PendleAdapter } from \"./yield_source/pendle.js\";\nimport { GenericYieldAdapter } from \"./yield_source/generic_yield.js\";\n\n// Derivatives adapters\nimport { HlpVaultAdapter } from \"./derivatives/hlp.js\";\nimport { GenericDerivativesAdapter } from \"./derivatives/generic_derivatives.js\";\n\n// Options adapters\nimport { RyskAdapter } from \"./options/rysk.js\";\nimport { GenericOptionsAdapter } from \"./options/generic_options.js\";\n\n// NFT adapters\nimport { ERC721Adapter } from \"./nft/erc721.js\";\n\n// ============================================================\n// DEX\n// ============================================================\n\n/** Create a Dex implementation from a protocol registry entry */\nexport function createDex(entry: ProtocolEntry, rpcUrl?: string): IDex {\n switch (entry.interface) {\n case \"uniswap_v3\":\n return new UniswapV3Adapter(entry, rpcUrl);\n case \"uniswap_v4\":\n throw DefiError.unsupported(\n `[${entry.name}] Uniswap V4 (singleton PoolManager) is not yet supported — use HyperSwap V3 or another V3-compatible DEX for quotes`,\n );\n case \"algebra_v3\":\n return new AlgebraV3Adapter(entry, rpcUrl);\n case \"uniswap_v2\":\n return new UniswapV2Adapter(entry, rpcUrl);\n case \"solidly_v2\":\n case \"solidly_cl\":\n return new SolidlyAdapter(entry, rpcUrl);\n case \"curve_stableswap\":\n return new CurveStableSwapAdapter(entry);\n case \"balancer_v3\":\n return new BalancerV3Adapter(entry);\n case \"woofi\":\n return new WooFiAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`DEX interface '${entry.interface}' not yet implemented`);\n }\n}\n\n// ============================================================\n// Lending\n// ============================================================\n\n/** Create a Lending implementation from a protocol registry entry */\nexport function createLending(entry: ProtocolEntry, rpcUrl?: string): ILending {\n switch (entry.interface) {\n case \"aave_v3\":\n case \"aave_v3_isolated\":\n return new AaveV3Adapter(entry, rpcUrl);\n case \"aave_v2\":\n return new AaveV2Adapter(entry, rpcUrl);\n case \"morpho_blue\":\n return new MorphoBlueAdapter(entry, rpcUrl);\n case \"euler_v2\":\n return new EulerV2Adapter(entry, rpcUrl);\n case \"compound_v2\":\n return new CompoundV2Adapter(entry, rpcUrl);\n case \"compound_v3\":\n return new CompoundV3Adapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Lending interface '${entry.interface}' not yet implemented`);\n }\n}\n\n// ============================================================\n// CDP\n// ============================================================\n\n/** Create a CDP implementation from a protocol registry entry */\nexport function createCdp(entry: ProtocolEntry, rpcUrl?: string): ICdp {\n switch (entry.interface) {\n case \"liquity_v2\":\n return new FelixCdpAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`CDP interface '${entry.interface}' not yet implemented`);\n }\n}\n\n// ============================================================\n// Vault\n// ============================================================\n\n/** Create a Vault implementation from a protocol registry entry */\nexport function createVault(entry: ProtocolEntry, rpcUrl?: string): IVault {\n switch (entry.interface) {\n case \"erc4626\":\n case \"beefy_vault\":\n return new ERC4626VaultAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Vault interface '${entry.interface}' not yet implemented`);\n }\n}\n\n// ============================================================\n// Liquid Staking\n// ============================================================\n\n/** Create a LiquidStaking implementation from a protocol registry entry */\nexport function createLiquidStaking(entry: ProtocolEntry, rpcUrl?: string): ILiquidStaking {\n switch (entry.interface) {\n case \"kinetiq_staking\":\n return new KinetiqAdapter(entry, rpcUrl);\n case \"sthype_staking\":\n return new StHypeAdapter(entry, rpcUrl);\n case \"hyperbeat_lst\":\n case \"kintsu\":\n return new GenericLstAdapter(entry, rpcUrl);\n default:\n return new GenericLstAdapter(entry, rpcUrl);\n }\n}\n\n// ============================================================\n// Gauge\n// ============================================================\n\n/** Create a GaugeSystem implementation from a protocol registry entry */\nexport function createGauge(entry: ProtocolEntry, rpcUrl?: string): IGaugeSystem {\n switch (entry.interface) {\n case \"solidly_v2\":\n case \"solidly_cl\":\n case \"algebra_v3\":\n case \"hybra\":\n return new SolidlyGaugeAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Gauge interface '${entry.interface}' not supported`);\n }\n}\n\n/** Create a MasterChef IGauge implementation from a protocol registry entry */\nexport function createMasterChef(entry: ProtocolEntry, rpcUrl?: string): IGauge {\n return new MasterChefAdapter(entry, rpcUrl);\n}\n\n// ============================================================\n// Yield Source (fallback to GenericYield)\n// ============================================================\n\n/** Create a YieldSource implementation — falls back to GenericYield for unknown interfaces */\nexport function createYieldSource(entry: ProtocolEntry, rpcUrl?: string): IYieldSource {\n switch (entry.interface) {\n case \"pendle_v2\":\n return new PendleAdapter(entry, rpcUrl);\n default:\n return new GenericYieldAdapter(entry, rpcUrl);\n }\n}\n\n// ============================================================\n// Derivatives (fallback to GenericDerivatives)\n// ============================================================\n\n/** Create a Derivatives implementation — falls back to GenericDerivatives for unknown interfaces */\nexport function createDerivatives(entry: ProtocolEntry, rpcUrl?: string): IDerivatives {\n switch (entry.interface) {\n case \"hlp_vault\":\n return new HlpVaultAdapter(entry, rpcUrl);\n default:\n return new GenericDerivativesAdapter(entry, rpcUrl);\n }\n}\n\n// ============================================================\n// Options (fallback to GenericOptions)\n// ============================================================\n\n/** Create an Options implementation — falls back to GenericOptions for unknown interfaces */\nexport function createOptions(entry: ProtocolEntry, rpcUrl?: string): IOptions {\n switch (entry.interface) {\n case \"rysk\":\n return new RyskAdapter(entry, rpcUrl);\n default:\n return new GenericOptionsAdapter(entry, rpcUrl);\n }\n}\n\n// ============================================================\n// NFT\n// ============================================================\n\n/** Create an NFT implementation from a protocol registry entry */\nexport function createNft(entry: ProtocolEntry, rpcUrl?: string): INft {\n switch (entry.interface) {\n case \"erc721\":\n return new ERC721Adapter(entry, rpcUrl);\n case \"marketplace\":\n throw DefiError.unsupported(`NFT marketplace '${entry.name}' is not queryable as ERC-721. Use a specific collection address.`);\n default:\n throw DefiError.unsupported(`NFT interface '${entry.interface}' not supported`);\n }\n}\n\n// ============================================================\n// Oracle from Lending\n// ============================================================\n\n/** Create an Oracle from a lending protocol entry (Aave V3 forks have an oracle contract) */\nexport function createOracleFromLending(entry: ProtocolEntry, rpcUrl: string): IOracle {\n switch (entry.interface) {\n case \"aave_v3\":\n case \"aave_v3_isolated\":\n return new AaveOracleAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Oracle not available for lending interface '${entry.interface}'`);\n }\n}\n\n// ============================================================\n// Oracle from CDP\n// ============================================================\n\n/** Create an Oracle from a CDP protocol entry (Felix has its own PriceFeed contract) */\nexport function createOracleFromCdp(entry: ProtocolEntry, _asset: Address, rpcUrl: string): IOracle {\n switch (entry.interface) {\n case \"liquity_v2\":\n return new FelixOracleAdapter(entry, rpcUrl);\n default:\n throw DefiError.unsupported(`Oracle not available for CDP interface '${entry.interface}'`);\n }\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http, decodeAbiParameters } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst DEFAULT_FEE = 3000;\n\nconst swapRouterAbi = parseAbi([\n \"struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; }\",\n \"function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut)\",\n]);\n\nconst quoterAbi = parseAbi([\n \"struct QuoteExactInputSingleParams { address tokenIn; address tokenOut; uint256 amountIn; uint24 fee; uint160 sqrtPriceLimitX96; }\",\n \"function quoteExactInputSingle(QuoteExactInputSingleParams memory params) external returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\",\n]);\n\n// Ramses CL uses tickSpacing instead of fee in the quoter struct\nconst ramsesQuoterAbi = parseAbi([\n \"struct QuoteExactInputSingleParams { address tokenIn; address tokenOut; uint256 amountIn; int24 tickSpacing; uint160 sqrtPriceLimitX96; }\",\n \"function quoteExactInputSingle(QuoteExactInputSingleParams memory params) external returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\",\n]);\n\nconst positionManagerAbi = parseAbi([\n \"struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; }\",\n \"function mint(MintParams calldata params) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)\",\n]);\n\nexport class UniswapV3Adapter implements IDex {\n private readonly protocolName: string;\n private readonly router: Address;\n private readonly quoter: Address | undefined;\n private readonly positionManager: Address | undefined;\n private readonly factory: Address | undefined;\n private readonly fee: number;\n private readonly rpcUrl: string | undefined;\n private readonly useTickSpacingQuoter: boolean;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n this.quoter = entry.contracts?.[\"quoter\"];\n this.positionManager = entry.contracts?.[\"position_manager\"];\n this.factory = entry.contracts?.[\"factory\"];\n this.fee = DEFAULT_FEE;\n this.rpcUrl = rpcUrl;\n // Ramses CL and similar forks use tickSpacing-based pool identification\n this.useTickSpacingQuoter = entry.contracts?.[\"pool_deployer\"] !== undefined\n || entry.contracts?.[\"gauge_factory\"] !== undefined;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n const amountOutMinimum = 0n;\n\n const data = encodeFunctionData({\n abi: swapRouterAbi,\n functionName: \"exactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n fee: this.fee,\n recipient: params.recipient,\n deadline,\n amountIn: params.amount_in,\n amountOutMinimum,\n sqrtPriceLimitX96: 0n,\n },\n ],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} tokenIn for tokenOut`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 200_000,\n approvals: [{ token: params.token_in, spender: this.router, amount: params.amount_in }],\n };\n }\n\n async quote(params: QuoteParams): Promise<QuoteResult> {\n if (!this.rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL configured\");\n }\n\n if (this.quoter) {\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n // Try tickSpacing-based quoter first for Ramses CL and similar forks\n if (this.useTickSpacingQuoter) {\n const tickSpacings = [1, 10, 50, 100, 200];\n const tsResults = await Promise.allSettled(\n tickSpacings.map(async (ts) => {\n const result = await client.call({\n to: this.quoter!,\n data: encodeFunctionData({\n abi: ramsesQuoterAbi,\n functionName: \"quoteExactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n amountIn: params.amount_in,\n tickSpacing: ts,\n sqrtPriceLimitX96: 0n,\n },\n ],\n }),\n });\n if (!result.data) return { amountOut: 0n, tickSpacing: ts };\n const [amountOut] = decodeAbiParameters(\n [{ name: \"amountOut\", type: \"uint256\" }],\n result.data,\n );\n return { amountOut, tickSpacing: ts };\n }),\n );\n\n let best = { amountOut: 0n, tickSpacing: 50 };\n for (const r of tsResults) {\n if (r.status === \"fulfilled\" && r.value.amountOut > best.amountOut) {\n best = r.value;\n }\n }\n\n if (best.amountOut > 0n) {\n return {\n protocol: this.protocolName,\n amount_out: best.amountOut,\n price_impact_bps: undefined,\n fee_bps: undefined,\n route: [`${params.token_in} -> ${params.token_out} (tickSpacing: ${best.tickSpacing})`],\n };\n }\n\n // tickSpacing-based protocol (Ramses CL): quoter returned no result.\n // Pool exists but has no liquidity in this fork snapshot.\n throw DefiError.rpcError(\n `[${this.protocolName}] No quote available — pool exists but has zero liquidity for this pair`,\n );\n }\n\n // Standard Uniswap V3 fee-based quoter\n const feeTiers = [500, 3000, 10000, 100];\n const results = await Promise.allSettled(\n feeTiers.map(async (fee) => {\n const result = await client.call({\n to: this.quoter!,\n data: encodeFunctionData({\n abi: quoterAbi,\n functionName: \"quoteExactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n amountIn: params.amount_in,\n fee,\n sqrtPriceLimitX96: 0n,\n },\n ],\n }),\n });\n if (!result.data) return { amountOut: 0n, fee };\n const [amountOut] = decodeAbiParameters(\n [{ name: \"amountOut\", type: \"uint256\" }],\n result.data,\n );\n return { amountOut, fee };\n }),\n );\n\n let best = { amountOut: 0n, fee: 3000 };\n for (const r of results) {\n if (r.status === \"fulfilled\" && r.value.amountOut > best.amountOut) {\n best = r.value;\n }\n }\n\n if (best.amountOut > 0n) {\n return {\n protocol: this.protocolName,\n amount_out: best.amountOut,\n price_impact_bps: undefined,\n fee_bps: Math.floor(best.fee / 10),\n route: [`${params.token_in} -> ${params.token_out} (fee: ${best.fee})`],\n };\n }\n }\n\n // Fallback: simulate swap via eth_call on the router\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const callData = encodeFunctionData({\n abi: swapRouterAbi,\n functionName: \"exactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n fee: this.fee,\n recipient: \"0x0000000000000000000000000000000000000001\",\n deadline: BigInt(\"18446744073709551615\"),\n amountIn: params.amount_in,\n amountOutMinimum: 0n,\n sqrtPriceLimitX96: 0n,\n },\n ],\n });\n\n let output: `0x${string}` | undefined;\n try {\n const result = await client.call({ to: this.router, data: callData });\n output = result.data;\n } catch (e: unknown) {\n const errMsg = String(e);\n if (errMsg.includes(\"STF\") || errMsg.includes(\"insufficient\")) {\n throw DefiError.unsupported(\n `[${this.protocolName}] quote unavailable — no quoter contract configured. Swap simulation requires token balance. Add a quoter address to the protocol config.`,\n );\n }\n throw DefiError.rpcError(`[${this.protocolName}] swap simulation for quote failed: ${errMsg}`);\n }\n\n const amountOut =\n output && output.length >= 66\n ? BigInt(output.slice(0, 66))\n : 0n;\n\n return {\n protocol: this.protocolName,\n amount_out: amountOut,\n price_impact_bps: undefined,\n fee_bps: Math.floor(this.fee / 10),\n route: [`${params.token_in} -> ${params.token_out} (simulated)`],\n };\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n const pm = this.positionManager;\n if (!pm) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Position manager address not configured\");\n }\n\n // Sort tokens (Uniswap V3 requires token0 < token1)\n const [token0, token1, rawAmount0, rawAmount1] =\n params.token_a.toLowerCase() < params.token_b.toLowerCase()\n ? [params.token_a, params.token_b, params.amount_a, params.amount_b]\n : [params.token_b, params.token_a, params.amount_b, params.amount_a];\n\n // V3 NPM mint: getLiquidityForAmounts uses min(L0, L1), so if either is 0\n // then liquidity=0 → revert. Use 1 wei minimum for single-side LP.\n const amount0 = rawAmount0 === 0n && rawAmount1 > 0n ? 1n : rawAmount0;\n const amount1 = rawAmount1 === 0n && rawAmount0 > 0n ? 1n : rawAmount1;\n\n const data = encodeFunctionData({\n abi: positionManagerAbi,\n functionName: \"mint\",\n args: [\n {\n token0,\n token1,\n fee: this.fee,\n tickLower: -887220,\n tickUpper: 887220,\n amount0Desired: amount0,\n amount1Desired: amount1,\n amount0Min: 0n,\n amount1Min: 0n,\n recipient: params.recipient,\n deadline: BigInt(\"18446744073709551615\"),\n },\n ],\n });\n\n return {\n description: `[${this.protocolName}] Add liquidity`,\n to: pm,\n data,\n value: 0n,\n gas_estimate: 500_000,\n approvals: [\n { token: token0, spender: pm, amount: amount0 },\n { token: token1, spender: pm, amount: amount1 },\n ],\n };\n }\n\n async buildRemoveLiquidity(_params: RemoveLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] remove_liquidity requires tokenId — use NFT position manager directly`,\n );\n }\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http, decodeFunctionResult, decodeAbiParameters } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts)\",\n \"function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB, uint256 liquidity)\",\n \"function removeLiquidity(address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB)\",\n \"function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts)\",\n]);\n\nconst lbQuoterAbi = parseAbi([\n \"function findBestPathFromAmountIn(address[] calldata route, uint128 amountIn) external view returns ((address[] route, address[] pairs, uint256[] binSteps, uint256[] versions, uint128[] amounts, uint128[] virtualAmountsWithoutSlippage, uint128[] fees))\",\n]);\n\nexport class UniswapV2Adapter implements IDex {\n private readonly protocolName: string;\n private readonly router: Address;\n private readonly rpcUrl: string | undefined;\n private readonly lbQuoter: Address | undefined;\n private readonly lbIntermediaries: Address[];\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n this.lbQuoter = entry.contracts?.[\"lb_quoter\"];\n this.rpcUrl = rpcUrl;\n\n // Collect LB intermediary tokens from contracts with \"lb_mid_\" prefix\n this.lbIntermediaries = [];\n if (entry.contracts) {\n for (const [key, addr] of Object.entries(entry.contracts)) {\n if (key.startsWith(\"lb_mid_\")) {\n this.lbIntermediaries.push(addr);\n }\n }\n }\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const amountOutMin = 0n;\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n const path: Address[] = [params.token_in, params.token_out];\n\n const data = encodeFunctionData({\n abi,\n functionName: \"swapExactTokensForTokens\",\n args: [params.amount_in, amountOutMin, path, params.recipient, deadline],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} tokens via V2`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 150_000,\n approvals: [{ token: params.token_in, spender: this.router, amount: params.amount_in }],\n };\n }\n\n async quote(params: QuoteParams): Promise<QuoteResult> {\n if (!this.rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL configured\");\n }\n\n // Try LB (Liquidity Book) quote first if lb_quoter is configured\n if (this.lbQuoter) {\n try {\n return await this.lbQuote(params);\n } catch {\n // Fall through to V2 quote\n }\n }\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const path: Address[] = [params.token_in, params.token_out];\n\n const result = await client.call({\n to: this.router,\n data: encodeFunctionData({\n abi,\n functionName: \"getAmountsOut\",\n args: [params.amount_in, path],\n }),\n });\n\n if (!result.data) {\n throw DefiError.rpcError(`[${this.protocolName}] getAmountsOut returned no data`);\n }\n\n const decoded = decodeFunctionResult({\n abi,\n functionName: \"getAmountsOut\",\n data: result.data,\n }) as unknown as bigint[];\n\n const amountOut = decoded[decoded.length - 1];\n\n return {\n protocol: this.protocolName,\n amount_out: amountOut,\n price_impact_bps: undefined,\n fee_bps: 30,\n route: [`${params.token_in} -> ${params.token_out}`],\n };\n }\n\n private async lbQuote(params: QuoteParams): Promise<QuoteResult> {\n const client = createPublicClient({ transport: http(this.rpcUrl!) });\n\n // Build candidate routes: direct + multi-hop through each intermediary\n const routes: Address[][] = [[params.token_in, params.token_out]];\n const tokenInLower = params.token_in.toLowerCase();\n const tokenOutLower = params.token_out.toLowerCase();\n for (const mid of this.lbIntermediaries) {\n if (mid.toLowerCase() !== tokenInLower && mid.toLowerCase() !== tokenOutLower) {\n routes.push([params.token_in, mid, params.token_out]);\n }\n }\n\n const lbResultParams = [\n {\n type: \"tuple\" as const,\n components: [\n { name: \"route\", type: \"address[]\" as const },\n { name: \"pairs\", type: \"address[]\" as const },\n { name: \"binSteps\", type: \"uint256[]\" as const },\n { name: \"versions\", type: \"uint256[]\" as const },\n { name: \"amounts\", type: \"uint128[]\" as const },\n { name: \"virtualAmountsWithoutSlippage\", type: \"uint128[]\" as const },\n { name: \"fees\", type: \"uint128[]\" as const },\n ],\n },\n ] as const;\n\n let bestOut = 0n;\n let bestRoute: Address[] = [];\n\n const results = await Promise.allSettled(\n routes.map(async (route) => {\n const result = await client.call({\n to: this.lbQuoter!,\n data: encodeFunctionData({\n abi: lbQuoterAbi,\n functionName: \"findBestPathFromAmountIn\",\n args: [route, params.amount_in],\n }),\n });\n if (!result.data) return { amountOut: 0n, route };\n const [quote] = decodeAbiParameters(lbResultParams, result.data);\n const amounts = quote.amounts;\n return { amountOut: amounts[amounts.length - 1], route };\n }),\n );\n\n for (const r of results) {\n if (r.status === \"fulfilled\" && r.value.amountOut > bestOut) {\n bestOut = r.value.amountOut;\n bestRoute = r.value.route;\n }\n }\n\n if (bestOut === 0n) {\n throw DefiError.rpcError(`[${this.protocolName}] LB quote returned zero for all routes`);\n }\n\n return {\n protocol: this.protocolName,\n amount_out: bestOut,\n price_impact_bps: undefined,\n fee_bps: undefined,\n route: [bestRoute.map((a) => a.slice(0, 10)).join(\" -> \") + \" (LB)\"],\n };\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi,\n functionName: \"addLiquidity\",\n args: [\n params.token_a,\n params.token_b,\n params.amount_a,\n params.amount_b,\n 0n,\n 0n,\n params.recipient,\n BigInt(\"18446744073709551615\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Add liquidity V2`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 300_000,\n approvals: [\n { token: params.token_a, spender: this.router, amount: params.amount_a },\n { token: params.token_b, spender: this.router, amount: params.amount_b },\n ],\n };\n }\n\n async buildRemoveLiquidity(params: RemoveLiquidityParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi,\n functionName: \"removeLiquidity\",\n args: [\n params.token_a,\n params.token_b,\n params.liquidity,\n 0n,\n 0n,\n params.recipient,\n BigInt(\"18446744073709551615\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Remove liquidity V2`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http, decodeAbiParameters, concatHex, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"struct ExactInputSingleParams { address tokenIn; address tokenOut; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 limitSqrtPrice; }\",\n \"function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut)\",\n]);\n\n// Algebra Integral quoter: path = tokenIn(20) + deployer(20) + tokenOut(20) per hop\n// Returns arrays for multi-hop results\nconst algebraQuoterAbi = parseAbi([\n \"function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256[] memory amountOutList, uint256[] memory amountInList, uint160[] memory sqrtPriceX96AfterList, uint32[] memory initializedTicksCrossedList, uint256 gasEstimate, uint16[] memory feeList)\",\n]);\n\n// Algebra V2 / NEST-style quoter: single-hop struct\n// selector: 0x5e5e6e0f quoteExactInputSingle((address,address,uint256,uint160))\n// returns: (uint256 amountOut, uint256 amountIn, uint160 sqrtPriceX96After)\nconst algebraSingleQuoterAbi = parseAbi([\n \"function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint160 limitSqrtPrice) params) external returns (uint256 amountOut, uint256 amountIn, uint160 sqrtPriceX96After)\",\n]);\n\n// Algebra NonfungiblePositionManager (no fee field, uses plugin instead)\nconst algebraPositionManagerAbi = parseAbi([\n \"struct MintParams { address token0; address token1; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; }\",\n \"function mint(MintParams calldata params) external payable returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1)\",\n]);\n\nexport class AlgebraV3Adapter implements IDex {\n private readonly protocolName: string;\n private readonly router: Address;\n private readonly quoter: Address | undefined;\n private readonly positionManager: Address | undefined;\n private readonly rpcUrl: string | undefined;\n // NEST and similar forks expose quoteExactInputSingle((address,address,uint256,uint160))\n // instead of path-based quoteExactInput. Detected by presence of pool_deployer in config.\n private readonly useSingleQuoter: boolean;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n this.quoter = entry.contracts?.[\"quoter\"];\n this.positionManager = entry.contracts?.[\"position_manager\"];\n this.rpcUrl = rpcUrl;\n // pool_deployer present → NEST-style single-hop struct quoter\n this.useSingleQuoter = entry.contracts?.[\"pool_deployer\"] !== undefined;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n const amountOutMinimum = 0n;\n\n const data = encodeFunctionData({\n abi,\n functionName: \"exactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n recipient: params.recipient,\n deadline,\n amountIn: params.amount_in,\n amountOutMinimum,\n limitSqrtPrice: 0n,\n },\n ],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} tokenIn for tokenOut`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 250_000,\n approvals: [{ token: params.token_in, spender: this.router, amount: params.amount_in }],\n };\n }\n\n async quote(params: QuoteParams): Promise<QuoteResult> {\n if (!this.rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL configured\");\n }\n if (!this.quoter) {\n throw DefiError.unsupported(\n `[${this.protocolName}] No quoter contract configured`,\n );\n }\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n // NEST and similar forks: use single-hop struct quoter\n if (this.useSingleQuoter) {\n const result = await client.call({\n to: this.quoter,\n data: encodeFunctionData({\n abi: algebraSingleQuoterAbi,\n functionName: \"quoteExactInputSingle\",\n args: [\n {\n tokenIn: params.token_in,\n tokenOut: params.token_out,\n amountIn: params.amount_in,\n limitSqrtPrice: 0n,\n },\n ],\n }),\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] quoteExactInputSingle failed: ${e}`);\n });\n\n if (!result.data || result.data.length < 66) {\n throw DefiError.rpcError(`[${this.protocolName}] quoter returned empty data`);\n }\n\n const [amountOut] = decodeAbiParameters(\n [\n { name: \"amountOut\", type: \"uint256\" },\n { name: \"amountIn\", type: \"uint256\" },\n { name: \"sqrtPriceX96After\", type: \"uint160\" },\n ],\n result.data,\n );\n\n return {\n protocol: this.protocolName,\n amount_out: amountOut as bigint,\n price_impact_bps: undefined,\n fee_bps: undefined,\n route: [`${params.token_in} -> ${params.token_out}`],\n };\n }\n\n // KittenSwap and standard Algebra Integral path: tokenIn(20) + deployer(20) + tokenOut(20) = 60 bytes\n // Standard pools use deployer=address(0) in path (CREATE2 salt without deployer prefix)\n const path = concatHex([params.token_in, zeroAddress as Address, params.token_out]);\n\n const result = await client.call({\n to: this.quoter,\n data: encodeFunctionData({\n abi: algebraQuoterAbi,\n functionName: \"quoteExactInput\",\n args: [path, params.amount_in],\n }),\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] quoteExactInput failed: ${e}`);\n });\n\n if (!result.data || result.data.length < 66) {\n throw DefiError.rpcError(`[${this.protocolName}] quoter returned empty data`);\n }\n\n // Decode first element: amountOutList is an array, take the last element\n const decoded = decodeAbiParameters(\n [\n { name: \"amountOutList\", type: \"uint256[]\" },\n { name: \"amountInList\", type: \"uint256[]\" },\n { name: \"sqrtPriceX96AfterList\", type: \"uint160[]\" },\n { name: \"initializedTicksCrossedList\", type: \"uint32[]\" },\n { name: \"gasEstimate\", type: \"uint256\" },\n { name: \"feeList\", type: \"uint16[]\" },\n ],\n result.data,\n );\n\n const amountOutList = decoded[0] as readonly bigint[];\n const feeList = decoded[5] as readonly number[];\n const amountOut = amountOutList[amountOutList.length - 1];\n const fee = feeList.length > 0 ? feeList[0] : undefined;\n\n return {\n protocol: this.protocolName,\n amount_out: amountOut,\n price_impact_bps: undefined,\n fee_bps: fee !== undefined ? Math.floor(fee / 10) : undefined,\n route: [`${params.token_in} -> ${params.token_out}`],\n };\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n const pm = this.positionManager;\n if (!pm) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Position manager address not configured\");\n }\n\n // Sort tokens (Algebra requires token0 < token1)\n const [token0, token1, rawAmount0, rawAmount1] =\n params.token_a.toLowerCase() < params.token_b.toLowerCase()\n ? [params.token_a, params.token_b, params.amount_a, params.amount_b]\n : [params.token_b, params.token_a, params.amount_b, params.amount_a];\n\n // Prevent liquidity=0 revert for single-side LP (same as V3)\n const amount0 = rawAmount0 === 0n && rawAmount1 > 0n ? 1n : rawAmount0;\n const amount1 = rawAmount1 === 0n && rawAmount0 > 0n ? 1n : rawAmount1;\n\n const data = encodeFunctionData({\n abi: algebraPositionManagerAbi,\n functionName: \"mint\",\n args: [\n {\n token0,\n token1,\n tickLower: -887220,\n tickUpper: 887220,\n amount0Desired: amount0,\n amount1Desired: amount1,\n amount0Min: 0n,\n amount1Min: 0n,\n recipient: params.recipient,\n deadline: BigInt(\"18446744073709551615\"),\n },\n ],\n });\n\n return {\n description: `[${this.protocolName}] Add liquidity`,\n to: pm,\n data,\n value: 0n,\n gas_estimate: 500_000,\n approvals: [\n { token: token0, spender: pm, amount: amount0 },\n { token: token1, spender: pm, amount: amount1 },\n ],\n };\n }\n\n async buildRemoveLiquidity(_params: RemoveLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] remove_liquidity requires tokenId — use NFT position manager directly`,\n );\n }\n}\n","import { encodeFunctionData, parseAbi, zeroAddress } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"function swapSingleTokenExactIn(address pool, address tokenIn, address tokenOut, uint256 exactAmountIn, uint256 minAmountOut, uint256 deadline, bool wethIsEth, bytes calldata userData) external returns (uint256 amountOut)\",\n]);\n\nexport class BalancerV3Adapter implements IDex {\n private readonly protocolName: string;\n private readonly router: `0x${string}`;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract\");\n }\n this.router = router;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const minAmountOut = 0n;\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n\n // Balancer V3 requires a pool address. For now use a simplified single-pool swap.\n // In production, the pool would be resolved from the registry or an on-chain query.\n const data = encodeFunctionData({\n abi,\n functionName: \"swapSingleTokenExactIn\",\n args: [\n zeroAddress, // TODO: resolve pool from registry\n params.token_in,\n params.token_out,\n params.amount_in,\n minAmountOut,\n deadline,\n false,\n \"0x\",\n ],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} via Balancer V3`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async quote(_params: QuoteParams): Promise<QuoteResult> {\n throw DefiError.unsupported(`[${this.protocolName}] quote requires RPC`);\n }\n\n async buildAddLiquidity(_params: AddLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] add_liquidity requires pool-specific params`);\n }\n\n async buildRemoveLiquidity(_params: RemoveLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] remove_liquidity requires pool-specific params`);\n }\n}\n","import { encodeFunctionData, parseAbi } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst poolAbi = parseAbi([\n \"function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256)\",\n \"function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256)\",\n \"function add_liquidity(uint256[2] amounts, uint256 min_mint_amount) external returns (uint256)\",\n \"function remove_liquidity(uint256 amount, uint256[2] min_amounts) external returns (uint256[2])\",\n]);\n\nexport class CurveStableSwapAdapter implements IDex {\n private readonly protocolName: string;\n private readonly router: `0x${string}`;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n // Direct pool exchange: swap token at index 0 for token at index 1.\n // The `router` address is treated as the pool address for direct swaps.\n // Callers should set the pool address as the \"router\" contract in the registry\n // when targeting a specific Curve pool.\n // Without prior quote, set min output to 0. Use quote() first for slippage protection.\n const minDy = 0n;\n\n const data = encodeFunctionData({\n abi: poolAbi,\n functionName: \"exchange\",\n args: [0n, 1n, params.amount_in, minDy],\n });\n\n return {\n description: `[${this.protocolName}] Curve pool exchange ${params.amount_in} tokens (index 0 -> 1)`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async quote(_params: QuoteParams): Promise<QuoteResult> {\n throw DefiError.unsupported(`[${this.protocolName}] quote requires RPC connection`);\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n // Add liquidity to a 2-token Curve pool\n const data = encodeFunctionData({\n abi: poolAbi,\n functionName: \"add_liquidity\",\n args: [[params.amount_a, params.amount_b], 0n],\n });\n\n return {\n description: `[${this.protocolName}] Curve add liquidity`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 400_000,\n };\n }\n\n async buildRemoveLiquidity(params: RemoveLiquidityParams): Promise<DeFiTx> {\n // Remove liquidity from a 2-token Curve pool\n const data = encodeFunctionData({\n abi: poolAbi,\n functionName: \"remove_liquidity\",\n args: [params.liquidity, [0n, 0n]],\n });\n\n return {\n description: `[${this.protocolName}] Curve remove liquidity`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http, decodeAbiParameters } from \"viem\";\nimport type { Address, PublicClient } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"struct Route { address from; address to; bool stable; }\",\n \"function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, (address from, address to, bool stable)[] calldata routes, address to, uint256 deadline) external returns (uint256[] memory amounts)\",\n \"function getAmountsOut(uint256 amountIn, (address from, address to, bool stable)[] calldata routes) external view returns (uint256[] memory amounts)\",\n \"function addLiquidity(address tokenA, address tokenB, bool stable, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB, uint256 liquidity)\",\n \"function removeLiquidity(address tokenA, address tokenB, bool stable, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint256 amountA, uint256 amountB)\",\n]);\n\n// Velodrome V2 / Aerodrome style: Route includes factory address\nconst abiV2 = parseAbi([\n \"function getAmountsOut(uint256 amountIn, (address from, address to, bool stable, address factory)[] calldata routes) external view returns (uint256[] memory amounts)\",\n]);\n\nexport class SolidlyAdapter implements IDex {\n private readonly protocolName: string;\n private readonly router: `0x${string}`;\n /** Default to volatile (false). True for stablecoin pairs. */\n private readonly defaultStable: boolean;\n private readonly rpcUrl: string | undefined;\n /** Factory address — present on Velodrome V2 / Aerodrome forks */\n private readonly factory: Address | undefined;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract address\");\n }\n this.router = router;\n this.defaultStable = false;\n this.rpcUrl = rpcUrl;\n this.factory = entry.contracts?.[\"factory\"];\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const amountOutMin = 0n;\n const deadline = BigInt(params.deadline ?? 18446744073709551615n);\n\n const routes = [\n { from: params.token_in, to: params.token_out, stable: this.defaultStable },\n ];\n\n const data = encodeFunctionData({\n abi,\n functionName: \"swapExactTokensForTokens\",\n args: [params.amount_in, amountOutMin, routes, params.recipient, deadline],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} tokens via Solidly`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 200_000,\n approvals: [{ token: params.token_in, spender: this.router, amount: params.amount_in }],\n };\n }\n\n private async callGetAmountsOut(\n client: PublicClient,\n callData: `0x${string}`,\n ): Promise<bigint> {\n const result = await client.call({ to: this.router, data: callData });\n if (!result.data) return 0n;\n const [amounts] = decodeAbiParameters(\n [{ name: \"amounts\", type: \"uint256[]\" }],\n result.data,\n );\n return amounts.length >= 2 ? amounts[amounts.length - 1] : 0n;\n }\n\n private encodeV1(params: QuoteParams, stable: boolean): `0x${string}` {\n return encodeFunctionData({\n abi,\n functionName: \"getAmountsOut\",\n args: [params.amount_in, [{ from: params.token_in, to: params.token_out, stable }]],\n });\n }\n\n private encodeV2(params: QuoteParams, stable: boolean): `0x${string}` {\n return encodeFunctionData({\n abi: abiV2,\n functionName: \"getAmountsOut\",\n args: [params.amount_in, [{ from: params.token_in, to: params.token_out, stable, factory: this.factory! }]],\n });\n }\n\n async quote(params: QuoteParams): Promise<QuoteResult> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n // Try all combinations: [volatile, stable] x [V1 ABI, V2 ABI (if factory present)]\n // Pick the best (highest amountOut)\n const candidates: Array<{ callData: `0x${string}`; stable: boolean }> = [\n { callData: this.encodeV1(params, false), stable: false },\n { callData: this.encodeV1(params, true), stable: true },\n ];\n if (this.factory) {\n candidates.unshift(\n { callData: this.encodeV2(params, false), stable: false },\n { callData: this.encodeV2(params, true), stable: true },\n );\n }\n\n const results = await Promise.allSettled(\n candidates.map((c) => this.callGetAmountsOut(client, c.callData)),\n );\n\n let bestOut = 0n;\n let bestStable = false;\n for (let i = 0; i < results.length; i++) {\n const r = results[i];\n if (r.status === \"fulfilled\" && r.value > bestOut) {\n bestOut = r.value;\n bestStable = candidates[i].stable;\n }\n }\n\n if (bestOut === 0n) {\n throw DefiError.rpcError(`[${this.protocolName}] getAmountsOut returned zero for all routes`);\n }\n\n return {\n protocol: this.protocolName,\n amount_out: bestOut,\n price_impact_bps: undefined,\n fee_bps: bestStable ? 4 : 20,\n route: [`${params.token_in} -> ${params.token_out} (stable: ${bestStable})`],\n };\n }\n\n async buildAddLiquidity(params: AddLiquidityParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi,\n functionName: \"addLiquidity\",\n args: [\n params.token_a,\n params.token_b,\n this.defaultStable,\n params.amount_a,\n params.amount_b,\n 0n,\n 0n,\n params.recipient,\n BigInt(\"18446744073709551615\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Add liquidity (Solidly)`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 350_000,\n approvals: [\n { token: params.token_a, spender: this.router, amount: params.amount_a },\n { token: params.token_b, spender: this.router, amount: params.amount_b },\n ],\n };\n }\n\n async buildRemoveLiquidity(params: RemoveLiquidityParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi,\n functionName: \"removeLiquidity\",\n args: [\n params.token_a,\n params.token_b,\n this.defaultStable,\n params.liquidity,\n 0n,\n 0n,\n params.recipient,\n BigInt(\"18446744073709551615\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Remove liquidity (Solidly)`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n}\n","import { encodeFunctionData, parseAbi, zeroAddress } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IDex,\n ProtocolEntry,\n SwapParams,\n QuoteParams,\n QuoteResult,\n AddLiquidityParams,\n RemoveLiquidityParams,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst abi = parseAbi([\n \"function swap(address fromToken, address toToken, uint256 fromAmount, uint256 minToAmount, address to, address rebateTo) external payable returns (uint256 realToAmount)\",\n]);\n\nexport class WooFiAdapter implements IDex {\n private readonly protocolName: string;\n private readonly router: `0x${string}`;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const router = entry.contracts?.[\"router\"];\n if (!router) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'router' contract\");\n }\n this.router = router;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSwap(params: SwapParams): Promise<DeFiTx> {\n const minToAmount = 0n;\n\n const data = encodeFunctionData({\n abi,\n functionName: \"swap\",\n args: [\n params.token_in,\n params.token_out,\n params.amount_in,\n minToAmount,\n params.recipient,\n zeroAddress,\n ],\n });\n\n return {\n description: `[${this.protocolName}] Swap ${params.amount_in} via WOOFi`,\n to: this.router,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async quote(_params: QuoteParams): Promise<QuoteResult> {\n throw DefiError.unsupported(`[${this.protocolName}] quote requires RPC`);\n }\n\n async buildAddLiquidity(_params: AddLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] WOOFi does not support LP positions via router`);\n }\n\n async buildRemoveLiquidity(_params: RemoveLiquidityParams): Promise<DeFiTx> {\n throw DefiError.unsupported(`[${this.protocolName}] WOOFi does not support LP positions via router`);\n }\n}\n","import { createPublicClient, encodeFunctionData, http, parseAbi, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IGaugeSystem,\n ProtocolEntry,\n RewardInfo,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst gaugeAbi = parseAbi([\n \"function deposit(uint256 amount) external\",\n \"function depositFor(uint256 amount, uint256 tokenId) external\",\n \"function withdraw(uint256 amount) external\",\n \"function getReward(address account) external\",\n \"function getReward(address account, address[] tokens) external\",\n \"function earned(address account) external view returns (uint256)\",\n \"function earned(address token, address account) external view returns (uint256)\",\n \"function rewardRate() external view returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function rewardsListLength() external view returns (uint256)\",\n \"function isReward(address token) external view returns (bool)\",\n]);\n\nconst veAbi = parseAbi([\n \"function create_lock(uint256 value, uint256 lock_duration) external returns (uint256)\",\n \"function increase_amount(uint256 tokenId, uint256 value) external\",\n \"function increase_unlock_time(uint256 tokenId, uint256 lock_duration) external\",\n \"function withdraw(uint256 tokenId) external\",\n \"function balanceOfNFT(uint256 tokenId) external view returns (uint256)\",\n \"function locked(uint256 tokenId) external view returns (uint256 amount, uint256 end)\",\n]);\n\nconst voterAbi = parseAbi([\n \"function vote(uint256 tokenId, address[] calldata pools, uint256[] calldata weights) external\",\n \"function claimBribes(address[] calldata bribes, address[][] calldata tokens, uint256 tokenId) external\",\n \"function claimFees(address[] calldata fees, address[][] calldata tokens, uint256 tokenId) external\",\n \"function gauges(address pool) external view returns (address)\",\n]);\n\nexport class SolidlyGaugeAdapter implements IGaugeSystem {\n private readonly protocolName: string;\n private readonly voter: Address;\n private readonly veToken: Address;\n private readonly rpcUrl: string | undefined;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const voter = entry.contracts?.[\"voter\"];\n if (!voter) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'voter' contract\");\n }\n const veToken = entry.contracts?.[\"ve_token\"];\n if (!veToken) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 've_token' contract\");\n }\n this.voter = voter;\n this.veToken = veToken;\n this.rpcUrl = rpcUrl;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n // IGauge\n\n async buildDeposit(gauge: Address, amount: bigint, tokenId?: bigint, lpToken?: Address): Promise<DeFiTx> {\n if (tokenId !== undefined) {\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"depositFor\",\n args: [amount, tokenId],\n });\n return {\n description: `[${this.protocolName}] Deposit ${amount} LP to gauge (boost veNFT #${tokenId})`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 200_000,\n approvals: lpToken ? [{ token: lpToken, spender: gauge, amount }] : undefined,\n };\n }\n\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"deposit\",\n args: [amount],\n });\n return {\n description: `[${this.protocolName}] Deposit ${amount} LP to gauge`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 200_000,\n approvals: lpToken ? [{ token: lpToken, spender: gauge, amount }] : undefined,\n };\n }\n\n async buildWithdraw(gauge: Address, amount: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"withdraw\",\n args: [amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${amount} LP from gauge`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async buildClaimRewards(gauge: Address, account?: Address): Promise<DeFiTx> {\n // Ramses V2 gauges use getReward(address account, address[] tokens)\n // where account must equal msg.sender. Try to discover reward tokens via RPC.\n if (account && this.rpcUrl) {\n try {\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const listLen = await client.readContract({\n address: gauge,\n abi: gaugeAbi,\n functionName: \"rewardsListLength\",\n }) as bigint;\n if (listLen > 0n) {\n // Discover reward tokens by checking isReward against known tokens\n // For Ramses V2, use the voter to find reward tokens\n // Alternatively, scan storage: the gauge exposes earned(token, account)\n // We'll pass empty tokens array and let the gauge figure it out,\n // or pass a placeholder. Since we know RAM is the reward token\n // from the gauge context, we need to enumerate them.\n // Fallback: use getReward(account, []) — some implementations accept empty array\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"getReward\",\n args: [account, [] as Address[]],\n });\n return {\n description: `[${this.protocolName}] Claim gauge rewards`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n } catch {\n // fall through to default\n }\n }\n\n // Standard Solidly V2 gauge: getReward(address account)\n // account param will be overridden by msg.sender in most gauge implementations\n const data = encodeFunctionData({\n abi: gaugeAbi,\n functionName: \"getReward\",\n args: [account ?? zeroAddress],\n });\n return {\n description: `[${this.protocolName}] Claim gauge rewards`,\n to: gauge,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async getPendingRewards(_gauge: Address, _user: Address): Promise<RewardInfo[]> {\n throw DefiError.unsupported(`[${this.protocolName}] get_pending_rewards requires RPC`);\n }\n\n // IVoteEscrow\n\n async buildCreateLock(amount: bigint, lockDuration: number): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: veAbi,\n functionName: \"create_lock\",\n args: [amount, BigInt(lockDuration)],\n });\n return {\n description: `[${this.protocolName}] Create veNFT lock: ${amount} tokens for ${lockDuration}s`,\n to: this.veToken,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildIncreaseAmount(tokenId: bigint, amount: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: veAbi,\n functionName: \"increase_amount\",\n args: [tokenId, amount],\n });\n return {\n description: `[${this.protocolName}] Increase veNFT #${tokenId} by ${amount}`,\n to: this.veToken,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async buildIncreaseUnlockTime(tokenId: bigint, lockDuration: number): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: veAbi,\n functionName: \"increase_unlock_time\",\n args: [tokenId, BigInt(lockDuration)],\n });\n return {\n description: `[${this.protocolName}] Extend veNFT #${tokenId} lock by ${lockDuration}s`,\n to: this.veToken,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async buildWithdrawExpired(tokenId: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: veAbi,\n functionName: \"withdraw\",\n args: [tokenId],\n });\n return {\n description: `[${this.protocolName}] Withdraw expired veNFT #${tokenId}`,\n to: this.veToken,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n // IVoter\n\n async buildVote(tokenId: bigint, pools: Address[], weights: bigint[]): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: voterAbi,\n functionName: \"vote\",\n args: [tokenId, pools, weights],\n });\n return {\n description: `[${this.protocolName}] Vote with veNFT #${tokenId}`,\n to: this.voter,\n data,\n value: 0n,\n gas_estimate: 500_000,\n };\n }\n\n async buildClaimBribes(bribes: Address[], tokenId: bigint): Promise<DeFiTx> {\n // claimBribes needs token arrays per bribe contract — simplified version\n const tokensPerBribe: Address[][] = bribes.map(() => []);\n const data = encodeFunctionData({\n abi: voterAbi,\n functionName: \"claimBribes\",\n args: [bribes, tokensPerBribe, tokenId],\n });\n return {\n description: `[${this.protocolName}] Claim bribes for veNFT #${tokenId}`,\n to: this.voter,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildClaimFees(fees: Address[], tokenId: bigint): Promise<DeFiTx> {\n const tokensPerFee: Address[][] = fees.map(() => []);\n const data = encodeFunctionData({\n abi: voterAbi,\n functionName: \"claimFees\",\n args: [fees, tokensPerFee, tokenId],\n });\n return {\n description: `[${this.protocolName}] Claim trading fees for veNFT #${tokenId}`,\n to: this.voter,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n}\n","import { encodeFunctionData, parseAbi, createPublicClient, http } from \"viem\";\nimport type { Address } from \"viem\";\n\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type {\n IGauge,\n ProtocolEntry,\n RewardInfo,\n DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst masterchefAbi = parseAbi([\n \"function deposit(uint256 pid, uint256 amount) external\",\n \"function withdraw(uint256 pid, uint256 amount) external\",\n \"function claim(uint256[] calldata pids) external\",\n \"function pendingRewards(address account, uint256[] calldata pids) view returns (uint256[] memory moeRewards)\",\n \"function getNumberOfFarms() view returns (uint256)\",\n \"function getPidByPool(address pool) view returns (uint256)\",\n]);\n\nexport class MasterChefAdapter implements IGauge {\n private readonly protocolName: string;\n private readonly masterchef: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n const masterchef = entry.contracts?.[\"masterchef\"];\n if (!masterchef) {\n throw new DefiError(\"CONTRACT_ERROR\", \"Missing 'masterchef' contract\");\n }\n this.masterchef = masterchef;\n this.rpcUrl = rpcUrl;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n /**\n * Deposit LP tokens into a MasterChef farm.\n * `gauge` is the pool address (unused for calldata — MasterChef is the target).\n * `tokenId` carries the farm pid.\n */\n async buildDeposit(gauge: Address, amount: bigint, tokenId?: bigint): Promise<DeFiTx> {\n const pid = tokenId ?? 0n;\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"deposit\",\n args: [pid, amount],\n });\n return {\n description: `[${this.protocolName}] Deposit ${amount} LP to farm pid=${pid} (pool ${gauge})`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /**\n * Withdraw LP tokens from a MasterChef farm.\n * `gauge` is used to look up the pid description only; call site should pass pid via tokenId\n * on the deposit flow. Here pid defaults to 0 — callers should encode the pid in the gauge\n * address slot or wrap this adapter with a pid-aware helper.\n */\n async buildWithdraw(gauge: Address, amount: bigint): Promise<DeFiTx> {\n // IGauge interface does not carry tokenId on withdraw; default pid=0.\n // Callers that need a specific pid should call buildWithdrawPid directly.\n const pid = 0n;\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"withdraw\",\n args: [pid, amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${amount} LP from farm pid=${pid} (pool ${gauge})`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /** Withdraw LP tokens specifying a pid explicitly (MasterChef extension beyond IGauge). */\n async buildWithdrawPid(pid: bigint, amount: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"withdraw\",\n args: [pid, amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${amount} LP from farm pid=${pid}`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /** Claim pending MOE rewards. IGauge interface provides no pid — defaults to pid=0. */\n async buildClaimRewards(gauge: Address): Promise<DeFiTx> {\n const pid = 0n;\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"claim\",\n args: [[pid]],\n });\n return {\n description: `[${this.protocolName}] Claim MOE rewards for farm pid=${pid} (pool ${gauge})`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /** Claim pending MOE rewards for a specific pid (MasterChef extension beyond IGauge). */\n async buildClaimRewardsPid(pid: bigint): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: masterchefAbi,\n functionName: \"claim\",\n args: [[pid]],\n });\n return {\n description: `[${this.protocolName}] Claim MOE rewards for farm pid=${pid}`,\n to: this.masterchef,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n /** Get pending MOE rewards for a user. Requires rpcUrl. */\n async getPendingRewards(_gauge: Address, user: Address): Promise<RewardInfo[]> {\n if (!this.rpcUrl) {\n throw DefiError.unsupported(`[${this.protocolName}] getPendingRewards requires RPC`);\n }\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const rewards = await client.readContract({\n address: this.masterchef,\n abi: masterchefAbi,\n functionName: \"pendingRewards\",\n args: [user, [0n]],\n });\n return (rewards as bigint[]).map((amount) => ({\n token: this.masterchef,\n symbol: \"MOE\",\n amount,\n }));\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n InterestRateMode,\n} from \"@hypurrquant/defi-core\";\n\nconst POOL_ABI = parseAbi([\n \"function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external\",\n \"function borrow(address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf) external\",\n \"function repay(address asset, uint256 amount, uint256 interestRateMode, address onBehalfOf) external returns (uint256)\",\n \"function withdraw(address asset, uint256 amount, address to) external returns (uint256)\",\n \"function getUserAccountData(address user) external view returns (uint256 totalCollateralBase, uint256 totalDebtBase, uint256 availableBorrowsBase, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)\",\n \"function getReserveData(address asset) external view returns (uint256 configuration, uint128 liquidityIndex, uint128 currentLiquidityRate, uint128 variableBorrowIndex, uint128 currentVariableBorrowRate, uint128 currentStableBorrowRate, uint40 lastUpdateTimestamp, uint16 id, address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress, uint128 accruedToTreasury, uint128 unbacked, uint128 isolationModeTotalDebt)\",\n]);\n\nconst ERC20_ABI = parseAbi([\n \"function totalSupply() external view returns (uint256)\",\n]);\n\nconst INCENTIVES_ABI = parseAbi([\n \"function getIncentivesController() external view returns (address)\",\n]);\n\nconst REWARDS_CONTROLLER_ABI = parseAbi([\n \"function getRewardsByAsset(address asset) external view returns (address[])\",\n \"function getRewardsData(address asset, address reward) external view returns (uint256 index, uint256 emissionsPerSecond, uint256 lastUpdateTimestamp, uint256 distributionEnd)\",\n]);\n\nconst POOL_PROVIDER_ABI = parseAbi([\n \"function ADDRESSES_PROVIDER() external view returns (address)\",\n]);\n\nconst ADDRESSES_PROVIDER_ABI = parseAbi([\n \"function getPriceOracle() external view returns (address)\",\n]);\n\nconst ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n \"function BASE_CURRENCY_UNIT() external view returns (uint256)\",\n]);\n\nconst ERC20_DECIMALS_ABI = parseAbi([\n \"function decimals() external view returns (uint8)\",\n]);\n\nfunction u256ToF64(v: bigint): number {\n const MAX_U128 = (1n << 128n) - 1n;\n if (v > MAX_U128) return Infinity;\n return Number(v);\n}\n\nexport class AaveV3Adapter implements ILending {\n private readonly protocolName: string;\n private readonly pool: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const pool = entry.contracts?.[\"pool\"];\n if (!pool) throw DefiError.contractError(`[${entry.name}] Missing 'pool' contract address`);\n this.pool = pool;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"supply\",\n args: [params.asset, params.amount, params.on_behalf_of, 0],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 300_000,\n approvals: [{ token: params.asset, spender: this.pool, amount: params.amount }],\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const rateMode = params.interest_rate_mode === InterestRateMode.Stable ? 1n : 2n;\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"borrow\",\n args: [params.asset, params.amount, rateMode, 0, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const rateMode = params.interest_rate_mode === InterestRateMode.Stable ? 1n : 2n;\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"repay\",\n args: [params.asset, params.amount, rateMode, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 300_000,\n approvals: [{ token: params.asset, spender: this.pool, amount: params.amount }],\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"withdraw\",\n args: [params.asset, params.amount, params.to],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.amount} from pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const result = await client.readContract({\n address: this.pool,\n abi: POOL_ABI,\n functionName: \"getReserveData\",\n args: [asset],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getReserveData failed: ${e}`);\n });\n\n const RAY = 1e27;\n const SECONDS_PER_YEAR = 31536000;\n\n // Convert ray rate to APY: ((1 + rate/SECONDS_PER_YEAR)^SECONDS_PER_YEAR - 1) * 100\n const toApy = (rayRate: bigint): number => {\n const rate = Number(rayRate) / RAY;\n return (Math.pow(1 + rate / SECONDS_PER_YEAR, SECONDS_PER_YEAR) - 1) * 100;\n };\n\n const supplyRate = toApy(result[2]);\n const variableRate = toApy(result[4]);\n const stableRate = toApy(result[5]);\n\n const aTokenAddress = result[8] as Address;\n const variableDebtTokenAddress = result[10] as Address;\n\n const [totalSupply, totalBorrow] = await Promise.all([\n client.readContract({\n address: aTokenAddress,\n abi: ERC20_ABI,\n functionName: \"totalSupply\",\n }).catch(() => 0n),\n client.readContract({\n address: variableDebtTokenAddress,\n abi: ERC20_ABI,\n functionName: \"totalSupply\",\n }).catch(() => 0n),\n ]);\n\n const utilization = totalSupply > 0n\n ? Number((totalBorrow * 10000n) / totalSupply) / 100\n : 0;\n\n // Fetch incentive/reward data (best-effort, never breaks base rates)\n const supplyRewardTokens: string[] = [];\n const borrowRewardTokens: string[] = [];\n const supplyEmissions: string[] = [];\n const borrowEmissions: string[] = [];\n\n try {\n const controllerAddr = await client.readContract({\n address: aTokenAddress,\n abi: INCENTIVES_ABI,\n functionName: \"getIncentivesController\",\n });\n\n if (controllerAddr && controllerAddr !== zeroAddress) {\n const [supplyRewards, borrowRewards] = await Promise.all([\n client.readContract({\n address: controllerAddr,\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsByAsset\",\n args: [aTokenAddress],\n }).catch(() => [] as Address[]),\n client.readContract({\n address: controllerAddr,\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsByAsset\",\n args: [variableDebtTokenAddress],\n }).catch(() => [] as Address[]),\n ]);\n\n // Fetch emissions data for supply rewards\n const supplyDataPromises = supplyRewards.map((reward) =>\n client.readContract({\n address: controllerAddr,\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsData\",\n args: [aTokenAddress, reward],\n }).catch(() => null),\n );\n const supplyData = await Promise.all(supplyDataPromises);\n for (let i = 0; i < supplyRewards.length; i++) {\n const data = supplyData[i];\n if (data && data[1] > 0n) {\n supplyRewardTokens.push(supplyRewards[i]);\n supplyEmissions.push(data[1].toString());\n }\n }\n\n // Fetch emissions data for borrow rewards\n const borrowDataPromises = borrowRewards.map((reward) =>\n client.readContract({\n address: controllerAddr,\n abi: REWARDS_CONTROLLER_ABI,\n functionName: \"getRewardsData\",\n args: [variableDebtTokenAddress, reward],\n }).catch(() => null),\n );\n const borrowData = await Promise.all(borrowDataPromises);\n for (let i = 0; i < borrowRewards.length; i++) {\n const data = borrowData[i];\n if (data && data[1] > 0n) {\n borrowRewardTokens.push(borrowRewards[i]);\n borrowEmissions.push(data[1].toString());\n }\n }\n }\n } catch {\n // Incentives not supported by this deployment — silently ignore\n }\n\n // Calculate incentive APY from emissions using oracle prices\n let supplyIncentiveApy: number | undefined;\n let borrowIncentiveApy: number | undefined;\n\n const hasSupplyRewards = supplyRewardTokens.length > 0;\n const hasBorrowRewards = borrowRewardTokens.length > 0;\n\n if ((hasSupplyRewards || hasBorrowRewards) && totalSupply > 0n) {\n try {\n // Pool → AddressesProvider → Oracle\n const providerAddr = await client.readContract({\n address: this.pool,\n abi: POOL_PROVIDER_ABI,\n functionName: \"ADDRESSES_PROVIDER\",\n });\n const oracleAddr = await client.readContract({\n address: providerAddr,\n abi: ADDRESSES_PROVIDER_ABI,\n functionName: \"getPriceOracle\",\n });\n const [assetPrice, baseCurrencyUnit, assetDecimals] = await Promise.all([\n client.readContract({\n address: oracleAddr,\n abi: ORACLE_ABI,\n functionName: \"getAssetPrice\",\n args: [asset],\n }),\n client.readContract({\n address: oracleAddr,\n abi: ORACLE_ABI,\n functionName: \"BASE_CURRENCY_UNIT\",\n }),\n client.readContract({\n address: asset,\n abi: ERC20_DECIMALS_ABI,\n functionName: \"decimals\",\n }).catch(() => 18),\n ]);\n\n const priceUnit = Number(baseCurrencyUnit);\n const assetPriceF = Number(assetPrice) / priceUnit;\n const assetDecimalsDivisor = 10 ** assetDecimals;\n\n // Supply-side incentive APY\n if (hasSupplyRewards) {\n let totalSupplyIncentiveUsdPerYear = 0;\n const totalSupplyUsd = (Number(totalSupply) / assetDecimalsDivisor) * assetPriceF;\n\n for (let i = 0; i < supplyRewardTokens.length; i++) {\n const emissionPerSec = BigInt(supplyEmissions[i]);\n const [rewardPrice, rewardDecimals] = await Promise.all([\n client.readContract({\n address: oracleAddr,\n abi: ORACLE_ABI,\n functionName: \"getAssetPrice\",\n args: [supplyRewardTokens[i] as Address],\n }).catch(() => 0n),\n client.readContract({\n address: supplyRewardTokens[i] as Address,\n abi: ERC20_DECIMALS_ABI,\n functionName: \"decimals\",\n }).catch(() => 18),\n ]);\n if (rewardPrice > 0n) {\n const rewardPriceF = Number(rewardPrice) / priceUnit;\n const emissionPerYear = (Number(emissionPerSec) / (10 ** rewardDecimals)) * SECONDS_PER_YEAR;\n totalSupplyIncentiveUsdPerYear += emissionPerYear * rewardPriceF;\n }\n }\n if (totalSupplyUsd > 0) {\n supplyIncentiveApy = (totalSupplyIncentiveUsdPerYear / totalSupplyUsd) * 100;\n }\n }\n\n // Borrow-side incentive APY\n if (hasBorrowRewards && totalBorrow > 0n) {\n let totalBorrowIncentiveUsdPerYear = 0;\n const totalBorrowUsd = (Number(totalBorrow) / assetDecimalsDivisor) * assetPriceF;\n\n for (let i = 0; i < borrowRewardTokens.length; i++) {\n const emissionPerSec = BigInt(borrowEmissions[i]);\n const [rewardPrice, rewardDecimals] = await Promise.all([\n client.readContract({\n address: oracleAddr,\n abi: ORACLE_ABI,\n functionName: \"getAssetPrice\",\n args: [borrowRewardTokens[i] as Address],\n }).catch(() => 0n),\n client.readContract({\n address: borrowRewardTokens[i] as Address,\n abi: ERC20_DECIMALS_ABI,\n functionName: \"decimals\",\n }).catch(() => 18),\n ]);\n if (rewardPrice > 0n) {\n const rewardPriceF = Number(rewardPrice) / priceUnit;\n const emissionPerYear = (Number(emissionPerSec) / (10 ** rewardDecimals)) * SECONDS_PER_YEAR;\n totalBorrowIncentiveUsdPerYear += emissionPerYear * rewardPriceF;\n }\n }\n if (totalBorrowUsd > 0) {\n borrowIncentiveApy = (totalBorrowIncentiveUsdPerYear / totalBorrowUsd) * 100;\n }\n }\n } catch {\n // Oracle not available — skip incentive APY calculation\n }\n }\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyRate,\n borrow_variable_apy: variableRate,\n borrow_stable_apy: stableRate,\n utilization,\n total_supply: totalSupply,\n total_borrow: totalBorrow,\n ...(hasSupplyRewards && {\n supply_reward_tokens: supplyRewardTokens,\n supply_emissions_per_second: supplyEmissions,\n }),\n ...(hasBorrowRewards && {\n borrow_reward_tokens: borrowRewardTokens,\n borrow_emissions_per_second: borrowEmissions,\n }),\n ...(supplyIncentiveApy !== undefined && { supply_incentive_apy: supplyIncentiveApy }),\n ...(borrowIncentiveApy !== undefined && { borrow_incentive_apy: borrowIncentiveApy }),\n };\n }\n\n async getUserPosition(user: Address): Promise<UserPosition> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const result = await client.readContract({\n address: this.pool,\n abi: POOL_ABI,\n functionName: \"getUserAccountData\",\n args: [user],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getUserAccountData failed: ${e}`);\n });\n\n const [totalCollateralBase, totalDebtBase, , , ltv, healthFactor] = result;\n const MAX_UINT256 = 2n ** 256n - 1n;\n const hf = healthFactor >= MAX_UINT256 ? Infinity : Number(healthFactor) / 1e18;\n const collateralUsd = u256ToF64(totalCollateralBase) / 1e8;\n const debtUsd = u256ToF64(totalDebtBase) / 1e8;\n const ltvBps = u256ToF64(ltv);\n\n const supplies = collateralUsd > 0\n ? [{ asset: zeroAddress as Address, symbol: \"Total Collateral\", amount: totalCollateralBase, value_usd: collateralUsd }]\n : [];\n const borrows = debtUsd > 0\n ? [{ asset: zeroAddress as Address, symbol: \"Total Debt\", amount: totalDebtBase, value_usd: debtUsd }]\n : [];\n\n return {\n protocol: this.protocolName,\n user,\n supplies,\n borrows,\n health_factor: hf,\n net_apy: ltvBps / 100,\n };\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n InterestRateMode,\n} from \"@hypurrquant/defi-core\";\n\n// V2 uses deposit/borrow/repay/withdraw (same as V3 for borrow/repay/withdraw)\nconst POOL_ABI = parseAbi([\n \"function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external\",\n \"function borrow(address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf) external\",\n \"function repay(address asset, uint256 amount, uint256 rateMode, address onBehalfOf) external returns (uint256)\",\n \"function withdraw(address asset, uint256 amount, address to) external returns (uint256)\",\n \"function getUserAccountData(address user) external view returns (uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)\",\n // V2 getReserveData: 12 fields (no accruedToTreasury/unbacked/isolationModeTotalDebt)\n // positions: [0]=configuration, [1]=liquidityIndex, [2]=variableBorrowIndex,\n // [3]=currentLiquidityRate, [4]=currentVariableBorrowRate, [5]=currentStableBorrowRate,\n // [6]=lastUpdateTimestamp, [7]=aTokenAddress, [8]=stableDebtTokenAddress,\n // [9]=variableDebtTokenAddress, [10]=interestRateStrategyAddress, [11]=id\n \"function getReserveData(address asset) external view returns (uint256 configuration, uint128 liquidityIndex, uint128 variableBorrowIndex, uint128 currentLiquidityRate, uint128 currentVariableBorrowRate, uint128 currentStableBorrowRate, uint40 lastUpdateTimestamp, address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress, uint8 id)\",\n]);\n\nconst ERC20_ABI = parseAbi([\n \"function totalSupply() external view returns (uint256)\",\n]);\n\nfunction u256ToF64(v: bigint): number {\n const MAX_U128 = (1n << 128n) - 1n;\n if (v > MAX_U128) return Infinity;\n return Number(v);\n}\n\nexport class AaveV2Adapter implements ILending {\n private readonly protocolName: string;\n private readonly pool: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const pool = entry.contracts?.[\"pool\"];\n if (!pool) throw DefiError.contractError(`[${entry.name}] Missing 'pool' contract address`);\n this.pool = pool;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"deposit\",\n args: [params.asset, params.amount, params.on_behalf_of, 0],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 300_000,\n approvals: [{ token: params.asset, spender: this.pool, amount: params.amount }],\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const rateMode = params.interest_rate_mode === InterestRateMode.Stable ? 1n : 2n;\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"borrow\",\n args: [params.asset, params.amount, rateMode, 0, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const rateMode = params.interest_rate_mode === InterestRateMode.Stable ? 1n : 2n;\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"repay\",\n args: [params.asset, params.amount, rateMode, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 300_000,\n approvals: [{ token: params.asset, spender: this.pool, amount: params.amount }],\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: POOL_ABI,\n functionName: \"withdraw\",\n args: [params.asset, params.amount, params.to],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.amount} from pool`,\n to: this.pool,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const result = await client.readContract({\n address: this.pool,\n abi: POOL_ABI,\n functionName: \"getReserveData\",\n args: [asset],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getReserveData failed: ${e}`);\n });\n\n const RAY = 1e27;\n const SECONDS_PER_YEAR = 31536000;\n\n // Convert ray rate to APY: ((1 + rate/SECONDS_PER_YEAR)^SECONDS_PER_YEAR - 1) * 100\n const toApy = (rayRate: bigint): number => {\n const rate = Number(rayRate) / RAY;\n return (Math.pow(1 + rate / SECONDS_PER_YEAR, SECONDS_PER_YEAR) - 1) * 100;\n };\n\n // V2 field positions:\n // [3] = currentLiquidityRate, [4] = currentVariableBorrowRate, [5] = currentStableBorrowRate\n // [7] = aTokenAddress, [9] = variableDebtTokenAddress\n const supplyRate = toApy(result[3]);\n const variableRate = toApy(result[4]);\n const stableRate = toApy(result[5]);\n\n const aTokenAddress = result[7] as Address;\n const variableDebtTokenAddress = result[9] as Address;\n\n const [totalSupply, totalBorrow] = await Promise.all([\n client.readContract({\n address: aTokenAddress,\n abi: ERC20_ABI,\n functionName: \"totalSupply\",\n }).catch(() => 0n),\n client.readContract({\n address: variableDebtTokenAddress,\n abi: ERC20_ABI,\n functionName: \"totalSupply\",\n }).catch(() => 0n),\n ]);\n\n const utilization = totalSupply > 0n\n ? Number((totalBorrow * 10000n) / totalSupply) / 100\n : 0;\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyRate,\n borrow_variable_apy: variableRate,\n borrow_stable_apy: stableRate,\n utilization,\n total_supply: totalSupply,\n total_borrow: totalBorrow,\n };\n }\n\n async getUserPosition(user: Address): Promise<UserPosition> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const result = await client.readContract({\n address: this.pool,\n abi: POOL_ABI,\n functionName: \"getUserAccountData\",\n args: [user],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getUserAccountData failed: ${e}`);\n });\n\n const [totalCollateralBase, totalDebtBase, , , ltv, healthFactor] = result;\n const MAX_UINT256 = 2n ** 256n - 1n;\n const hf = healthFactor >= MAX_UINT256 ? Infinity : Number(healthFactor) / 1e18;\n // V2 returns values in ETH (18 decimals) vs V3's base currency (8 decimals)\n const collateralUsd = u256ToF64(totalCollateralBase) / 1e18;\n const debtUsd = u256ToF64(totalDebtBase) / 1e18;\n const ltvBps = u256ToF64(ltv);\n\n const supplies = collateralUsd > 0\n ? [{ asset: zeroAddress as Address, symbol: \"Total Collateral\", amount: totalCollateralBase, value_usd: collateralUsd }]\n : [];\n const borrows = debtUsd > 0\n ? [{ asset: zeroAddress as Address, symbol: \"Total Debt\", amount: totalDebtBase, value_usd: debtUsd }]\n : [];\n\n return {\n protocol: this.protocolName,\n user,\n supplies,\n borrows,\n health_factor: hf,\n net_apy: ltvBps / 100,\n };\n }\n}\n","import { createPublicClient, http, parseAbi } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { IOracle } from \"@hypurrquant/defi-core\";\nimport { DefiError, type ProtocolEntry, type PriceData } from \"@hypurrquant/defi-core\";\n\nconst ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n \"function getAssetsPrices(address[] calldata assets) external view returns (uint256[] memory)\",\n \"function BASE_CURRENCY_UNIT() external view returns (uint256)\",\n]);\n\nexport class AaveOracleAdapter implements IOracle {\n private readonly protocolName: string;\n private readonly oracle: Address;\n private readonly rpcUrl: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n if (!rpcUrl) throw DefiError.rpcError(`[${entry.name}] RPC URL required for oracle`);\n this.rpcUrl = rpcUrl;\n const oracle = entry.contracts?.[\"oracle\"];\n if (!oracle) throw DefiError.contractError(`[${entry.name}] Missing 'oracle' contract address`);\n this.oracle = oracle;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getPrice(asset: Address): Promise<PriceData> {\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const baseUnit = await client.readContract({\n address: this.oracle,\n abi: ORACLE_ABI,\n functionName: \"BASE_CURRENCY_UNIT\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] BASE_CURRENCY_UNIT failed: ${e}`);\n });\n\n const priceVal = await client.readContract({\n address: this.oracle,\n abi: ORACLE_ABI,\n functionName: \"getAssetPrice\",\n args: [asset],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getAssetPrice failed: ${e}`);\n });\n\n const priceF64 = baseUnit > 0n ? Number(priceVal) / Number(baseUnit) : 0;\n const priceUsd = baseUnit > 0n\n ? (priceVal * (10n ** 18n)) / baseUnit\n : 0n;\n\n return {\n source: `${this.protocolName} Oracle`,\n source_type: \"oracle\",\n asset,\n price_usd: priceUsd,\n price_f64: priceF64,\n };\n }\n\n async getPrices(assets: Address[]): Promise<PriceData[]> {\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const baseUnit = await client.readContract({\n address: this.oracle,\n abi: ORACLE_ABI,\n functionName: \"BASE_CURRENCY_UNIT\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] BASE_CURRENCY_UNIT failed: ${e}`);\n });\n\n const rawPrices = await client.readContract({\n address: this.oracle,\n abi: ORACLE_ABI,\n functionName: \"getAssetsPrices\",\n args: [assets],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] getAssetsPrices failed: ${e}`);\n });\n\n return (rawPrices as bigint[]).map((priceVal, i) => {\n const priceF64 = baseUnit > 0n ? Number(priceVal) / Number(baseUnit) : 0;\n const priceUsd = baseUnit > 0n ? (priceVal * (10n ** 18n)) / baseUnit : 0n;\n return {\n source: `${this.protocolName} Oracle`,\n source_type: \"oracle\",\n asset: assets[i]!,\n price_usd: priceUsd,\n price_f64: priceF64,\n };\n });\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst CTOKEN_ABI = parseAbi([\n \"function supplyRatePerBlock() external view returns (uint256)\",\n \"function borrowRatePerBlock() external view returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function totalBorrows() external view returns (uint256)\",\n \"function mint(uint256 mintAmount) external returns (uint256)\",\n \"function redeem(uint256 redeemTokens) external returns (uint256)\",\n \"function borrow(uint256 borrowAmount) external returns (uint256)\",\n \"function repayBorrow(uint256 repayAmount) external returns (uint256)\",\n]);\n\n// ~3s blocks on BSC\nconst BSC_BLOCKS_PER_YEAR = 10_512_000;\n\nexport class CompoundV2Adapter implements ILending {\n private readonly protocolName: string;\n private readonly defaultVtoken: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const vtoken =\n contracts[\"vusdt\"] ??\n contracts[\"vusdc\"] ??\n contracts[\"vbnb\"] ??\n contracts[\"comptroller\"];\n if (!vtoken) throw DefiError.contractError(\"Missing vToken or comptroller address\");\n this.defaultVtoken = vtoken;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: CTOKEN_ABI,\n functionName: \"mint\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to Venus`,\n to: this.defaultVtoken,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: CTOKEN_ABI,\n functionName: \"borrow\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from Venus`,\n to: this.defaultVtoken,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: CTOKEN_ABI,\n functionName: \"repayBorrow\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to Venus`,\n to: this.defaultVtoken,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: CTOKEN_ABI,\n functionName: \"redeem\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw from Venus`,\n to: this.defaultVtoken,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [supplyRate, borrowRate, totalSupply, totalBorrows] = await Promise.all([\n client.readContract({ address: this.defaultVtoken, abi: CTOKEN_ABI, functionName: \"supplyRatePerBlock\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] supplyRatePerBlock failed: ${e}`); }),\n client.readContract({ address: this.defaultVtoken, abi: CTOKEN_ABI, functionName: \"borrowRatePerBlock\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] borrowRatePerBlock failed: ${e}`); }),\n client.readContract({ address: this.defaultVtoken, abi: CTOKEN_ABI, functionName: \"totalSupply\" }).catch(() => 0n),\n client.readContract({ address: this.defaultVtoken, abi: CTOKEN_ABI, functionName: \"totalBorrows\" }).catch(() => 0n),\n ]);\n\n const supplyPerBlock = Number(supplyRate) / 1e18;\n const borrowPerBlock = Number(borrowRate) / 1e18;\n const supplyApy = supplyPerBlock * BSC_BLOCKS_PER_YEAR * 100;\n const borrowApy = borrowPerBlock * BSC_BLOCKS_PER_YEAR * 100;\n\n const supplyF = Number(totalSupply);\n const borrowF = Number(totalBorrows);\n const utilization = supplyF > 0 ? (borrowF / supplyF) * 100 : 0;\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyApy,\n borrow_variable_apy: borrowApy,\n utilization,\n total_supply: totalSupply as bigint,\n total_borrow: totalBorrows as bigint,\n };\n }\n\n async getUserPosition(_user: Address): Promise<UserPosition> {\n throw DefiError.unsupported(\n `[${this.protocolName}] User position requires querying individual vToken balances`,\n );\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst COMET_ABI = parseAbi([\n \"function getUtilization() external view returns (uint256)\",\n \"function getSupplyRate(uint256 utilization) external view returns (uint64)\",\n \"function getBorrowRate(uint256 utilization) external view returns (uint64)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function totalBorrow() external view returns (uint256)\",\n \"function supply(address asset, uint256 amount) external\",\n \"function withdraw(address asset, uint256 amount) external\",\n]);\n\nconst SECONDS_PER_YEAR = 365.25 * 24 * 3600;\n\nexport class CompoundV3Adapter implements ILending {\n private readonly protocolName: string;\n private readonly comet: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const comet = contracts[\"comet_usdc\"] ?? contracts[\"comet\"] ?? contracts[\"comet_weth\"];\n if (!comet) throw DefiError.contractError(\"Missing 'comet_usdc' or 'comet' address\");\n this.comet = comet;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: COMET_ABI,\n functionName: \"supply\",\n args: [params.asset, params.amount],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to Comet`,\n to: this.comet,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n // In Compound V3, borrow = withdraw base asset\n const data = encodeFunctionData({\n abi: COMET_ABI,\n functionName: \"withdraw\",\n args: [params.asset, params.amount],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from Comet`,\n to: this.comet,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n // In Compound V3, repay = supply base asset\n const data = encodeFunctionData({\n abi: COMET_ABI,\n functionName: \"supply\",\n args: [params.asset, params.amount],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to Comet`,\n to: this.comet,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: COMET_ABI,\n functionName: \"withdraw\",\n args: [params.asset, params.amount],\n });\n return {\n description: `[${this.protocolName}] Withdraw from Comet`,\n to: this.comet,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const utilization = await client.readContract({\n address: this.comet,\n abi: COMET_ABI,\n functionName: \"getUtilization\",\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] getUtilization failed: ${e}`); });\n\n const [supplyRate, borrowRate, totalSupply, totalBorrow] = await Promise.all([\n client.readContract({ address: this.comet, abi: COMET_ABI, functionName: \"getSupplyRate\", args: [utilization as bigint] }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] getSupplyRate failed: ${e}`); }),\n client.readContract({ address: this.comet, abi: COMET_ABI, functionName: \"getBorrowRate\", args: [utilization as bigint] }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] getBorrowRate failed: ${e}`); }),\n client.readContract({ address: this.comet, abi: COMET_ABI, functionName: \"totalSupply\" }).catch(() => 0n),\n client.readContract({ address: this.comet, abi: COMET_ABI, functionName: \"totalBorrow\" }).catch(() => 0n),\n ]);\n\n // Comet rates are per-second scaled by 1e18\n const supplyPerSec = Number(supplyRate) / 1e18;\n const borrowPerSec = Number(borrowRate) / 1e18;\n const supplyApy = supplyPerSec * SECONDS_PER_YEAR * 100;\n const borrowApy = borrowPerSec * SECONDS_PER_YEAR * 100;\n const utilPct = Number(utilization as bigint) / 1e18 * 100;\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyApy,\n borrow_variable_apy: borrowApy,\n utilization: utilPct,\n total_supply: totalSupply as bigint,\n total_borrow: totalBorrow as bigint,\n };\n }\n\n async getUserPosition(_user: Address): Promise<UserPosition> {\n throw DefiError.unsupported(\n `[${this.protocolName}] User position requires querying Comet balanceOf + borrowBalanceOf`,\n );\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst EULER_VAULT_ABI = parseAbi([\n \"function deposit(uint256 amount, address receiver) external returns (uint256)\",\n \"function withdraw(uint256 amount, address receiver, address owner) external returns (uint256)\",\n \"function borrow(uint256 amount, address receiver) external returns (uint256)\",\n \"function repay(uint256 amount, address receiver) external returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function totalBorrows() external view returns (uint256)\",\n \"function interestRate() external view returns (uint256)\",\n]);\n\nconst SECONDS_PER_YEAR = 365.25 * 24 * 3600;\n\nexport class EulerV2Adapter implements ILending {\n private readonly protocolName: string;\n private readonly euler: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const euler = contracts[\"evk_vault\"] ?? contracts[\"euler\"] ?? contracts[\"markets\"];\n if (!euler) throw DefiError.contractError(\"Missing 'evk_vault' or 'euler' contract address\");\n this.euler = euler;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: EULER_VAULT_ABI,\n functionName: \"deposit\",\n args: [params.amount, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Deposit ${params.amount} into Euler vault`,\n to: this.euler,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: EULER_VAULT_ABI,\n functionName: \"borrow\",\n args: [params.amount, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from Euler vault`,\n to: this.euler,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: EULER_VAULT_ABI,\n functionName: \"repay\",\n args: [params.amount, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to Euler vault`,\n to: this.euler,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: EULER_VAULT_ABI,\n functionName: \"withdraw\",\n args: [params.amount, params.to, params.to],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.amount} from Euler vault`,\n to: this.euler,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [totalSupply, totalBorrows, interestRate] = await Promise.all([\n client.readContract({ address: this.euler, abi: EULER_VAULT_ABI, functionName: \"totalSupply\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] totalSupply failed: ${e}`); }),\n client.readContract({ address: this.euler, abi: EULER_VAULT_ABI, functionName: \"totalBorrows\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] totalBorrows failed: ${e}`); }),\n client.readContract({ address: this.euler, abi: EULER_VAULT_ABI, functionName: \"interestRate\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] interestRate failed: ${e}`); }),\n ]);\n\n // Euler V2 interest rates per-second scaled by 1e27\n const rateF64 = Number(interestRate) / 1e27;\n const borrowApy = rateF64 * SECONDS_PER_YEAR * 100;\n\n const supplyF = Number(totalSupply);\n const borrowF = Number(totalBorrows);\n const utilization = supplyF > 0 ? (borrowF / supplyF) * 100 : 0;\n const supplyApy = borrowApy * (borrowF / Math.max(supplyF, 1));\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyApy,\n borrow_variable_apy: borrowApy,\n utilization,\n total_supply: totalSupply as bigint,\n total_borrow: totalBorrows as bigint,\n };\n }\n\n async getUserPosition(_user: Address): Promise<UserPosition> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Euler V2 user positions require querying individual vault balances. Use the vault address directly to check balanceOf(user) for supply positions.`,\n );\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILending } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type SupplyParams,\n type BorrowParams,\n type RepayParams,\n type WithdrawParams,\n type LendingRates,\n type UserPosition,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst MORPHO_ABI = parseAbi([\n \"function market(bytes32 id) external view returns (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee)\",\n \"function idToMarketParams(bytes32 id) external view returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv)\",\n \"function supply((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) external returns (uint256 assetsSupplied, uint256 sharesSupplied)\",\n \"function borrow((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed)\",\n \"function repay((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, bytes data) external returns (uint256 assetsRepaid, uint256 sharesRepaid)\",\n \"function withdraw((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, uint256 assets, uint256 shares, address onBehalf, address receiver) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn)\",\n]);\n\nconst META_MORPHO_ABI = parseAbi([\n \"function supplyQueueLength() external view returns (uint256)\",\n \"function supplyQueue(uint256 index) external view returns (bytes32)\",\n \"function totalAssets() external view returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n]);\n\nconst IRM_ABI = parseAbi([\n \"function borrowRateView((address loanToken, address collateralToken, address oracle, address irm, uint256 lltv) marketParams, (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets, uint128 totalBorrowShares, uint128 lastUpdate, uint128 fee) market) external view returns (uint256)\",\n]);\n\nconst SECONDS_PER_YEAR = 365.25 * 24 * 3600;\n\ntype MarketParams = {\n loanToken: Address;\n collateralToken: Address;\n oracle: Address;\n irm: Address;\n lltv: bigint;\n};\n\nfunction defaultMarketParams(loanToken: Address = zeroAddress as Address): MarketParams {\n return {\n loanToken,\n collateralToken: zeroAddress as Address,\n oracle: zeroAddress as Address,\n irm: zeroAddress as Address,\n lltv: 0n,\n };\n}\n\nexport class MorphoBlueAdapter implements ILending {\n private readonly protocolName: string;\n private readonly morpho: Address;\n private readonly defaultVault?: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const morpho = contracts[\"morpho_blue\"];\n if (!morpho) throw DefiError.contractError(\"Missing 'morpho_blue' contract address\");\n this.morpho = morpho;\n this.defaultVault =\n contracts[\"fehype\"] ?? contracts[\"vault\"] ?? contracts[\"feusdc\"];\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildSupply(params: SupplyParams): Promise<DeFiTx> {\n const market = defaultMarketParams(params.asset);\n const data = encodeFunctionData({\n abi: MORPHO_ABI,\n functionName: \"supply\",\n args: [market, params.amount, 0n, params.on_behalf_of, \"0x\"],\n });\n return {\n description: `[${this.protocolName}] Supply ${params.amount} to Morpho market`,\n to: this.morpho,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildBorrow(params: BorrowParams): Promise<DeFiTx> {\n const market = defaultMarketParams(params.asset);\n const data = encodeFunctionData({\n abi: MORPHO_ABI,\n functionName: \"borrow\",\n args: [market, params.amount, 0n, params.on_behalf_of, params.on_behalf_of],\n });\n return {\n description: `[${this.protocolName}] Borrow ${params.amount} from Morpho market`,\n to: this.morpho,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async buildRepay(params: RepayParams): Promise<DeFiTx> {\n const market = defaultMarketParams(params.asset);\n const data = encodeFunctionData({\n abi: MORPHO_ABI,\n functionName: \"repay\",\n args: [market, params.amount, 0n, params.on_behalf_of, \"0x\"],\n });\n return {\n description: `[${this.protocolName}] Repay ${params.amount} to Morpho market`,\n to: this.morpho,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildWithdraw(params: WithdrawParams): Promise<DeFiTx> {\n const market = defaultMarketParams(params.asset);\n const data = encodeFunctionData({\n abi: MORPHO_ABI,\n functionName: \"withdraw\",\n args: [market, params.amount, 0n, params.to, params.to],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.amount} from Morpho market`,\n to: this.morpho,\n data,\n value: 0n,\n gas_estimate: 250_000,\n };\n }\n\n async getRates(asset: Address): Promise<LendingRates> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n if (!this.defaultVault) {\n throw DefiError.contractError(`[${this.protocolName}] No MetaMorpho vault configured for rate query`);\n }\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const queueLen = await client.readContract({\n address: this.defaultVault,\n abi: META_MORPHO_ABI,\n functionName: \"supplyQueueLength\",\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] supplyQueueLength failed: ${e}`); });\n\n if ((queueLen as bigint) === 0n) {\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: 0,\n borrow_variable_apy: 0,\n utilization: 0,\n total_supply: 0n,\n total_borrow: 0n,\n };\n }\n\n const marketId = await client.readContract({\n address: this.defaultVault,\n abi: META_MORPHO_ABI,\n functionName: \"supplyQueue\",\n args: [0n],\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] supplyQueue(0) failed: ${e}`); }) as `0x${string}`;\n\n const mkt = await client.readContract({\n address: this.morpho,\n abi: MORPHO_ABI,\n functionName: \"market\",\n args: [marketId],\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] market() failed: ${e}`); });\n\n const [totalSupplyAssets, totalSupplyShares, totalBorrowAssets, totalBorrowShares, lastUpdate, fee] = mkt as [bigint, bigint, bigint, bigint, bigint, bigint];\n\n const supplyF = Number(totalSupplyAssets);\n const borrowF = Number(totalBorrowAssets);\n const util = supplyF > 0 ? borrowF / supplyF : 0;\n\n const params2 = await client.readContract({\n address: this.morpho,\n abi: MORPHO_ABI,\n functionName: \"idToMarketParams\",\n args: [marketId],\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] idToMarketParams failed: ${e}`); });\n\n const [loanToken, collateralToken, oracle, irm, lltv] = params2 as [Address, Address, Address, Address, bigint];\n\n const irmMarketParams: MarketParams = { loanToken, collateralToken, oracle, irm, lltv };\n const irmMarket = { totalSupplyAssets, totalSupplyShares, totalBorrowAssets, totalBorrowShares, lastUpdate, fee };\n\n const borrowRatePerSec = await client.readContract({\n address: irm,\n abi: IRM_ABI,\n functionName: \"borrowRateView\",\n args: [irmMarketParams, irmMarket],\n }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] borrowRateView failed: ${e}`); }) as bigint;\n\n const ratePerSec = Number(borrowRatePerSec) / 1e18;\n const borrowApy = ratePerSec * SECONDS_PER_YEAR * 100;\n const feePct = Number(fee) / 1e18;\n const supplyApy = borrowApy * util * (1 - feePct);\n\n return {\n protocol: this.protocolName,\n asset,\n supply_apy: supplyApy,\n borrow_variable_apy: borrowApy,\n utilization: util * 100,\n total_supply: totalSupplyAssets,\n total_borrow: totalBorrowAssets,\n };\n }\n\n async getUserPosition(_user: Address): Promise<UserPosition> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Morpho Blue user positions are per-market — use vault deposit/withdraw instead`,\n );\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ICdp } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type OpenCdpParams,\n type AdjustCdpParams,\n type CloseCdpParams,\n type CdpInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst BORROWER_OPS_ABI = parseAbi([\n \"function openTrove(address _owner, uint256 _ownerIndex, uint256 _collAmount, uint256 _boldAmount, uint256 _upperHint, uint256 _lowerHint, uint256 _annualInterestRate, uint256 _maxUpfrontFee, address _addManager, address _removeManager, address _receiver) external returns (uint256)\",\n \"function adjustTrove(uint256 _troveId, uint256 _collChange, bool _isCollIncrease, uint256 _debtChange, bool _isDebtIncrease, uint256 _upperHint, uint256 _lowerHint, uint256 _maxUpfrontFee) external\",\n \"function closeTrove(uint256 _troveId) external\",\n]);\n\nconst TROVE_MANAGER_ABI = parseAbi([\n \"function getLatestTroveData(uint256 _troveId) external view returns (uint256 entireDebt, uint256 entireColl, uint256 redistDebtGain, uint256 redistCollGain, uint256 accruedInterest, uint256 recordedDebt, uint256 annualInterestRate, uint256 accruedBatchManagementFee, uint256 weightedRecordedDebt, uint256 lastInterestRateAdjTime)\",\n]);\n\nconst HINT_HELPERS_ABI = parseAbi([\n \"function getApproxHint(uint256 _collIndex, uint256 _interestRate, uint256 _numTrials, uint256 _inputRandomSeed) external view returns (uint256 hintId, uint256 diff, uint256 latestRandomSeed)\",\n]);\n\nconst SORTED_TROVES_ABI = parseAbi([\n \"function findInsertPosition(uint256 _annualInterestRate, uint256 _prevId, uint256 _nextId) external view returns (uint256 prevId, uint256 nextId)\",\n]);\n\nexport class FelixCdpAdapter implements ICdp {\n private readonly protocolName: string;\n private readonly borrowerOperations: Address;\n private readonly troveManager?: Address;\n private readonly hintHelpers?: Address;\n private readonly sortedTroves?: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const bo = contracts[\"borrower_operations\"];\n if (!bo) throw DefiError.contractError(\"Missing 'borrower_operations' contract\");\n this.borrowerOperations = bo;\n this.troveManager = contracts[\"trove_manager\"];\n this.hintHelpers = contracts[\"hint_helpers\"];\n this.sortedTroves = contracts[\"sorted_troves\"];\n }\n\n name(): string {\n return this.protocolName;\n }\n\n private async getHints(interestRate: bigint): Promise<[bigint, bigint]> {\n if (!this.hintHelpers || !this.sortedTroves || !this.rpcUrl) {\n return [0n, 0n];\n }\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const approxResult = await client.readContract({\n address: this.hintHelpers,\n abi: HINT_HELPERS_ABI,\n functionName: \"getApproxHint\",\n args: [0n, interestRate, 15n, 42n],\n }).catch(() => null);\n\n if (!approxResult) return [0n, 0n];\n const [hintId] = approxResult as [bigint, bigint, bigint];\n\n const insertResult = await client.readContract({\n address: this.sortedTroves,\n abi: SORTED_TROVES_ABI,\n functionName: \"findInsertPosition\",\n args: [interestRate, hintId, hintId],\n }).catch(() => null);\n\n if (!insertResult) return [0n, 0n];\n const [prevId, nextId] = insertResult as [bigint, bigint];\n return [prevId, nextId];\n }\n\n async buildOpen(params: OpenCdpParams): Promise<DeFiTx> {\n const interestRate = 50000000000000000n; // 5% default\n const [upperHint, lowerHint] = await this.getHints(interestRate);\n const hasHints = upperHint !== 0n || lowerHint !== 0n;\n\n const data = encodeFunctionData({\n abi: BORROWER_OPS_ABI,\n functionName: \"openTrove\",\n args: [\n params.recipient,\n 0n,\n params.collateral_amount,\n params.debt_amount,\n upperHint,\n lowerHint,\n interestRate,\n BigInt(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"), // U256::MAX\n params.recipient,\n params.recipient,\n params.recipient,\n ],\n });\n\n return {\n description: `[${this.protocolName}] Open trove: collateral=${params.collateral_amount}, debt=${params.debt_amount} (hints=${hasHints ? \"optimized\" : \"none\"})`,\n to: this.borrowerOperations,\n data,\n value: 0n,\n gas_estimate: hasHints ? 500_000 : 5_000_000,\n };\n }\n\n async buildAdjust(params: AdjustCdpParams): Promise<DeFiTx> {\n const collChange = params.collateral_delta ?? 0n;\n const debtChange = params.debt_delta ?? 0n;\n\n const data = encodeFunctionData({\n abi: BORROWER_OPS_ABI,\n functionName: \"adjustTrove\",\n args: [\n params.cdp_id,\n collChange,\n params.add_collateral,\n debtChange,\n params.add_debt,\n 0n,\n 0n,\n BigInt(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\"),\n ],\n });\n\n return {\n description: `[${this.protocolName}] Adjust trove ${params.cdp_id}`,\n to: this.borrowerOperations,\n data,\n value: 0n,\n gas_estimate: 400_000,\n };\n }\n\n async buildClose(params: CloseCdpParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: BORROWER_OPS_ABI,\n functionName: \"closeTrove\",\n args: [params.cdp_id],\n });\n\n return {\n description: `[${this.protocolName}] Close trove ${params.cdp_id}`,\n to: this.borrowerOperations,\n data,\n value: 0n,\n gas_estimate: 350_000,\n };\n }\n\n async getCdpInfo(cdpId: bigint): Promise<CdpInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(`[${this.protocolName}] getCdpInfo requires RPC — set HYPEREVM_RPC_URL`);\n if (!this.troveManager) throw DefiError.contractError(`[${this.protocolName}] trove_manager contract not configured`);\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const data = await client.readContract({\n address: this.troveManager,\n abi: TROVE_MANAGER_ABI,\n functionName: \"getLatestTroveData\",\n args: [cdpId],\n }).catch((e: unknown) => {\n throw DefiError.invalidParam(`[${this.protocolName}] Trove ${cdpId} not found: ${e}`);\n });\n\n const [entireDebt, entireColl] = data as [bigint, bigint, bigint, bigint, bigint, bigint, bigint, bigint, bigint, bigint];\n\n if (entireDebt === 0n && entireColl === 0n) {\n throw DefiError.invalidParam(`[${this.protocolName}] Trove ${cdpId} does not exist`);\n }\n\n const collRatio = entireDebt > 0n ? Number(entireColl) / Number(entireDebt) : 0;\n\n return {\n protocol: this.protocolName,\n cdp_id: cdpId,\n collateral: {\n token: zeroAddress as Address,\n symbol: \"WHYPE\",\n amount: entireColl,\n decimals: 18,\n },\n debt: {\n token: zeroAddress as Address,\n symbol: \"feUSD\",\n amount: entireDebt,\n decimals: 18,\n },\n collateral_ratio: collRatio,\n };\n }\n}\n","import { createPublicClient, http, parseAbi } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { IOracle } from \"@hypurrquant/defi-core\";\nimport { DefiError, type ProtocolEntry, type PriceData } from \"@hypurrquant/defi-core\";\n\nconst PRICE_FEED_ABI = parseAbi([\n \"function fetchPrice() external view returns (uint256 price, bool isNewOracleFailureDetected)\",\n \"function lastGoodPrice() external view returns (uint256)\",\n]);\n\nexport class FelixOracleAdapter implements IOracle {\n private readonly protocolName: string;\n private readonly priceFeed: Address;\n private readonly asset: Address;\n private readonly rpcUrl: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n if (!rpcUrl) throw DefiError.rpcError(`[${entry.name}] RPC URL required for oracle`);\n this.rpcUrl = rpcUrl;\n const contracts = entry.contracts ?? {};\n const feed = contracts[\"price_feed\"];\n if (!feed) throw DefiError.contractError(`[${entry.name}] Missing 'price_feed' contract address`);\n this.priceFeed = feed;\n // The asset address is stored under \"asset\" or falls back to zero (WHYPE native)\n this.asset = contracts[\"asset\"] ?? (\"0x0000000000000000000000000000000000000000\" as Address);\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getPrice(asset: Address): Promise<PriceData> {\n if (asset !== this.asset && this.asset !== \"0x0000000000000000000000000000000000000000\") {\n throw DefiError.unsupported(`[${this.protocolName}] Felix PriceFeed only supports asset ${this.asset}`);\n }\n\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n let priceVal: bigint;\n try {\n const result = await client.readContract({\n address: this.priceFeed,\n abi: PRICE_FEED_ABI,\n functionName: \"fetchPrice\",\n });\n const [price] = result as [bigint, boolean];\n priceVal = price;\n } catch {\n // Fall back to lastGoodPrice\n priceVal = await client.readContract({\n address: this.priceFeed,\n abi: PRICE_FEED_ABI,\n functionName: \"lastGoodPrice\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] lastGoodPrice failed: ${e}`);\n }) as bigint;\n }\n\n // Felix prices are already in 18-decimal USD\n const priceF64 = Number(priceVal) / 1e18;\n\n return {\n source: \"Felix PriceFeed\",\n source_type: \"oracle\",\n asset,\n price_usd: priceVal,\n price_f64: priceF64,\n };\n }\n\n async getPrices(assets: Address[]): Promise<PriceData[]> {\n const results: PriceData[] = [];\n for (const asset of assets) {\n try {\n results.push(await this.getPrice(asset));\n } catch {\n // Skip unsupported assets\n }\n }\n return results;\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { IVault } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type VaultInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst ERC4626_ABI = parseAbi([\n \"function asset() external view returns (address)\",\n \"function totalAssets() external view returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function convertToShares(uint256 assets) external view returns (uint256)\",\n \"function convertToAssets(uint256 shares) external view returns (uint256)\",\n \"function deposit(uint256 assets, address receiver) external returns (uint256 shares)\",\n \"function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares)\",\n]);\n\nexport class ERC4626VaultAdapter implements IVault {\n private readonly protocolName: string;\n private readonly vaultAddress: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const vault = entry.contracts?.[\"vault\"];\n if (!vault) throw DefiError.contractError(\"Missing 'vault' contract address\");\n this.vaultAddress = vault;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildDeposit(assets: bigint, receiver: Address): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: ERC4626_ABI,\n functionName: \"deposit\",\n args: [assets, receiver],\n });\n return {\n description: `[${this.protocolName}] Deposit ${assets} assets into vault`,\n to: this.vaultAddress,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async buildWithdraw(assets: bigint, receiver: Address, owner: Address): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: ERC4626_ABI,\n functionName: \"withdraw\",\n args: [assets, receiver, owner],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${assets} assets from vault`,\n to: this.vaultAddress,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async totalAssets(): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n return client.readContract({\n address: this.vaultAddress,\n abi: ERC4626_ABI,\n functionName: \"totalAssets\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] totalAssets failed: ${e}`);\n }) as Promise<bigint>;\n }\n\n async convertToShares(assets: bigint): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n return client.readContract({\n address: this.vaultAddress,\n abi: ERC4626_ABI,\n functionName: \"convertToShares\",\n args: [assets],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] convertToShares failed: ${e}`);\n }) as Promise<bigint>;\n }\n\n async convertToAssets(shares: bigint): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n return client.readContract({\n address: this.vaultAddress,\n abi: ERC4626_ABI,\n functionName: \"convertToAssets\",\n args: [shares],\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] convertToAssets failed: ${e}`);\n }) as Promise<bigint>;\n }\n\n async getVaultInfo(): Promise<VaultInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [totalAssets, totalSupply, asset] = await Promise.all([\n client.readContract({ address: this.vaultAddress, abi: ERC4626_ABI, functionName: \"totalAssets\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] totalAssets failed: ${e}`); }),\n client.readContract({ address: this.vaultAddress, abi: ERC4626_ABI, functionName: \"totalSupply\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] totalSupply failed: ${e}`); }),\n client.readContract({ address: this.vaultAddress, abi: ERC4626_ABI, functionName: \"asset\" }).catch((e: unknown) => { throw DefiError.rpcError(`[${this.protocolName}] asset failed: ${e}`); }),\n ]);\n\n return {\n protocol: this.protocolName,\n vault_address: this.vaultAddress,\n asset: asset as Address,\n total_assets: totalAssets as bigint,\n total_supply: totalSupply as bigint,\n };\n }\n}\n","import { parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILiquidStaking } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type StakeParams,\n type UnstakeParams,\n type StakingInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst GENERIC_LST_ABI = parseAbi([\n \"function stake() external payable returns (uint256)\",\n \"function unstake(uint256 amount) external returns (uint256)\",\n]);\n\nexport class GenericLstAdapter implements ILiquidStaking {\n private readonly protocolName: string;\n private readonly staking: Address;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const staking = entry.contracts?.[\"staking\"];\n if (!staking) throw DefiError.contractError(\"Missing 'staking' contract\");\n this.staking = staking;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildStake(params: StakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({ abi: GENERIC_LST_ABI, functionName: \"stake\" });\n return {\n description: `[${this.protocolName}] Stake ${params.amount} HYPE`,\n to: this.staking,\n data,\n value: params.amount,\n gas_estimate: 200_000,\n };\n }\n\n async buildUnstake(params: UnstakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: GENERIC_LST_ABI,\n functionName: \"unstake\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Unstake ${params.amount}`,\n to: this.staking,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async getInfo(): Promise<StakingInfo> {\n throw DefiError.unsupported(`[${this.protocolName}] getInfo requires RPC`);\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILiquidStaking } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type StakeParams,\n type UnstakeParams,\n type StakingInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst STHYPE_ABI = parseAbi([\n \"function submit(address referral) external payable returns (uint256)\",\n \"function requestWithdrawals(uint256[] amounts, address owner) external returns (uint256[] requestIds)\",\n]);\n\nconst ERC20_ABI = parseAbi([\n \"function totalSupply() external view returns (uint256)\",\n]);\n\nexport class StHypeAdapter implements ILiquidStaking {\n private readonly protocolName: string;\n private readonly staking: Address;\n private readonly sthypeToken?: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const staking = entry.contracts?.[\"staking\"];\n if (!staking) throw DefiError.contractError(\"Missing 'staking' contract\");\n this.staking = staking;\n this.sthypeToken = entry.contracts?.[\"sthype_token\"];\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildStake(params: StakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: STHYPE_ABI,\n functionName: \"submit\",\n args: [zeroAddress as Address],\n });\n return {\n description: `[${this.protocolName}] Stake ${params.amount} HYPE for stHYPE`,\n to: this.staking,\n data,\n value: params.amount,\n gas_estimate: 200_000,\n };\n }\n\n async buildUnstake(params: UnstakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: STHYPE_ABI,\n functionName: \"requestWithdrawals\",\n args: [[params.amount], params.recipient],\n });\n return {\n description: `[${this.protocolName}] Request unstake ${params.amount} stHYPE`,\n to: this.staking,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async getInfo(): Promise<StakingInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n const tokenAddr = this.sthypeToken ?? this.staking;\n\n const totalSupply = await client.readContract({\n address: tokenAddr,\n abi: ERC20_ABI,\n functionName: \"totalSupply\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] totalSupply failed: ${e}`);\n }) as bigint;\n\n return {\n protocol: this.protocolName,\n staked_token: zeroAddress as Address,\n liquid_token: tokenAddr,\n exchange_rate: 1.0,\n total_staked: totalSupply,\n };\n }\n}\n","import { createPublicClient, http, parseAbi, encodeFunctionData, zeroAddress } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { ILiquidStaking } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type StakeParams,\n type UnstakeParams,\n type StakingInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst KINETIQ_ABI = parseAbi([\n \"function stake() external payable returns (uint256)\",\n \"function requestUnstake(uint256 amount) external returns (uint256)\",\n \"function totalStaked() external view returns (uint256)\",\n]);\n\nconst ORACLE_ABI = parseAbi([\n \"function getAssetPrice(address asset) external view returns (uint256)\",\n]);\n\n// WHYPE address on HyperEVM\nconst WHYPE: Address = \"0x5555555555555555555555555555555555555555\";\n// HyperLend oracle address (Aave V3 compatible)\nconst HYPERLEND_ORACLE: Address = \"0xc9fb4fbe842d57ea1df3e641a281827493a63030\";\n\nexport class KinetiqAdapter implements ILiquidStaking {\n private readonly protocolName: string;\n private readonly staking: Address;\n private readonly liquidToken: Address;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n const staking = entry.contracts?.[\"staking\"];\n if (!staking) throw DefiError.contractError(\"Missing 'staking' contract address\");\n this.staking = staking;\n this.liquidToken = entry.contracts?.[\"khype_token\"] ?? staking;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildStake(params: StakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({ abi: KINETIQ_ABI, functionName: \"stake\" });\n return {\n description: `[${this.protocolName}] Stake ${params.amount} HYPE for kHYPE`,\n to: this.staking,\n data,\n value: params.amount,\n gas_estimate: 300_000,\n };\n }\n\n async buildUnstake(params: UnstakeParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: KINETIQ_ABI,\n functionName: \"requestUnstake\",\n args: [params.amount],\n });\n return {\n description: `[${this.protocolName}] Request unstake ${params.amount} kHYPE`,\n to: this.staking,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async getInfo(): Promise<StakingInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const totalStaked = await client.readContract({\n address: this.staking,\n abi: KINETIQ_ABI,\n functionName: \"totalStaked\",\n }).catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] totalStaked failed: ${e}`);\n }) as bigint;\n\n const [khypePrice, hypePrice] = await Promise.all([\n client.readContract({ address: HYPERLEND_ORACLE, abi: ORACLE_ABI, functionName: \"getAssetPrice\", args: [this.liquidToken] }).catch(() => 0n),\n client.readContract({ address: HYPERLEND_ORACLE, abi: ORACLE_ABI, functionName: \"getAssetPrice\", args: [WHYPE] }).catch(() => 0n),\n ]);\n\n const rateF64 =\n (hypePrice as bigint) > 0n && (khypePrice as bigint) > 0n\n ? Number((khypePrice as bigint) * 10n ** 18n / (hypePrice as bigint)) / 1e18\n : 1.0;\n\n return {\n protocol: this.protocolName,\n staked_token: zeroAddress as Address,\n liquid_token: this.liquidToken,\n exchange_rate: rateF64,\n total_staked: totalStaked,\n };\n }\n}\n","import type { Address } from \"viem\";\nimport type { IYieldSource } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type YieldInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nexport class PendleAdapter implements IYieldSource {\n private readonly protocolName: string;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n if (!entry.contracts?.[\"router\"]) {\n throw DefiError.contractError(\"Missing 'router' contract\");\n }\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getYields(): Promise<YieldInfo[]> {\n throw DefiError.unsupported(`[${this.protocolName}] getYields requires RPC`);\n }\n\n async buildDeposit(_pool: string, _amount: bigint, _recipient: Address): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Pendle deposit requires market address and token routing params. Use Pendle-specific CLI.`,\n );\n }\n\n async buildWithdraw(_pool: string, _amount: bigint, _recipient: Address): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Pendle withdraw requires market-specific params`,\n );\n }\n}\n","import type { Address } from \"viem\";\nimport type { IYieldSource } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type YieldInfo,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nexport class GenericYieldAdapter implements IYieldSource {\n private readonly protocolName: string;\n private readonly interfaceName: string;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n this.interfaceName = entry.interface;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getYields(): Promise<YieldInfo[]> {\n throw DefiError.unsupported(`[${this.protocolName}] getYields requires RPC`);\n }\n\n async buildDeposit(_pool: string, _amount: bigint, _recipient: Address): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Yield interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'pendle_v2' (Pendle). Protocols like Steer (managed liquidity), ` +\n `Liminal (yield optimization), and Altura (gaming yield) need custom deposit logic.`,\n );\n }\n\n async buildWithdraw(_pool: string, _amount: bigint, _recipient: Address): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Yield interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'pendle_v2' (Pendle). Protocols like Steer (managed liquidity), ` +\n `Liminal (yield optimization), and Altura (gaming yield) need custom withdraw logic.`,\n );\n }\n}\n","import { parseAbi, encodeFunctionData } from \"viem\";\nimport type { IDerivatives } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type DerivativesPositionParams,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\nimport type { Address } from \"viem\";\n\nconst HLP_ABI = parseAbi([\n \"function deposit(uint256 amount) external returns (uint256)\",\n \"function withdraw(uint256 shares) external returns (uint256)\",\n]);\n\nexport class HlpVaultAdapter implements IDerivatives {\n private readonly protocolName: string;\n private readonly vault: Address;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const vault = entry.contracts?.[\"vault\"];\n if (!vault) throw DefiError.contractError(\"Missing 'vault' contract\");\n this.vault = vault;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildOpenPosition(params: DerivativesPositionParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: HLP_ABI,\n functionName: \"deposit\",\n args: [params.collateral],\n });\n return {\n description: `[${this.protocolName}] Deposit ${params.collateral} into HLP vault`,\n to: this.vault,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n\n async buildClosePosition(params: DerivativesPositionParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: HLP_ABI,\n functionName: \"withdraw\",\n args: [params.size],\n });\n return {\n description: `[${this.protocolName}] Withdraw ${params.size} from HLP vault`,\n to: this.vault,\n data,\n value: 0n,\n gas_estimate: 200_000,\n };\n }\n}\n","import type { IDerivatives } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type DerivativesPositionParams,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nexport class GenericDerivativesAdapter implements IDerivatives {\n private readonly protocolName: string;\n private readonly interfaceName: string;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n this.interfaceName = entry.interface;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildOpenPosition(_params: DerivativesPositionParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Derivatives interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'hlp_vault' (HLP Vault). Protocols like Rumpel need custom position management logic.`,\n );\n }\n\n async buildClosePosition(_params: DerivativesPositionParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Derivatives interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'hlp_vault' (HLP Vault). Protocols like Rumpel need custom position management logic.`,\n );\n }\n}\n","import { parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { IOptions } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type OptionParams,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nconst RYSK_ABI = parseAbi([\n \"function openOption(address underlying, uint256 strikePrice, uint256 expiry, bool isCall, uint256 amount) external returns (uint256 premium)\",\n \"function closeOption(address underlying, uint256 strikePrice, uint256 expiry, bool isCall, uint256 amount) external returns (uint256 payout)\",\n]);\n\nexport class RyskAdapter implements IOptions {\n private readonly protocolName: string;\n private readonly controller: Address;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n const controller = entry.contracts?.[\"controller\"];\n if (!controller) throw DefiError.contractError(\"Missing 'controller' contract\");\n this.controller = controller;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildBuy(params: OptionParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: RYSK_ABI,\n functionName: \"openOption\",\n args: [\n params.underlying,\n params.strike_price,\n BigInt(params.expiry),\n params.is_call,\n params.amount,\n ],\n });\n return {\n description: `[${this.protocolName}] Buy ${params.is_call ? \"call\" : \"put\"} ${params.amount} option, strike=${params.strike_price}, expiry=${params.expiry}`,\n to: this.controller,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n\n async buildSell(params: OptionParams): Promise<DeFiTx> {\n const data = encodeFunctionData({\n abi: RYSK_ABI,\n functionName: \"closeOption\",\n args: [\n params.underlying,\n params.strike_price,\n BigInt(params.expiry),\n params.is_call,\n params.amount,\n ],\n });\n return {\n description: `[${this.protocolName}] Sell/close ${params.is_call ? \"call\" : \"put\"} ${params.amount} option`,\n to: this.controller,\n data,\n value: 0n,\n gas_estimate: 300_000,\n };\n }\n}\n","import type { IOptions } from \"@hypurrquant/defi-core\";\nimport {\n DefiError,\n type ProtocolEntry,\n type OptionParams,\n type DeFiTx,\n} from \"@hypurrquant/defi-core\";\n\nexport class GenericOptionsAdapter implements IOptions {\n private readonly protocolName: string;\n private readonly interfaceName: string;\n\n constructor(entry: ProtocolEntry, _rpcUrl?: string) {\n this.protocolName = entry.name;\n this.interfaceName = entry.interface;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async buildBuy(_params: OptionParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Options interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'rysk' (Rysk Finance). Other options protocols need custom strike/expiry handling.`,\n );\n }\n\n async buildSell(_params: OptionParams): Promise<DeFiTx> {\n throw DefiError.unsupported(\n `[${this.protocolName}] Options interface '${this.interfaceName}' requires a protocol-specific adapter. ` +\n `Supported: 'rysk' (Rysk Finance). Other options protocols need custom strike/expiry handling.`,\n );\n }\n}\n","import { createPublicClient, http, parseAbi } from \"viem\";\nimport type { Address } from \"viem\";\nimport type { INft, NftCollectionInfo, NftTokenInfo } from \"@hypurrquant/defi-core\";\nimport { DefiError, type ProtocolEntry } from \"@hypurrquant/defi-core\";\n\nconst ERC721_ABI = parseAbi([\n \"function name() returns (string)\",\n \"function symbol() returns (string)\",\n \"function totalSupply() returns (uint256)\",\n \"function ownerOf(uint256 tokenId) returns (address)\",\n \"function balanceOf(address owner) returns (uint256)\",\n \"function tokenURI(uint256 tokenId) returns (string)\",\n]);\n\nexport class ERC721Adapter implements INft {\n private readonly protocolName: string;\n private readonly rpcUrl?: string;\n\n constructor(entry: ProtocolEntry, rpcUrl?: string) {\n this.protocolName = entry.name;\n this.rpcUrl = rpcUrl;\n }\n\n name(): string {\n return this.protocolName;\n }\n\n async getCollectionInfo(collection: Address): Promise<NftCollectionInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [collectionName, symbol, totalSupply] = await Promise.all([\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"name\" })\n .catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] name failed: ${e}`);\n }),\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"symbol\" })\n .catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] symbol failed: ${e}`);\n }),\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"totalSupply\" })\n .catch(() => undefined),\n ]);\n\n return {\n address: collection,\n name: collectionName as string,\n symbol: symbol as string,\n total_supply: totalSupply as bigint | undefined,\n };\n }\n\n async getTokenInfo(collection: Address, tokenId: bigint): Promise<NftTokenInfo> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n const [owner, tokenUri] = await Promise.all([\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"ownerOf\", args: [tokenId] })\n .catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] ownerOf failed: ${e}`);\n }),\n client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"tokenURI\", args: [tokenId] })\n .catch(() => undefined),\n ]);\n\n return {\n collection,\n token_id: tokenId,\n owner: owner as Address,\n token_uri: tokenUri as string | undefined,\n };\n }\n\n async getBalance(owner: Address, collection: Address): Promise<bigint> {\n if (!this.rpcUrl) throw DefiError.rpcError(\"No RPC URL configured\");\n const client = createPublicClient({ transport: http(this.rpcUrl) });\n\n return client\n .readContract({ address: collection, abi: ERC721_ABI, functionName: \"balanceOf\", args: [owner] })\n .catch((e: unknown) => {\n throw DefiError.rpcError(`[${this.protocolName}] balanceOf failed: ${e}`);\n }) as Promise<bigint>;\n }\n}\n","import type { Address } from \"viem\";\n\nimport type { IDex, PriceData, QuoteParams } from \"@hypurrquant/defi-core\";\n\n/**\n * Utility for deriving spot prices from DEX quoters.\n * Quotes 1 unit of the token against a quote token (e.g. USDC) to derive price.\n */\nexport class DexSpotPrice {\n /**\n * Get the spot price for `token` denominated in `quoteToken` (e.g. USDC).\n *\n * `tokenDecimals` — decimals of the input token (to know how much \"1 unit\" is)\n * `quoteDecimals` — decimals of the quote token (to convert the output to number)\n */\n static async getPrice(\n dex: IDex,\n token: Address,\n tokenDecimals: number,\n quoteToken: Address,\n quoteDecimals: number,\n ): Promise<PriceData> {\n const amountIn = 10n ** BigInt(tokenDecimals); // 1 token\n\n const quoteParams: QuoteParams = {\n protocol: \"\",\n token_in: token,\n token_out: quoteToken,\n amount_in: amountIn,\n };\n\n const quote = await dex.quote(quoteParams);\n\n // Convert to USD price (assuming quoteToken is a USD stablecoin)\n const priceF64 = Number(quote.amount_out) / 10 ** quoteDecimals;\n\n // Normalize to 18-decimal representation\n let priceUsd: bigint;\n if (quoteDecimals < 18) {\n priceUsd = quote.amount_out * 10n ** BigInt(18 - quoteDecimals);\n } else if (quoteDecimals > 18) {\n priceUsd = quote.amount_out / 10n ** BigInt(quoteDecimals - 18);\n } else {\n priceUsd = quote.amount_out;\n }\n\n return {\n source: `dex:${dex.name()}`,\n source_type: \"dex_spot\",\n asset: token,\n price_usd: priceUsd,\n price_f64: priceF64,\n block_number: undefined,\n timestamp: undefined,\n };\n }\n}\n","#!/usr/bin/env node\n/**\n * MCP (Model Context Protocol) server for defi-cli.\n *\n * Exposes DeFi operations as MCP tools: lending, DEX, bridge, vault, staking,\n * price queries, exploit detection, and portfolio overview.\n * Transactions default to dry-run mode unless DEFI_PRIVATE_KEY is set and\n * broadcast is explicitly requested via the `broadcast` parameter.\n */\n\nimport \"dotenv/config\";\nimport { createRequire } from \"node:module\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { z } from \"zod\";\nimport { Registry, InterestRateMode } from \"@hypurrquant/defi-core\";\nimport { createLending, createDex, createVault, createLiquidStaking } from \"@hypurrquant/defi-protocols\";\nimport { Executor } from \"./executor.js\";\nimport type { Address } from \"viem\";\n\n// ── JSON envelope helpers ──\n\nfunction ok(data: unknown, meta?: Record<string, unknown>) {\n return JSON.stringify({ ok: true, data, meta }, null, 2);\n}\n\nfunction err(error: string, meta?: Record<string, unknown>) {\n return JSON.stringify({ ok: false, error, meta }, null, 2);\n}\n\n// ── Registry helper ──\n\nfunction getRegistry() {\n return Registry.loadEmbedded();\n}\n\nfunction resolveToken(registry: Registry, chainName: string, token: string): Address {\n if (token.startsWith(\"0x\")) return token as Address;\n return registry.resolveToken(chainName, token).address as Address;\n}\n\nfunction makeExecutor(broadcast: boolean, rpcUrl: string, explorerUrl?: string): Executor {\n return new Executor(broadcast, rpcUrl, explorerUrl);\n}\n\n// ── MCP Server ──\n\nconst _require = createRequire(import.meta.url);\nconst _pkg = _require(\"../package.json\") as { version: string };\n\nconst server = new McpServer(\n { name: \"defi-cli\", version: _pkg.version },\n { capabilities: { tools: {}, resources: {}, prompts: {} } },\n);\n\n// ============================================================\n// defi_status — chain and protocol status\n// ============================================================\n\nserver.tool(\n \"defi_status\",\n \"Show chain and protocol status: lists all protocols deployed on a chain with contract addresses and categories\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm). E.g. hyperevm, ethereum, arbitrum, base\"),\n },\n async ({ chain }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocols = registry.getProtocolsForChain(chainName);\n\n const data = {\n chain: chainName,\n chain_id: chainConfig.chain_id,\n rpc_url: chainConfig.effectiveRpcUrl(),\n protocols: protocols.map(p => ({\n slug: p.slug,\n name: p.name,\n category: p.category,\n interface: p.interface,\n contracts: p.contracts ?? {},\n })),\n summary: {\n total_protocols: protocols.length,\n },\n };\n\n return { content: [{ type: \"text\", text: ok(data, { chain: chainName }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e)) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_lending_rates — get lending rates for a protocol\n// ============================================================\n\nserver.tool(\n \"defi_lending_rates\",\n \"Get current supply and borrow rates for an asset on a lending protocol (e.g. Aave V3)\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n protocol: z.string().describe(\"Protocol slug, e.g. aave-v3, felix\"),\n asset: z.string().describe(\"Token symbol (e.g. USDC) or address (0x...)\"),\n },\n async ({ chain, protocol, asset }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocolConfig = registry.getProtocol(protocol);\n const adapter = createLending(protocolConfig, chainConfig.effectiveRpcUrl());\n const assetAddr = resolveToken(registry, chainName, asset);\n const rates = await adapter.getRates(assetAddr);\n return { content: [{ type: \"text\", text: ok(rates, { chain: chainName, protocol, asset }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { protocol, asset }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_lending_supply — supply to lending protocol\n// ============================================================\n\nserver.tool(\n \"defi_lending_supply\",\n \"Supply an asset to a lending protocol. Defaults to dry-run (no broadcast). Set broadcast=true to send transaction (requires DEFI_PRIVATE_KEY env var)\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n protocol: z.string().describe(\"Protocol slug, e.g. aave-v3\"),\n asset: z.string().describe(\"Token symbol or address\"),\n amount: z.string().describe(\"Amount in wei (as string to avoid precision loss)\"),\n on_behalf_of: z.string().optional().describe(\"Supply on behalf of this address (default: DEFI_WALLET_ADDRESS env var)\"),\n broadcast: z.boolean().optional().describe(\"Set true to broadcast the transaction (default: false = dry run)\"),\n },\n async ({ chain, protocol, asset, amount, on_behalf_of, broadcast }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocolConfig = registry.getProtocol(protocol);\n const adapter = createLending(protocolConfig, chainConfig.effectiveRpcUrl());\n const assetAddr = resolveToken(registry, chainName, asset);\n const onBehalfOf = (on_behalf_of ?? process.env[\"DEFI_WALLET_ADDRESS\"] ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildSupply({ protocol: protocolConfig.name, asset: assetAddr, amount: BigInt(amount), on_behalf_of: onBehalfOf });\n const executor = makeExecutor(broadcast ?? false, chainConfig.effectiveRpcUrl(), chainConfig.explorer_url);\n const result = await executor.execute(tx);\n return { content: [{ type: \"text\", text: ok(result, { chain: chainName, protocol, asset, broadcast: broadcast ?? false }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { protocol, asset }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_lending_withdraw — withdraw from lending protocol\n// ============================================================\n\nserver.tool(\n \"defi_lending_withdraw\",\n \"Withdraw a supplied asset from a lending protocol. Defaults to dry-run. Set broadcast=true to send transaction\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n protocol: z.string().describe(\"Protocol slug, e.g. aave-v3\"),\n asset: z.string().describe(\"Token symbol or address\"),\n amount: z.string().describe(\"Amount in wei to withdraw\"),\n to: z.string().optional().describe(\"Recipient address (default: DEFI_WALLET_ADDRESS)\"),\n broadcast: z.boolean().optional().describe(\"Set true to broadcast (default: false)\"),\n },\n async ({ chain, protocol, asset, amount, to, broadcast }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocolConfig = registry.getProtocol(protocol);\n const adapter = createLending(protocolConfig, chainConfig.effectiveRpcUrl());\n const assetAddr = resolveToken(registry, chainName, asset);\n const toAddr = (to ?? process.env[\"DEFI_WALLET_ADDRESS\"] ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildWithdraw({ protocol: protocolConfig.name, asset: assetAddr, amount: BigInt(amount), to: toAddr });\n const executor = makeExecutor(broadcast ?? false, chainConfig.effectiveRpcUrl(), chainConfig.explorer_url);\n const result = await executor.execute(tx);\n return { content: [{ type: \"text\", text: ok(result, { chain: chainName, protocol, asset, broadcast: broadcast ?? false }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { protocol, asset }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_dex_quote — get swap quote\n// ============================================================\n\nserver.tool(\n \"defi_dex_quote\",\n \"Get a DEX swap quote without executing. Returns expected output amount and price impact\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n protocol: z.string().describe(\"Protocol slug, e.g. uniswap-v3, algebra-v3\"),\n token_in: z.string().describe(\"Input token symbol or address\"),\n token_out: z.string().describe(\"Output token symbol or address\"),\n amount_in: z.string().describe(\"Amount of input token in wei\"),\n },\n async ({ chain, protocol, token_in, token_out, amount_in }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocolConfig = registry.getProtocol(protocol);\n const adapter = createDex(protocolConfig, chainConfig.effectiveRpcUrl());\n const tokenIn = resolveToken(registry, chainName, token_in);\n const tokenOut = resolveToken(registry, chainName, token_out);\n const result = await adapter.quote({ protocol: protocolConfig.name, token_in: tokenIn, token_out: tokenOut, amount_in: BigInt(amount_in) });\n return { content: [{ type: \"text\", text: ok(result, { chain: chainName, protocol, token_in, token_out }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { protocol, token_in, token_out }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_dex_swap — execute swap\n// ============================================================\n\nserver.tool(\n \"defi_dex_swap\",\n \"Execute a token swap on a DEX. Defaults to dry-run. Set broadcast=true to send transaction\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n protocol: z.string().describe(\"Protocol slug, e.g. uniswap-v3\"),\n token_in: z.string().describe(\"Input token symbol or address\"),\n token_out: z.string().describe(\"Output token symbol or address\"),\n amount_in: z.string().describe(\"Amount of input token in wei\"),\n slippage_bps: z.number().optional().describe(\"Slippage tolerance in basis points (default: 50 = 0.5%)\"),\n recipient: z.string().optional().describe(\"Recipient address (default: DEFI_WALLET_ADDRESS)\"),\n broadcast: z.boolean().optional().describe(\"Set true to broadcast (default: false)\"),\n },\n async ({ chain, protocol, token_in, token_out, amount_in, slippage_bps, recipient, broadcast }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocolConfig = registry.getProtocol(protocol);\n const adapter = createDex(protocolConfig, chainConfig.effectiveRpcUrl());\n const tokenIn = resolveToken(registry, chainName, token_in);\n const tokenOut = resolveToken(registry, chainName, token_out);\n const recipientAddr = (recipient ?? process.env[\"DEFI_WALLET_ADDRESS\"] ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildSwap({\n protocol: protocolConfig.name,\n token_in: tokenIn,\n token_out: tokenOut,\n amount_in: BigInt(amount_in),\n slippage: { bps: slippage_bps ?? 50 },\n recipient: recipientAddr,\n });\n const executor = makeExecutor(broadcast ?? false, chainConfig.effectiveRpcUrl(), chainConfig.explorer_url);\n const result = await executor.execute(tx);\n return { content: [{ type: \"text\", text: ok(result, { chain: chainName, protocol, token_in, token_out, broadcast: broadcast ?? false }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { protocol, token_in, token_out }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_dex_lp_add — add liquidity\n// ============================================================\n\nserver.tool(\n \"defi_dex_lp_add\",\n \"Add liquidity to a DEX pool. Defaults to dry-run. Set broadcast=true to send transaction\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n protocol: z.string().describe(\"Protocol slug, e.g. uniswap-v3\"),\n token_a: z.string().describe(\"First token symbol or address\"),\n token_b: z.string().describe(\"Second token symbol or address\"),\n amount_a: z.string().describe(\"Amount of token A in wei\"),\n amount_b: z.string().describe(\"Amount of token B in wei\"),\n recipient: z.string().optional().describe(\"Recipient address for LP tokens\"),\n broadcast: z.boolean().optional().describe(\"Set true to broadcast (default: false)\"),\n },\n async ({ chain, protocol, token_a, token_b, amount_a, amount_b, recipient, broadcast }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocolConfig = registry.getProtocol(protocol);\n const adapter = createDex(protocolConfig, chainConfig.effectiveRpcUrl());\n const tokenA = resolveToken(registry, chainName, token_a);\n const tokenB = resolveToken(registry, chainName, token_b);\n const recipientAddr = (recipient ?? process.env[\"DEFI_WALLET_ADDRESS\"] ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildAddLiquidity({\n protocol: protocolConfig.name,\n token_a: tokenA,\n token_b: tokenB,\n amount_a: BigInt(amount_a),\n amount_b: BigInt(amount_b),\n recipient: recipientAddr,\n });\n const executor = makeExecutor(broadcast ?? false, chainConfig.effectiveRpcUrl(), chainConfig.explorer_url);\n const result = await executor.execute(tx);\n return { content: [{ type: \"text\", text: ok(result, { chain: chainName, protocol, token_a, token_b, broadcast: broadcast ?? false }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { protocol }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_dex_lp_remove — remove liquidity\n// ============================================================\n\nserver.tool(\n \"defi_dex_lp_remove\",\n \"Remove liquidity from a DEX pool. Defaults to dry-run. Set broadcast=true to send transaction\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n protocol: z.string().describe(\"Protocol slug, e.g. uniswap-v3\"),\n token_a: z.string().describe(\"First token symbol or address\"),\n token_b: z.string().describe(\"Second token symbol or address\"),\n liquidity: z.string().describe(\"Liquidity amount to remove in wei\"),\n recipient: z.string().optional().describe(\"Recipient address for returned tokens\"),\n broadcast: z.boolean().optional().describe(\"Set true to broadcast (default: false)\"),\n },\n async ({ chain, protocol, token_a, token_b, liquidity, recipient, broadcast }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocolConfig = registry.getProtocol(protocol);\n const adapter = createDex(protocolConfig, chainConfig.effectiveRpcUrl());\n const tokenA = resolveToken(registry, chainName, token_a);\n const tokenB = resolveToken(registry, chainName, token_b);\n const recipientAddr = (recipient ?? process.env[\"DEFI_WALLET_ADDRESS\"] ?? \"0x0000000000000000000000000000000000000001\") as Address;\n const tx = await adapter.buildRemoveLiquidity({\n protocol: protocolConfig.name,\n token_a: tokenA,\n token_b: tokenB,\n liquidity: BigInt(liquidity),\n recipient: recipientAddr,\n });\n const executor = makeExecutor(broadcast ?? false, chainConfig.effectiveRpcUrl(), chainConfig.explorer_url);\n const result = await executor.execute(tx);\n return { content: [{ type: \"text\", text: ok(result, { chain: chainName, protocol, token_a, token_b, broadcast: broadcast ?? false }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { protocol }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_bridge — cross-chain bridge quote\n// ============================================================\n\nserver.tool(\n \"defi_bridge\",\n \"Get a cross-chain bridge quote via LI.FI, deBridge DLN, or Circle CCTP. Returns estimated output amount and fees\",\n {\n from_chain: z.string().describe(\"Source chain name, e.g. ethereum, arbitrum, base\"),\n to_chain: z.string().describe(\"Destination chain name, e.g. hyperevm, arbitrum\"),\n token: z.string().optional().describe(\"Token symbol to bridge (default: USDC). Use native for native token\"),\n amount: z.string().describe(\"Amount in human-readable units, e.g. '100' for 100 USDC\"),\n recipient: z.string().optional().describe(\"Recipient address on destination chain\"),\n },\n async ({ from_chain, to_chain, token, amount, recipient }) => {\n try {\n const tokenSymbol = token ?? \"USDC\";\n const recipientAddr = recipient ?? process.env[\"DEFI_WALLET_ADDRESS\"] ?? \"0x0000000000000000000000000000000000000001\";\n\n // Use LI.FI API for a quote\n const LIFI_API = \"https://li.quest/v1\";\n const registry = getRegistry();\n\n let fromChainId: number | undefined;\n let toChainId: number | undefined;\n try {\n fromChainId = registry.getChain(from_chain).chain_id;\n } catch { /* use name */ }\n try {\n toChainId = registry.getChain(to_chain).chain_id;\n } catch { /* use name */ }\n\n const params = new URLSearchParams({\n fromChain: fromChainId ? String(fromChainId) : from_chain,\n toChain: toChainId ? String(toChainId) : to_chain,\n fromToken: tokenSymbol,\n toToken: tokenSymbol,\n fromAmount: String(Math.round(parseFloat(amount) * 1e6)), // USDC decimals\n toAddress: recipientAddr,\n });\n\n const res = await fetch(`${LIFI_API}/quote?${params}`, {\n headers: { Accept: \"application/json\" },\n });\n\n if (!res.ok) {\n const text = await res.text();\n throw new Error(`LI.FI quote failed (${res.status}): ${text.slice(0, 200)}`);\n }\n\n const data = await res.json() as Record<string, unknown>;\n const estimate = data.estimate as Record<string, unknown> | undefined;\n\n const quote = {\n from_chain,\n to_chain,\n token: tokenSymbol,\n amount_in: amount,\n amount_out: estimate?.toAmount ? String(Number(estimate.toAmount as string) / 1e6) : \"unknown\",\n fee_costs: estimate?.feeCosts ?? [],\n gas_costs: estimate?.gasCosts ?? [],\n execution_duration_seconds: estimate?.executionDuration ?? \"unknown\",\n tool: (data.tool as string) ?? \"unknown\",\n raw: data,\n };\n\n return { content: [{ type: \"text\", text: ok(quote, { from_chain, to_chain, token: tokenSymbol }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { from_chain, to_chain }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_vault_info — vault information\n// ============================================================\n\nserver.tool(\n \"defi_vault_info\",\n \"Get vault information: TVL, APY, total shares, and underlying asset details\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n protocol: z.string().describe(\"Protocol slug for the vault\"),\n },\n async ({ chain, protocol }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocolConfig = registry.getProtocol(protocol);\n const adapter = createVault(protocolConfig, chainConfig.effectiveRpcUrl());\n const info = await adapter.getVaultInfo();\n return { content: [{ type: \"text\", text: ok(info, { chain: chainName, protocol }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { protocol }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_staking_info — staking information\n// ============================================================\n\nserver.tool(\n \"defi_staking_info\",\n \"Get liquid staking protocol info: exchange rate, APY, total staked\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n protocol: z.string().describe(\"Protocol slug for the staking protocol\"),\n },\n async ({ chain, protocol }) => {\n try {\n const chainName = chain ?? \"hyperevm\";\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const protocolConfig = registry.getProtocol(protocol);\n const adapter = createLiquidStaking(protocolConfig, chainConfig.effectiveRpcUrl());\n const info = await adapter.getInfo();\n return { content: [{ type: \"text\", text: ok(info, { chain: chainName, protocol }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { protocol }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_price — asset price query\n// ============================================================\n\nserver.tool(\n \"defi_price\",\n \"Query asset price from on-chain oracles (Aave V3) and/or DEX spot prices\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n asset: z.string().describe(\"Token symbol (e.g. WBTC) or address (0x...)\"),\n source: z.enum([\"oracle\", \"dex\", \"all\"]).optional().describe(\"Price source: oracle, dex, or all (default: all)\"),\n },\n async ({ chain, asset, source }) => {\n try {\n const chainName = (chain ?? \"hyperevm\").toLowerCase();\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const rpcUrl = chainConfig.effectiveRpcUrl();\n const srcMode = source ?? \"all\";\n\n let assetAddr: Address;\n let assetSymbol: string;\n try {\n if (/^0x[0-9a-fA-F]{40}$/.test(asset)) {\n assetAddr = asset as Address;\n assetSymbol = asset;\n } else {\n const token = registry.resolveToken(chainName, asset);\n assetAddr = token.address as Address;\n assetSymbol = token.symbol;\n }\n } catch (e) {\n return { content: [{ type: \"text\", text: err(`Could not resolve asset: ${asset}`) }], isError: true };\n }\n\n const { ProtocolCategory } = await import(\"@hypurrquant/defi-core\");\n const { createOracleFromLending } = await import(\"@hypurrquant/defi-protocols\");\n\n const prices: Array<{ source: string; source_type: string; price: number }> = [];\n\n if (srcMode === \"all\" || srcMode === \"oracle\") {\n const lendingProtos = registry.getProtocolsForChain(chainName)\n .filter(p => p.category === ProtocolCategory.Lending);\n await Promise.all(lendingProtos.map(async (p) => {\n try {\n const oracle = createOracleFromLending(p, rpcUrl);\n const price = await oracle.getPrice(assetAddr);\n if (price.price_f64 > 0) prices.push({ source: p.slug, source_type: \"oracle\", price: price.price_f64 });\n } catch { /* skip */ }\n }));\n }\n\n if (srcMode === \"all\" || srcMode === \"dex\") {\n const { DexSpotPrice } = await import(\"@hypurrquant/defi-protocols\");\n const USDC_SYMBOL = \"USDC\";\n let usdcAddr: Address | undefined;\n let usdcDecimals = 6;\n try {\n const usdcToken = registry.resolveToken(chainName, USDC_SYMBOL);\n usdcAddr = usdcToken.address as Address;\n usdcDecimals = usdcToken.decimals;\n } catch { /* no USDC on chain */ }\n\n // Determine asset decimals from registry if resolved by symbol, else default 18\n let assetDecimals = 18;\n if (!/^0x[0-9a-fA-F]{40}$/.test(asset)) {\n try { assetDecimals = registry.resolveToken(chainName, asset).decimals; } catch { /* default 18 */ }\n }\n\n if (usdcAddr && assetAddr.toLowerCase() !== usdcAddr.toLowerCase()) {\n const dexProtos = registry.getProtocolsForChain(chainName)\n .filter(p => p.category === ProtocolCategory.Dex);\n await Promise.all(dexProtos.map(async (p) => {\n try {\n const dex = createDex(p, rpcUrl);\n const priceData = await DexSpotPrice.getPrice(dex, assetAddr, assetDecimals, usdcAddr!, usdcDecimals);\n if (priceData.price_f64 > 0) prices.push({ source: p.slug, source_type: \"dex\", price: priceData.price_f64 });\n } catch { /* skip */ }\n }));\n }\n }\n\n if (prices.length === 0) {\n return { content: [{ type: \"text\", text: err(`No price data found for ${assetSymbol} on ${chainName}`) }], isError: true };\n }\n\n const priceValues = prices.map(p => p.price);\n const avg = priceValues.reduce((a, b) => a + b, 0) / priceValues.length;\n const min = Math.min(...priceValues);\n const max = Math.max(...priceValues);\n const spread = max > 0 ? ((max - min) / max) * 100 : 0;\n\n const report = {\n asset: assetSymbol,\n asset_address: assetAddr,\n prices,\n average_price: Math.round(avg * 100) / 100,\n max_spread_pct: Math.round(spread * 100) / 100,\n };\n\n return { content: [{ type: \"text\", text: ok(report, { chain: chainName, asset: assetSymbol, source: srcMode }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { asset }) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_scan — exploit / price manipulation detection\n// ============================================================\n\nserver.tool(\n \"defi_scan\",\n \"Scan for potential price manipulation or exploit opportunities by comparing oracle prices vs DEX spot prices across lending protocols\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n min_spread_pct: z.number().optional().describe(\"Minimum oracle-vs-dex spread % to flag (default: 5)\"),\n },\n async ({ chain, min_spread_pct }) => {\n try {\n const chainName = (chain ?? \"hyperevm\").toLowerCase();\n const minSpread = min_spread_pct ?? 5;\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const rpcUrl = chainConfig.effectiveRpcUrl();\n\n const { ProtocolCategory } = await import(\"@hypurrquant/defi-core\");\n const { createOracleFromLending, DexSpotPrice } = await import(\"@hypurrquant/defi-protocols\");\n\n const tokens = registry.tokens.get(chainName) ?? [];\n const lendingProtos = registry.getProtocolsForChain(chainName)\n .filter(p => p.category === ProtocolCategory.Lending);\n const dexProtos = registry.getProtocolsForChain(chainName)\n .filter(p => p.category === ProtocolCategory.Dex);\n\n let usdcAddr: Address | undefined;\n try {\n usdcAddr = registry.resolveToken(chainName, \"USDC\").address as Address;\n } catch { /* no USDC */ }\n\n const findings: Array<{\n token: string;\n address: string;\n oracle_price: number;\n dex_price: number;\n spread_pct: number;\n verdict: string;\n }> = [];\n\n for (const token of tokens.slice(0, 20)) {\n const addr = token.address as Address;\n if (!usdcAddr || addr.toLowerCase() === usdcAddr.toLowerCase()) continue;\n\n let oraclePrice = 0;\n let dexPrice = 0;\n\n for (const p of lendingProtos) {\n try {\n const oracle = createOracleFromLending(p, rpcUrl);\n const priceData = await oracle.getPrice(addr);\n if (priceData.price_f64 > 0) { oraclePrice = priceData.price_f64; break; }\n } catch { /* skip */ }\n }\n\n for (const p of dexProtos) {\n try {\n const dex = createDex(p, rpcUrl);\n const priceData = await DexSpotPrice.getPrice(dex, addr, token.decimals, usdcAddr!, 6);\n if (priceData.price_f64 > 0) { dexPrice = priceData.price_f64; break; }\n } catch { /* skip */ }\n }\n\n if (oraclePrice > 0 && dexPrice > 0) {\n const spread = Math.abs(oraclePrice - dexPrice) / Math.max(oraclePrice, dexPrice) * 100;\n if (spread >= minSpread) {\n findings.push({\n token: token.symbol,\n address: addr,\n oracle_price: Math.round(oraclePrice * 10000) / 10000,\n dex_price: Math.round(dexPrice * 10000) / 10000,\n spread_pct: Math.round(spread * 100) / 100,\n verdict: spread >= 20 ? \"HIGH_RISK\" : spread >= 10 ? \"MEDIUM_RISK\" : \"LOW_RISK\",\n });\n }\n }\n }\n\n findings.sort((a, b) => b.spread_pct - a.spread_pct);\n\n return {\n content: [{\n type: \"text\",\n text: ok(\n { chain: chainName, findings, scanned_tokens: Math.min(tokens.length, 20), min_spread_pct: minSpread },\n { finding_count: findings.length },\n ),\n }],\n };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e)) }], isError: true };\n }\n },\n);\n\n// ============================================================\n// defi_portfolio — portfolio overview\n// ============================================================\n\nserver.tool(\n \"defi_portfolio\",\n \"Get a portfolio overview for a wallet address: lending positions, token balances, and health factors across all protocols on a chain\",\n {\n chain: z.string().optional().describe(\"Chain name (default: hyperevm)\"),\n address: z.string().describe(\"Wallet address to query (0x...)\"),\n },\n async ({ chain, address }) => {\n try {\n const chainName = (chain ?? \"hyperevm\").toLowerCase();\n\n if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {\n return { content: [{ type: \"text\", text: err(`Invalid address: ${address}`) }], isError: true };\n }\n\n const registry = getRegistry();\n const chainConfig = registry.getChain(chainName);\n const rpcUrl = chainConfig.effectiveRpcUrl();\n const user = address as Address;\n\n const { ProtocolCategory, multicallRead } = await import(\"@hypurrquant/defi-core\");\n const { createLending: _createLending } = await import(\"@hypurrquant/defi-protocols\");\n const { encodeFunctionData, parseAbi } = await import(\"viem\");\n\n const POOL_ABI = parseAbi([\n \"function getUserAccountData(address user) external view returns (uint256 totalCollateralBase, uint256 totalDebtBase, uint256 availableBorrowsBase, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)\",\n ]);\n\n const lendingProtos = registry.getProtocolsForChain(chainName)\n .filter(p => p.category === ProtocolCategory.Lending);\n\n const lendingPositions: Array<{\n protocol: string;\n total_collateral_usd: number;\n total_debt_usd: number;\n available_borrows_usd: number;\n health_factor: number;\n ltv: number;\n }> = [];\n\n for (const p of lendingProtos) {\n const poolAddr = (p.contracts as Record<string, string> | undefined)?.pool;\n if (!poolAddr) continue;\n try {\n const callData = encodeFunctionData({ abi: POOL_ABI, functionName: \"getUserAccountData\", args: [user] });\n const results = await multicallRead(rpcUrl, [[poolAddr as Address, callData as `0x${string}`]]);\n const raw = results[0];\n if (!raw || raw.length < 2 + 6 * 64) continue;\n const hex = raw.slice(2);\n const decodeU256 = (offset: number) => BigInt(\"0x\" + hex.slice(offset * 64, offset * 64 + 64));\n const totalCollateral = Number(decodeU256(0)) / 1e8;\n const totalDebt = Number(decodeU256(1)) / 1e8;\n const availableBorrows = Number(decodeU256(2)) / 1e8;\n const ltv = Number(decodeU256(4)) / 100;\n const hfRaw = decodeU256(5);\n const healthFactor = hfRaw >= BigInt(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\") / 2n\n ? 999999\n : Math.round(Number(hfRaw) / 1e16) / 100;\n\n if (totalCollateral > 0 || totalDebt > 0) {\n lendingPositions.push({\n protocol: p.slug,\n total_collateral_usd: Math.round(totalCollateral * 100) / 100,\n total_debt_usd: Math.round(totalDebt * 100) / 100,\n available_borrows_usd: Math.round(availableBorrows * 100) / 100,\n health_factor: healthFactor,\n ltv,\n });\n }\n } catch { /* skip */ }\n }\n\n const totalCollateralUsd = lendingPositions.reduce((s, p) => s + p.total_collateral_usd, 0);\n const totalDebtUsd = lendingPositions.reduce((s, p) => s + p.total_debt_usd, 0);\n\n const portfolio = {\n address,\n chain: chainName,\n lending_positions: lendingPositions,\n summary: {\n total_collateral_usd: Math.round(totalCollateralUsd * 100) / 100,\n total_debt_usd: Math.round(totalDebtUsd * 100) / 100,\n net_position_usd: Math.round((totalCollateralUsd - totalDebtUsd) * 100) / 100,\n active_protocols: lendingPositions.length,\n },\n };\n\n return { content: [{ type: \"text\", text: ok(portfolio, { chain: chainName, address }) }] };\n } catch (e) {\n return { content: [{ type: \"text\", text: err(e instanceof Error ? e.message : String(e), { address }) }], isError: true };\n }\n },\n);\n\n// ── Start server ──\n\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\n","import { createPublicClient, createWalletClient, http, parseAbi, encodeFunctionData } from \"viem\";\nimport type { Address } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport { DefiError } from \"@hypurrquant/defi-core\";\nimport type { ActionResult, DeFiTx, TxStatus } from \"@hypurrquant/defi-core\";\n\nconst ERC20_ABI = parseAbi([\n \"function allowance(address owner, address spender) external view returns (uint256)\",\n \"function approve(address spender, uint256 amount) external returns (bool)\",\n]);\n\n/** Gas buffer multiplier: 120% over estimated gas (20% headroom) */\nconst GAS_BUFFER_BPS = 12000n;\n\n/** Default max priority fee (tip) in wei — 20 gwei (safe for Mantle + EVM chains) */\nconst DEFAULT_PRIORITY_FEE_WEI = 20_000_000_000n;\n\n/** Max gas limit cap — Mantle uses high gas units (up to 5B for complex txs) */\nconst MAX_GAS_LIMIT = 5_000_000_000n; // 5B\n\nexport class Executor {\n readonly dryRun: boolean;\n readonly rpcUrl: string | undefined;\n readonly explorerUrl: string | undefined;\n\n constructor(broadcast: boolean, rpcUrl?: string, explorerUrl?: string) {\n this.dryRun = !broadcast;\n this.rpcUrl = rpcUrl;\n this.explorerUrl = explorerUrl;\n }\n\n /** Apply 20% buffer to a gas estimate */\n private static applyGasBuffer(gas: bigint): bigint {\n return (gas * GAS_BUFFER_BPS) / 10000n;\n }\n\n /**\n * Check allowance for a single token/spender pair and send an approve tx if needed.\n * Only called in broadcast mode (not dry-run).\n */\n private async checkAndApprove(\n token: Address,\n spender: Address,\n amount: bigint,\n owner: Address,\n publicClient: ReturnType<typeof createPublicClient>,\n walletClient: ReturnType<typeof createWalletClient>,\n ): Promise<void> {\n const allowance = await publicClient.readContract({\n address: token,\n abi: ERC20_ABI,\n functionName: \"allowance\",\n args: [owner, spender],\n });\n\n if (allowance >= amount) return;\n\n process.stderr.write(\n ` Approving ${amount} of ${token} for ${spender}...\\n`,\n );\n\n const approveData = encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [spender, amount],\n });\n\n const rpcUrl = this.rpcUrl!;\n const gasLimit = await (async () => {\n try {\n const estimated = await publicClient.estimateGas({\n to: token,\n data: approveData,\n account: owner,\n });\n const buffered = Executor.applyGasBuffer(estimated);\n return buffered > MAX_GAS_LIMIT ? MAX_GAS_LIMIT : buffered;\n } catch {\n return 80_000n;\n }\n })();\n\n const [maxFeePerGas, maxPriorityFeePerGas] = await this.fetchEip1559Fees(rpcUrl);\n\n const approveTxHash = await walletClient.sendTransaction({\n chain: null,\n account: walletClient.account!,\n to: token,\n data: approveData,\n gas: gasLimit > 0n ? gasLimit : undefined,\n maxFeePerGas: maxFeePerGas > 0n ? maxFeePerGas : undefined,\n maxPriorityFeePerGas: maxPriorityFeePerGas > 0n ? maxPriorityFeePerGas : undefined,\n });\n\n const approveTxUrl = this.explorerUrl\n ? `${this.explorerUrl}/tx/${approveTxHash}`\n : undefined;\n process.stderr.write(` Approve tx: ${approveTxHash}\\n`);\n if (approveTxUrl) process.stderr.write(` Explorer: ${approveTxUrl}\\n`);\n\n await publicClient.waitForTransactionReceipt({ hash: approveTxHash });\n process.stderr.write(\n ` Approved ${amount} of ${token} for ${spender}\\n`,\n );\n }\n\n /** Fetch EIP-1559 fee params from the network. Returns [maxFeePerGas, maxPriorityFeePerGas]. */\n private async fetchEip1559Fees(rpcUrl: string): Promise<[bigint, bigint]> {\n try {\n const client = createPublicClient({ transport: http(rpcUrl) });\n const gasPrice = await client.getGasPrice();\n let priorityFee = DEFAULT_PRIORITY_FEE_WEI;\n try {\n priorityFee = await client.estimateMaxPriorityFeePerGas();\n } catch {\n // fallback to default\n }\n const maxFee = gasPrice * 2n + priorityFee;\n return [maxFee, priorityFee];\n } catch {\n return [0n, 0n];\n }\n }\n\n /** Estimate gas dynamically with buffer, falling back to a hardcoded estimate */\n private async estimateGasWithBuffer(\n rpcUrl: string,\n tx: DeFiTx,\n from: `0x${string}`,\n ): Promise<bigint> {\n try {\n const client = createPublicClient({ transport: http(rpcUrl) });\n const estimated = await client.estimateGas({\n to: tx.to,\n data: tx.data,\n value: tx.value,\n account: from,\n });\n if (estimated > 0n) {\n const buffered = Executor.applyGasBuffer(estimated);\n return buffered > MAX_GAS_LIMIT ? MAX_GAS_LIMIT : buffered;\n }\n } catch {\n // fallback\n }\n return tx.gas_estimate ? BigInt(tx.gas_estimate) : 0n;\n }\n\n /** Simulate a transaction via eth_call + eth_estimateGas */\n private async simulate(tx: DeFiTx): Promise<ActionResult> {\n const rpcUrl = this.rpcUrl;\n if (!rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL — cannot simulate. Set HYPEREVM_RPC_URL.\");\n }\n\n const client = createPublicClient({ transport: http(rpcUrl) });\n\n const privateKey = process.env[\"DEFI_PRIVATE_KEY\"];\n const from: `0x${string}` = privateKey\n ? privateKeyToAccount(privateKey as `0x${string}`).address\n : \"0x0000000000000000000000000000000000000001\";\n\n try {\n await client.call({ to: tx.to, data: tx.data, value: tx.value, account: from });\n\n const gasEstimate = await this.estimateGasWithBuffer(rpcUrl, tx, from);\n const [maxFee, priorityFee] = await this.fetchEip1559Fees(rpcUrl);\n\n return {\n tx_hash: undefined,\n status: \"simulated\" as TxStatus,\n gas_used: gasEstimate > 0n ? Number(gasEstimate) : undefined,\n description: tx.description,\n details: {\n to: tx.to,\n from,\n data: tx.data,\n value: tx.value.toString(),\n gas_estimate: gasEstimate.toString(),\n max_fee_per_gas_gwei: (Number(maxFee) / 1e9).toFixed(4),\n max_priority_fee_gwei: (Number(priorityFee) / 1e9).toFixed(4),\n mode: \"simulated\",\n result: \"success\",\n },\n };\n } catch (e: unknown) {\n const errMsg = String(e);\n const revertReason = extractRevertReason(errMsg);\n\n return {\n tx_hash: undefined,\n status: \"simulation_failed\" as TxStatus,\n gas_used: tx.gas_estimate,\n description: tx.description,\n details: {\n to: tx.to,\n from,\n data: tx.data,\n value: tx.value.toString(),\n mode: \"simulated\",\n result: \"revert\",\n revert_reason: revertReason,\n },\n };\n }\n }\n\n async execute(tx: DeFiTx): Promise<ActionResult> {\n if (this.dryRun) {\n if (this.rpcUrl) {\n return this.simulate(tx);\n }\n\n return {\n tx_hash: undefined,\n status: \"dry_run\" as TxStatus,\n gas_used: tx.gas_estimate,\n description: tx.description,\n details: {\n to: tx.to,\n data: tx.data,\n value: tx.value.toString(),\n mode: \"dry_run\",\n },\n };\n }\n\n // === Broadcast mode ===\n const privateKey = process.env[\"DEFI_PRIVATE_KEY\"];\n if (!privateKey) {\n throw DefiError.invalidParam(\n \"DEFI_PRIVATE_KEY environment variable not set. Required for --broadcast.\",\n );\n }\n\n const account = privateKeyToAccount(privateKey as `0x${string}`);\n\n const rpcUrl = this.rpcUrl;\n if (!rpcUrl) {\n throw DefiError.rpcError(\"No RPC URL configured for broadcasting\");\n }\n\n const publicClient = createPublicClient({ transport: http(rpcUrl) });\n const walletClient = createWalletClient({ account, transport: http(rpcUrl) });\n\n // Auto-approve ERC20 tokens if needed\n if (tx.approvals && tx.approvals.length > 0) {\n for (const approval of tx.approvals) {\n await this.checkAndApprove(\n approval.token,\n approval.spender,\n approval.amount,\n account.address,\n publicClient,\n walletClient,\n );\n }\n }\n\n // Dynamic gas estimation with buffer\n const gasLimit = await this.estimateGasWithBuffer(rpcUrl, tx, account.address);\n\n // EIP-1559 gas pricing\n const [maxFeePerGas, maxPriorityFeePerGas] = await this.fetchEip1559Fees(rpcUrl);\n\n process.stderr.write(`Broadcasting transaction to ${rpcUrl}...\\n`);\n if (gasLimit > 0n) {\n process.stderr.write(` Gas limit: ${gasLimit} (with 20% buffer)\\n`);\n }\n\n const txHash = await walletClient.sendTransaction({\n chain: null,\n to: tx.to,\n data: tx.data,\n value: tx.value,\n gas: gasLimit > 0n ? gasLimit : undefined,\n maxFeePerGas: maxFeePerGas > 0n ? maxFeePerGas : undefined,\n maxPriorityFeePerGas: maxPriorityFeePerGas > 0n ? maxPriorityFeePerGas : undefined,\n });\n\n const txUrl = this.explorerUrl ? `${this.explorerUrl}/tx/${txHash}` : undefined;\n process.stderr.write(`Transaction sent: ${txHash}\\n`);\n if (txUrl) process.stderr.write(`Explorer: ${txUrl}\\n`);\n process.stderr.write(\"Waiting for confirmation...\\n\");\n\n const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash });\n\n const status = receipt.status === \"success\" ? \"confirmed\" : \"failed\";\n\n return {\n tx_hash: txHash,\n status: status as TxStatus,\n gas_used: receipt.gasUsed ? Number(receipt.gasUsed) : undefined,\n description: tx.description,\n details: {\n to: tx.to,\n from: account.address,\n block_number: receipt.blockNumber?.toString(),\n gas_limit: gasLimit.toString(),\n gas_used: receipt.gasUsed?.toString(),\n explorer_url: txUrl,\n mode: \"broadcast\",\n },\n };\n }\n}\n\n/** Extract a human-readable revert reason from an RPC error message */\nfunction extractRevertReason(err: string): string {\n for (const marker of [\"execution reverted:\", \"revert:\", \"Error(\"]) {\n const pos = err.indexOf(marker);\n if (pos !== -1) return err.slice(pos);\n }\n return err.length > 200 ? err.slice(0, 200) + \"...\" : err;\n}\n"],"mappings":";;;;;;;;;;;;;AA2BA,SAAS,kBAAkB,QAAQ,KAAK;AACpC,MAAI,QAAQ,OAAO,MAAM,GAAG,GAAG,EAAE,MAAM,aAAa;AACpD,SAAO,CAAC,MAAM,QAAQ,MAAM,IAAI,EAAE,SAAS,CAAC;AAChD;AACA,SAAS,cAAc,QAAQ,MAAM,QAAQ;AACzC,MAAI,QAAQ,OAAO,MAAM,aAAa;AACtC,MAAI,YAAY;AAChB,MAAI,aAAa,KAAK,MAAM,OAAO,CAAC,IAAI,KAAK;AAC7C,WAAS,IAAI,OAAO,GAAG,KAAK,OAAO,GAAG,KAAK;AACvC,QAAI,IAAI,MAAM,IAAI,CAAC;AACnB,QAAI,CAAC;AACD;AACJ,iBAAa,EAAE,SAAS,EAAE,OAAO,WAAW,GAAG;AAC/C,iBAAa;AACb,iBAAa;AACb,iBAAa;AACb,QAAI,MAAM,MAAM;AACZ,mBAAa,IAAI,OAAO,YAAY,SAAS,CAAC;AAC9C,mBAAa;AAAA,IACjB;AAAA,EACJ;AACA,SAAO;AACX;AAjDA,IAkDa;AAlDb;AAAA;AAAA;AAkDO,IAAM,YAAN,cAAwB,MAAM;AAAA,MACjC;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AAM,IAAI,EAAE,gBAAgB,CAAC;AAE9E,YAAM,YAAY;AAAA,QAChB;AAAA,QACA,OAAO;AAAA,QACP,mBAAmB;AAAA,QACnB,SAAS;AAAA,UACP,sBAAsB,KAAK,MAAM,qBAAqB,GAAG,IAAI;AAAA,UAC7D,gBAAgB,KAAK,MAAM,eAAe,GAAG,IAAI;AAAA,UACjD,kBAAkB,KAAK,OAAO,qBAAqB,gBAAgB,GAAG,IAAI;AAAA,UAC1E,kBAAkB,iBAAiB;AAAA,QACrC;AAAA,MACF;AAEA,aAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,GAAG,WAAW,EAAE,OAAO,WAAW,QAAQ,CAAC,EAAE,CAAC,EAAE;AAAA,IAC3F,SAAS,GAAG;AACV,aAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,IAAI,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,GAAG,EAAE,QAAQ,CAAC,EAAE,CAAC,GAAG,SAAS,KAAK;AAAA,IAC1H;AAAA,EACF;AACF;AAIA,IAAM,YAAY,IAAI,qBAAqB;AAC3C,MAAM,OAAO,QAAQ,SAAS;","names":["endPtr","encodeFunctionData","parseAbi","TxStatus","InterestRateMode","ProtocolCategory","encodeFunctionData","parseAbi","createPublicClient","http","decodeFunctionResult","decodeAbiParameters","zeroAddress","u256ToF64","DefiError","abi","POOL_ABI","ERC20_ABI","ORACLE_ABI","SECONDS_PER_YEAR","init_dist","client","amountOut","best","result","data","InterestRateMode","init_dist","init_dist","createPublicClient","http","parseAbi","encodeFunctionData","ERC20_ABI","err","ProtocolCategory","createOracleFromLending","DexSpotPrice","multicallRead","encodeFunctionData","parseAbi","POOL_ABI","decodeU256"]}