@aegis-engine/core 0.13.0 → 0.14.0
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.
- package/dist/account.js +1 -129
- package/dist/aegis-core.js +71 -10384
- package/dist/contract/generated/aegis-swap.d.ts +310 -5
- package/dist/contract/generated/market-data.d.ts +310 -5
- package/dist/engine/account/activitySchemas.d.ts +1 -0
- package/dist/engine/account/discoverySchemas.d.ts +101 -0
- package/dist/engine/account/portfolioSchemas.d.ts +2 -0
- package/dist/engine/account/transactionSchemas.d.ts +1 -0
- package/dist/engine/account/transport.d.ts +6 -0
- package/dist/engine/account/types.d.ts +1 -0
- package/dist/engine/dataSource.d.ts +4 -1
- package/dist/engine/registry.d.ts +15 -0
- package/dist/engine/sdkDeployment.d.ts +16 -0
- package/dist/engine/types.d.ts +5 -1
- package/dist/index.d.ts +2 -0
- package/dist/sdkRuntime-CvLRgf5w.js +1593 -0
- package/dist/transactionHistory-BGpe2c7k.js +149 -0
- package/package.json +2 -2
- package/dist/sdkRuntime-Dra77GTA.js +0 -18757
- package/dist/transactionHistory-CFVVYJeo.js +0 -6994
|
@@ -0,0 +1,1593 @@
|
|
|
1
|
+
var Bs=Object.defineProperty;var Fs=(e,t,n)=>t in e?Bs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var oe=(e,t,n)=>Fs(e,typeof t!="symbol"?t+"":t,n);import{keccak256 as xt,zeroAddress as ke,erc721Abi as Ht,hashTypedData as Vs,isAddress as sn,erc20Abi as qr,encodeFunctionData as Ln,BaseError as oa,ContractFunctionRevertedError as Ji,numberToHex as Us,encodeAbiParameters as eo,parseAbiParameters as Ws,RpcRequestError as to,isHex as no,decodeErrorResult as $s,ExecutionRevertedError as Ya,getEventSelector as Je,getAbiItem as et,parseAbi as sa,toEventSelector as Hs}from"viem";import"viem/actions";import{Z as Qa,J as Xa}from"./transactionHistory-BGpe2c7k.js";class f extends Array{constructor(t,n){if(super(t),this.sign=n,t>f.__kMaxLength)throw new RangeError("Maximum BigInt size exceeded");}static BigInt(t){var n=Math.floor,r=Number.isFinite;if(typeof t=="number"){if(t===0)return f.__zero();if(f.__isOneDigitInt(t))return 0>t?f.__oneDigit(-t,!0):f.__oneDigit(t,!1);if(!r(t)||n(t)!==t)throw new RangeError("The number "+t+" cannot be converted to BigInt because it is not an integer");return f.__fromDouble(t);}if(typeof t=="string"){const a=f.__fromString(t);if(a===null)throw new SyntaxError("Cannot convert "+t+" to a BigInt");return a;}if(typeof t=="boolean")return t===!0?f.__oneDigit(1,!1):f.__zero();if(typeof t=="object"){if(t.constructor===f)return t;const a=f.__toPrimitive(t);return f.BigInt(a);}throw new TypeError("Cannot convert "+t+" to a BigInt");}toDebugString(){const t=["BigInt["];for(const n of this)t.push((n&&(n>>>0).toString(16))+", ");return t.push("]"),t.join("");}toString(t=10){if(2>t||36<t)throw new RangeError("toString() radix argument must be between 2 and 36");return this.length===0?"0":(t&t-1)==0?f.__toStringBasePowerOfTwo(this,t):f.__toStringGeneric(this,t,!1);}static toNumber(t){const n=t.length;if(n===0)return 0;if(n===1){const h=t.__unsignedDigit(0);return t.sign?-h:h;}const r=t.__digit(n-1),a=f.__clz30(r),i=30*n-a;if(1024<i)return t.sign?-1/0:1/0;let o=i-1,s=r,l=n-1;const u=a+3;let d=u===32?0:s<<u;d>>>=12;const c=u-12;let p=12<=u?0:s<<20+u,y=20+u;for(0<c&&0<l&&(l--,s=t.__digit(l),d|=s>>>30-c,p=s<<c+2,y=c+2);0<y&&0<l;)l--,s=t.__digit(l),p|=30<=y?s<<y-30:s>>>30-y,y-=30;const b=f.__decideRounding(t,y,l,s);if((b===1||b===0&&(1&p)==1)&&(p=p+1>>>0,p===0&&(d++,d>>>20!=0&&(d=0,o++,1023<o))))return t.sign?-1/0:1/0;const m=t.sign?-2147483648:0;return o=o+1023<<20,f.__kBitConversionInts[1]=m|o|d,f.__kBitConversionInts[0]=p,f.__kBitConversionDouble[0];}static unaryMinus(t){if(t.length===0)return t;const n=t.__copy();return n.sign=!t.sign,n;}static bitwiseNot(t){return t.sign?f.__absoluteSubOne(t).__trim():f.__absoluteAddOne(t,!0);}static exponentiate(t,n){if(n.sign)throw new RangeError("Exponent must be positive");if(n.length===0)return f.__oneDigit(1,!1);if(t.length===0)return t;if(t.length===1&&t.__digit(0)===1)return t.sign&&(1&n.__digit(0))==0?f.unaryMinus(t):t;if(1<n.length)throw new RangeError("BigInt too big");let r=n.__unsignedDigit(0);if(r===1)return t;if(r>=f.__kMaxLengthBits)throw new RangeError("BigInt too big");if(t.length===1&&t.__digit(0)===2){const o=1+(0|r/30),s=t.sign&&(1&r)!=0,l=new f(o,s);l.__initializeDigits();const u=1<<r%30;return l.__setDigit(o-1,u),l;}let a=null,i=t;for((1&r)!=0&&(a=t),r>>=1;r!==0;r>>=1)i=f.multiply(i,i),(1&r)!=0&&(a===null?a=i:a=f.multiply(a,i));return a;}static multiply(t,n){if(t.length===0)return t;if(n.length===0)return n;let r=t.length+n.length;30<=t.__clzmsd()+n.__clzmsd()&&r--;const a=new f(r,t.sign!==n.sign);a.__initializeDigits();for(let i=0;i<t.length;i++)f.__multiplyAccumulate(n,t.__digit(i),a,i);return a.__trim();}static divide(t,n){if(n.length===0)throw new RangeError("Division by zero");if(0>f.__absoluteCompare(t,n))return f.__zero();const r=t.sign!==n.sign,a=n.__unsignedDigit(0);let i;if(n.length===1&&32767>=a){if(a===1)return r===t.sign?t:f.unaryMinus(t);i=f.__absoluteDivSmall(t,a,null);}else i=f.__absoluteDivLarge(t,n,!0,!1);return i.sign=r,i.__trim();}static remainder(t,n){if(n.length===0)throw new RangeError("Division by zero");if(0>f.__absoluteCompare(t,n))return t;const r=n.__unsignedDigit(0);if(n.length===1&&32767>=r){if(r===1)return f.__zero();const i=f.__absoluteModSmall(t,r);return i===0?f.__zero():f.__oneDigit(i,t.sign);}const a=f.__absoluteDivLarge(t,n,!1,!0);return a.sign=t.sign,a.__trim();}static add(t,n){const r=t.sign;return r===n.sign?f.__absoluteAdd(t,n,r):0<=f.__absoluteCompare(t,n)?f.__absoluteSub(t,n,r):f.__absoluteSub(n,t,!r);}static subtract(t,n){const r=t.sign;return r===n.sign?0<=f.__absoluteCompare(t,n)?f.__absoluteSub(t,n,r):f.__absoluteSub(n,t,!r):f.__absoluteAdd(t,n,r);}static leftShift(t,n){return n.length===0||t.length===0?t:n.sign?f.__rightShiftByAbsolute(t,n):f.__leftShiftByAbsolute(t,n);}static signedRightShift(t,n){return n.length===0||t.length===0?t:n.sign?f.__leftShiftByAbsolute(t,n):f.__rightShiftByAbsolute(t,n);}static unsignedRightShift(){throw new TypeError("BigInts have no unsigned right shift; use >> instead");}static lessThan(t,n){return 0>f.__compareToBigInt(t,n);}static lessThanOrEqual(t,n){return 0>=f.__compareToBigInt(t,n);}static greaterThan(t,n){return 0<f.__compareToBigInt(t,n);}static greaterThanOrEqual(t,n){return 0<=f.__compareToBigInt(t,n);}static equal(t,n){if(t.sign!==n.sign||t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t.__digit(r)!==n.__digit(r))return!1;return!0;}static notEqual(t,n){return!f.equal(t,n);}static bitwiseAnd(t,n){var r=Math.max;if(!t.sign&&!n.sign)return f.__absoluteAnd(t,n).__trim();if(t.sign&&n.sign){const a=r(t.length,n.length)+1;let i=f.__absoluteSubOne(t,a);const o=f.__absoluteSubOne(n);return i=f.__absoluteOr(i,o,i),f.__absoluteAddOne(i,!0,i).__trim();}return t.sign&&([t,n]=[n,t]),f.__absoluteAndNot(t,f.__absoluteSubOne(n)).__trim();}static bitwiseXor(t,n){var r=Math.max;if(!t.sign&&!n.sign)return f.__absoluteXor(t,n).__trim();if(t.sign&&n.sign){const o=r(t.length,n.length),s=f.__absoluteSubOne(t,o),l=f.__absoluteSubOne(n);return f.__absoluteXor(s,l,s).__trim();}const a=r(t.length,n.length)+1;t.sign&&([t,n]=[n,t]);let i=f.__absoluteSubOne(n,a);return i=f.__absoluteXor(i,t,i),f.__absoluteAddOne(i,!0,i).__trim();}static bitwiseOr(t,n){var r=Math.max;const a=r(t.length,n.length);if(!t.sign&&!n.sign)return f.__absoluteOr(t,n).__trim();if(t.sign&&n.sign){let o=f.__absoluteSubOne(t,a);const s=f.__absoluteSubOne(n);return o=f.__absoluteAnd(o,s,o),f.__absoluteAddOne(o,!0,o).__trim();}t.sign&&([t,n]=[n,t]);let i=f.__absoluteSubOne(n,a);return i=f.__absoluteAndNot(i,t,i),f.__absoluteAddOne(i,!0,i).__trim();}static asIntN(t,n){var r=Math.floor;if(n.length===0)return n;if(t=r(t),0>t)throw new RangeError("Invalid value: not (convertible to) a safe integer");if(t===0)return f.__zero();if(t>=f.__kMaxLengthBits)return n;const a=0|(t+29)/30;if(n.length<a)return n;const i=n.__unsignedDigit(a-1),o=1<<(t-1)%30;if(n.length===a&&i<o)return n;if((i&o)!==o)return f.__truncateToNBits(t,n);if(!n.sign)return f.__truncateAndSubFromPowerOfTwo(t,n,!0);if((i&o-1)==0){for(let s=a-2;0<=s;s--)if(n.__digit(s)!==0)return f.__truncateAndSubFromPowerOfTwo(t,n,!1);return n.length===a&&i===o?n:f.__truncateToNBits(t,n);}return f.__truncateAndSubFromPowerOfTwo(t,n,!1);}static asUintN(t,n){var r=Math.floor;if(n.length===0)return n;if(t=r(t),0>t)throw new RangeError("Invalid value: not (convertible to) a safe integer");if(t===0)return f.__zero();if(n.sign){if(t>f.__kMaxLengthBits)throw new RangeError("BigInt too big");return f.__truncateAndSubFromPowerOfTwo(t,n,!1);}if(t>=f.__kMaxLengthBits)return n;const a=0|(t+29)/30;if(n.length<a)return n;const i=t%30;return n.length==a&&(i===0||!(n.__digit(a-1)>>>i))?n:f.__truncateToNBits(t,n);}static ADD(t,n){if(t=f.__toPrimitive(t),n=f.__toPrimitive(n),typeof t=="string")return typeof n!="string"&&(n=n.toString()),t+n;if(typeof n=="string")return t.toString()+n;if(t=f.__toNumeric(t),n=f.__toNumeric(n),f.__isBigInt(t)&&f.__isBigInt(n))return f.add(t,n);if(typeof t=="number"&&typeof n=="number")return t+n;throw new TypeError("Cannot mix BigInt and other types, use explicit conversions");}static LT(t,n){return f.__compare(t,n,0);}static LE(t,n){return f.__compare(t,n,1);}static GT(t,n){return f.__compare(t,n,2);}static GE(t,n){return f.__compare(t,n,3);}static EQ(t,n){for(;;){if(f.__isBigInt(t))return f.__isBigInt(n)?f.equal(t,n):f.EQ(n,t);if(typeof t=="number"){if(f.__isBigInt(n))return f.__equalToNumber(n,t);if(typeof n!="object")return t==n;n=f.__toPrimitive(n);}else if(typeof t=="string"){if(f.__isBigInt(n))return t=f.__fromString(t),t!==null&&f.equal(t,n);if(typeof n!="object")return t==n;n=f.__toPrimitive(n);}else if(typeof t=="boolean"){if(f.__isBigInt(n))return f.__equalToNumber(n,+t);if(typeof n!="object")return t==n;n=f.__toPrimitive(n);}else if(typeof t=="symbol"){if(f.__isBigInt(n))return!1;if(typeof n!="object")return t==n;n=f.__toPrimitive(n);}else if(typeof t=="object"){if(typeof n=="object"&&n.constructor!==f)return t==n;t=f.__toPrimitive(t);}else return t==n;}}static NE(t,n){return!f.EQ(t,n);}static __zero(){return new f(0,!1);}static __oneDigit(t,n){const r=new f(1,n);return r.__setDigit(0,t),r;}__copy(){const t=new f(this.length,this.sign);for(let n=0;n<this.length;n++)t[n]=this[n];return t;}__trim(){let t=this.length,n=this[t-1];for(;n===0;)t--,n=this[t-1],this.pop();return t===0&&(this.sign=!1),this;}__initializeDigits(){for(let t=0;t<this.length;t++)this[t]=0;}static __decideRounding(t,n,r,a){if(0<n)return-1;let i;if(0>n)i=-n-1;else{if(r===0)return-1;r--,a=t.__digit(r),i=29;}let o=1<<i;if((a&o)==0)return-1;if(o-=1,(a&o)!=0)return 1;for(;0<r;)if(r--,t.__digit(r)!==0)return 1;return 0;}static __fromDouble(t){f.__kBitConversionDouble[0]=t;const n=2047&f.__kBitConversionInts[1]>>>20,r=n-1023,a=(0|r/30)+1,i=new f(a,0>t);let o=1048575&f.__kBitConversionInts[1]|1048576,s=f.__kBitConversionInts[0];const l=20,u=r%30;let d,c=0;if(u<20){const p=l-u;c=p+32,d=o>>>p,o=o<<32-p|s>>>p,s<<=32-p;}else if(u===20)c=32,d=o,o=s,s=0;else{const p=u-l;c=32-p,d=o<<p|s>>>32-p,o=s<<p,s=0;}i.__setDigit(a-1,d);for(let p=a-2;0<=p;p--)0<c?(c-=30,d=o>>>2,o=o<<30|s>>>2,s<<=30):d=0,i.__setDigit(p,d);return i.__trim();}static __isWhitespace(t){return 13>=t&&9<=t||(159>=t?t==32:131071>=t?t==160||t==5760:196607>=t?(t&=131071,10>=t||t==40||t==41||t==47||t==95||t==4096):t==65279);}static __fromString(t,n=0){let r=0;const a=t.length;let i=0;if(i===a)return f.__zero();let o=t.charCodeAt(i);for(;f.__isWhitespace(o);){if(++i===a)return f.__zero();o=t.charCodeAt(i);}if(o===43){if(++i===a)return null;o=t.charCodeAt(i),r=1;}else if(o===45){if(++i===a)return null;o=t.charCodeAt(i),r=-1;}if(n===0){if(n=10,o===48){if(++i===a)return f.__zero();if(o=t.charCodeAt(i),o===88||o===120){if(n=16,++i===a)return null;o=t.charCodeAt(i);}else if(o===79||o===111){if(n=8,++i===a)return null;o=t.charCodeAt(i);}else if(o===66||o===98){if(n=2,++i===a)return null;o=t.charCodeAt(i);}}}else if(n===16&&o===48){if(++i===a)return f.__zero();if(o=t.charCodeAt(i),o===88||o===120){if(++i===a)return null;o=t.charCodeAt(i);}}if(r!=0&&n!==10)return null;for(;o===48;){if(++i===a)return f.__zero();o=t.charCodeAt(i);}const s=a-i;let l=f.__kMaxBitsPerChar[n],u=f.__kBitsPerCharTableMultiplier-1;if(s>1073741824/l)return null;const d=l*s+u>>>f.__kBitsPerCharTableShift,c=new f(0|(d+29)/30,!1),p=10>n?n:10,y=10<n?n-10:0;if((n&n-1)==0){l>>=f.__kBitsPerCharTableShift;const b=[],m=[];let h=!1;do{let g=0,v=0;for(;;){let w;if(o-48>>>0<p)w=o-48;else if((32|o)-97>>>0<y)w=(32|o)-87;else{h=!0;break;}if(v+=l,g=g<<l|w,++i===a){h=!0;break;}if(o=t.charCodeAt(i),30<v+l)break;}b.push(g),m.push(v);}while(!h);f.__fillFromParts(c,b,m);}else{c.__initializeDigits();let b=!1,m=0;do{let h=0,g=1;for(;;){let w;if(o-48>>>0<p)w=o-48;else if((32|o)-97>>>0<y)w=(32|o)-87;else{b=!0;break;}const E=g*n;if(1073741823<E)break;if(g=E,h=h*n+w,m++,++i===a){b=!0;break;}o=t.charCodeAt(i);}u=30*f.__kBitsPerCharTableMultiplier-1;const v=0|(l*m+u>>>f.__kBitsPerCharTableShift)/30;c.__inplaceMultiplyAdd(g,h,v);}while(!b);}if(i!==a){if(!f.__isWhitespace(o))return null;for(i++;i<a;i++)if(o=t.charCodeAt(i),!f.__isWhitespace(o))return null;}return c.sign=r==-1,c.__trim();}static __fillFromParts(t,n,r){let a=0,i=0,o=0;for(let s=n.length-1;0<=s;s--){const l=n[s],u=r[s];i|=l<<o,o+=u,o===30?(t.__setDigit(a++,i),o=0,i=0):30<o&&(t.__setDigit(a++,1073741823&i),o-=30,i=l>>>u-o);}if(i!==0){if(a>=t.length)throw new Error("implementation bug");t.__setDigit(a++,i);}for(;a<t.length;a++)t.__setDigit(a,0);}static __toStringBasePowerOfTwo(t,n){const r=t.length;let a=n-1;a=(85&a>>>1)+(85&a),a=(51&a>>>2)+(51&a),a=(15&a>>>4)+(15&a);const i=a,o=n-1,s=t.__digit(r-1),l=f.__clz30(s);let u=0|(30*r-l+i-1)/i;if(t.sign&&u++,268435456<u)throw new Error("string too long");const d=Array(u);let c=u-1,p=0,y=0;for(let m=0;m<r-1;m++){const h=t.__digit(m),g=(p|h<<y)&o;d[c--]=f.__kConversionChars[g];const v=i-y;for(p=h>>>v,y=30-v;y>=i;)d[c--]=f.__kConversionChars[p&o],p>>>=i,y-=i;}const b=(p|s<<y)&o;for(d[c--]=f.__kConversionChars[b],p=s>>>i-y;p!==0;)d[c--]=f.__kConversionChars[p&o],p>>>=i;if(t.sign&&(d[c--]="-"),c!=-1)throw new Error("implementation bug");return d.join("");}static __toStringGeneric(t,n,r){const a=t.length;if(a===0)return"";if(a===1){let m=t.__unsignedDigit(0).toString(n);return r===!1&&t.sign&&(m="-"+m),m;}const i=30*a-f.__clz30(t.__digit(a-1)),o=f.__kMaxBitsPerChar[n],s=o-1;let l=i*f.__kBitsPerCharTableMultiplier;l+=s-1,l=0|l/s;const u=l+1>>1,d=f.exponentiate(f.__oneDigit(n,!1),f.__oneDigit(u,!1));let c,p;const y=d.__unsignedDigit(0);if(d.length===1&&32767>=y){c=new f(t.length,!1),c.__initializeDigits();let m=0;for(let h=2*t.length-1;0<=h;h--){const g=m<<15|t.__halfDigit(h);c.__setHalfDigit(h,0|g/y),m=0|g%y;}p=m.toString(n);}else{const m=f.__absoluteDivLarge(t,d,!0,!0);c=m.quotient;const h=m.remainder.__trim();p=f.__toStringGeneric(h,n,!0);}c.__trim();let b=f.__toStringGeneric(c,n,!0);for(;p.length<u;)p="0"+p;return r===!1&&t.sign&&(b="-"+b),b+p;}static __unequalSign(t){return t?-1:1;}static __absoluteGreater(t){return t?-1:1;}static __absoluteLess(t){return t?1:-1;}static __compareToBigInt(t,n){const r=t.sign;if(r!==n.sign)return f.__unequalSign(r);const a=f.__absoluteCompare(t,n);return 0<a?f.__absoluteGreater(r):0>a?f.__absoluteLess(r):0;}static __compareToNumber(t,n){if(f.__isOneDigitInt(n)){const r=t.sign,a=0>n;if(r!==a)return f.__unequalSign(r);if(t.length===0){if(a)throw new Error("implementation bug");return n===0?0:-1;}if(1<t.length)return f.__absoluteGreater(r);const i=Math.abs(n),o=t.__unsignedDigit(0);return o>i?f.__absoluteGreater(r):o<i?f.__absoluteLess(r):0;}return f.__compareToDouble(t,n);}static __compareToDouble(t,n){if(n!==n)return n;if(n===1/0)return-1;if(n===-1/0)return 1;const r=t.sign;if(r!==0>n)return f.__unequalSign(r);if(n===0)throw new Error("implementation bug: should be handled elsewhere");if(t.length===0)return-1;f.__kBitConversionDouble[0]=n;const a=2047&f.__kBitConversionInts[1]>>>20;if(a==2047)throw new Error("implementation bug: handled elsewhere");const i=a-1023;if(0>i)return f.__absoluteGreater(r);const o=t.length;let s=t.__digit(o-1);const l=f.__clz30(s),u=30*o-l,d=i+1;if(u<d)return f.__absoluteLess(r);if(u>d)return f.__absoluteGreater(r);let c=1048576|1048575&f.__kBitConversionInts[1],p=f.__kBitConversionInts[0];const y=20,b=29-l;if(b!==(0|(u-1)%30))throw new Error("implementation bug");let m,h=0;if(20>b){const g=y-b;h=g+32,m=c>>>g,c=c<<32-g|p>>>g,p<<=32-g;}else if(b===20)h=32,m=c,c=p,p=0;else{const g=b-y;h=32-g,m=c<<g|p>>>32-g,c=p<<g,p=0;}if(s>>>=0,m>>>=0,s>m)return f.__absoluteGreater(r);if(s<m)return f.__absoluteLess(r);for(let g=o-2;0<=g;g--){0<h?(h-=30,m=c>>>2,c=c<<30|p>>>2,p<<=30):m=0;const v=t.__unsignedDigit(g);if(v>m)return f.__absoluteGreater(r);if(v<m)return f.__absoluteLess(r);}if(c!==0||p!==0){if(h===0)throw new Error("implementation bug");return f.__absoluteLess(r);}return 0;}static __equalToNumber(t,n){var r=Math.abs;return f.__isOneDigitInt(n)?n===0?t.length===0:t.length===1&&t.sign===0>n&&t.__unsignedDigit(0)===r(n):f.__compareToDouble(t,n)===0;}static __comparisonResultToBool(t,n){return n===0?0>t:n===1?0>=t:n===2?0<t:n===3?0<=t:void 0;}static __compare(t,n,r){if(t=f.__toPrimitive(t),n=f.__toPrimitive(n),typeof t=="string"&&typeof n=="string")switch(r){case 0:return t<n;case 1:return t<=n;case 2:return t>n;case 3:return t>=n;}if(f.__isBigInt(t)&&typeof n=="string")return n=f.__fromString(n),n!==null&&f.__comparisonResultToBool(f.__compareToBigInt(t,n),r);if(typeof t=="string"&&f.__isBigInt(n))return t=f.__fromString(t),t!==null&&f.__comparisonResultToBool(f.__compareToBigInt(t,n),r);if(t=f.__toNumeric(t),n=f.__toNumeric(n),f.__isBigInt(t)){if(f.__isBigInt(n))return f.__comparisonResultToBool(f.__compareToBigInt(t,n),r);if(typeof n!="number")throw new Error("implementation bug");return f.__comparisonResultToBool(f.__compareToNumber(t,n),r);}if(typeof t!="number")throw new Error("implementation bug");if(f.__isBigInt(n))return f.__comparisonResultToBool(f.__compareToNumber(n,t),2^r);if(typeof n!="number")throw new Error("implementation bug");return r===0?t<n:r===1?t<=n:r===2?t>n:r===3?t>=n:void 0;}__clzmsd(){return f.__clz30(this.__digit(this.length-1));}static __absoluteAdd(t,n,r){if(t.length<n.length)return f.__absoluteAdd(n,t,r);if(t.length===0)return t;if(n.length===0)return t.sign===r?t:f.unaryMinus(t);let a=t.length;(t.__clzmsd()===0||n.length===t.length&&n.__clzmsd()===0)&&a++;const i=new f(a,r);let o=0,s=0;for(;s<n.length;s++){const l=t.__digit(s)+n.__digit(s)+o;o=l>>>30,i.__setDigit(s,1073741823&l);}for(;s<t.length;s++){const l=t.__digit(s)+o;o=l>>>30,i.__setDigit(s,1073741823&l);}return s<i.length&&i.__setDigit(s,o),i.__trim();}static __absoluteSub(t,n,r){if(t.length===0)return t;if(n.length===0)return t.sign===r?t:f.unaryMinus(t);const a=new f(t.length,r);let i=0,o=0;for(;o<n.length;o++){const s=t.__digit(o)-n.__digit(o)-i;i=1&s>>>30,a.__setDigit(o,1073741823&s);}for(;o<t.length;o++){const s=t.__digit(o)-i;i=1&s>>>30,a.__setDigit(o,1073741823&s);}return a.__trim();}static __absoluteAddOne(t,n,r=null){const a=t.length;r===null?r=new f(a,n):r.sign=n;let i=1;for(let o=0;o<a;o++){const s=t.__digit(o)+i;i=s>>>30,r.__setDigit(o,1073741823&s);}return i!=0&&r.__setDigitGrow(a,1),r;}static __absoluteSubOne(t,n){const r=t.length;n=n||r;const a=new f(n,!1);let i=1;for(let o=0;o<r;o++){const s=t.__digit(o)-i;i=1&s>>>30,a.__setDigit(o,1073741823&s);}if(i!=0)throw new Error("implementation bug");for(let o=r;o<n;o++)a.__setDigit(o,0);return a;}static __absoluteAnd(t,n,r=null){let a=t.length,i=n.length,o=i;if(a<i){o=a;const u=t,d=a;t=n,a=i,n=u,i=d;}let s=o;r===null?r=new f(s,!1):s=r.length;let l=0;for(;l<o;l++)r.__setDigit(l,t.__digit(l)&n.__digit(l));for(;l<s;l++)r.__setDigit(l,0);return r;}static __absoluteAndNot(t,n,r=null){const a=t.length,i=n.length;let o=i;a<i&&(o=a);let s=a;r===null?r=new f(s,!1):s=r.length;let l=0;for(;l<o;l++)r.__setDigit(l,t.__digit(l)&~n.__digit(l));for(;l<a;l++)r.__setDigit(l,t.__digit(l));for(;l<s;l++)r.__setDigit(l,0);return r;}static __absoluteOr(t,n,r=null){let a=t.length,i=n.length,o=i;if(a<i){o=a;const u=t,d=a;t=n,a=i,n=u,i=d;}let s=a;r===null?r=new f(s,!1):s=r.length;let l=0;for(;l<o;l++)r.__setDigit(l,t.__digit(l)|n.__digit(l));for(;l<a;l++)r.__setDigit(l,t.__digit(l));for(;l<s;l++)r.__setDigit(l,0);return r;}static __absoluteXor(t,n,r=null){let a=t.length,i=n.length,o=i;if(a<i){o=a;const u=t,d=a;t=n,a=i,n=u,i=d;}let s=a;r===null?r=new f(s,!1):s=r.length;let l=0;for(;l<o;l++)r.__setDigit(l,t.__digit(l)^n.__digit(l));for(;l<a;l++)r.__setDigit(l,t.__digit(l));for(;l<s;l++)r.__setDigit(l,0);return r;}static __absoluteCompare(t,n){const r=t.length-n.length;if(r!=0)return r;let a=t.length-1;for(;0<=a&&t.__digit(a)===n.__digit(a);)a--;return 0>a?0:t.__unsignedDigit(a)>n.__unsignedDigit(a)?1:-1;}static __multiplyAccumulate(t,n,r,a){if(n===0)return;const i=32767&n,o=n>>>15;let s=0,l=0;for(let u,d=0;d<t.length;d++,a++){u=r.__digit(a);const c=t.__digit(d),p=32767&c,y=c>>>15,b=f.__imul(p,i),m=f.__imul(p,o),h=f.__imul(y,i),g=f.__imul(y,o);u+=l+b+s,s=u>>>30,u&=1073741823,u+=((32767&m)<<15)+((32767&h)<<15),s+=u>>>30,l=g+(m>>>15)+(h>>>15),r.__setDigit(a,1073741823&u);}for(;s!=0||l!==0;a++){let u=r.__digit(a);u+=s+l,l=0,s=u>>>30,r.__setDigit(a,1073741823&u);}}static __internalMultiplyAdd(t,n,r,a,i){let o=r,s=0;for(let l=0;l<a;l++){const u=t.__digit(l),d=f.__imul(32767&u,n),c=f.__imul(u>>>15,n),p=d+((32767&c)<<15)+s+o;o=p>>>30,s=c>>>15,i.__setDigit(l,1073741823&p);}if(i.length>a)for(i.__setDigit(a++,o+s);a<i.length;)i.__setDigit(a++,0);else if(o+s!==0)throw new Error("implementation bug");}__inplaceMultiplyAdd(t,n,r){r>this.length&&(r=this.length);const a=32767&t,i=t>>>15;let o=0,s=n;for(let l=0;l<r;l++){const u=this.__digit(l),d=32767&u,c=u>>>15,p=f.__imul(d,a),y=f.__imul(d,i),b=f.__imul(c,a),m=f.__imul(c,i);let h=s+p+o;o=h>>>30,h&=1073741823,h+=((32767&y)<<15)+((32767&b)<<15),o+=h>>>30,s=m+(y>>>15)+(b>>>15),this.__setDigit(l,1073741823&h);}if(o!=0||s!==0)throw new Error("implementation bug");}static __absoluteDivSmall(t,n,r=null){r===null&&(r=new f(t.length,!1));let a=0;for(let i,o=2*t.length-1;0<=o;o-=2){i=(a<<15|t.__halfDigit(o))>>>0;const s=0|i/n;a=0|i%n,i=(a<<15|t.__halfDigit(o-1))>>>0;const l=0|i/n;a=0|i%n,r.__setDigit(o>>>1,s<<15|l);}return r;}static __absoluteModSmall(t,n){let r=0;for(let a=2*t.length-1;0<=a;a--)r=0|((r<<15|t.__halfDigit(a))>>>0)%n;return r;}static __absoluteDivLarge(t,n,r,a){const i=n.__halfDigitLength(),o=n.length,s=t.__halfDigitLength()-i;let l=null;r&&(l=new f(s+2>>>1,!1),l.__initializeDigits());const u=new f(i+2>>>1,!1);u.__initializeDigits();const d=f.__clz15(n.__halfDigit(i-1));0<d&&(n=f.__specialLeftShift(n,d,0));const c=f.__specialLeftShift(t,d,1),p=n.__halfDigit(i-1);let y=0;for(let b,m=s;0<=m;m--){b=32767;const h=c.__halfDigit(m+i);if(h!==p){const v=(h<<15|c.__halfDigit(m+i-1))>>>0;b=0|v/p;let w=0|v%p;const E=n.__halfDigit(i-2),A=c.__halfDigit(m+i-2);for(;f.__imul(b,E)>>>0>(w<<16|A)>>>0&&(b--,w+=p,!(32767<w)););}f.__internalMultiplyAdd(n,b,0,o,u);let g=c.__inplaceSub(u,m,i+1);g!==0&&(g=c.__inplaceAdd(n,m,i),c.__setHalfDigit(m+i,32767&c.__halfDigit(m+i)+g),b--),r&&(1&m?y=b<<15:l.__setDigit(m>>>1,y|b));}if(a)return c.__inplaceRightShift(d),r?{quotient:l,remainder:c}:c;if(r)return l;throw new Error("unreachable");}static __clz15(t){return f.__clz30(t)-15;}__inplaceAdd(t,n,r){let a=0;for(let i=0;i<r;i++){const o=this.__halfDigit(n+i)+t.__halfDigit(i)+a;a=o>>>15,this.__setHalfDigit(n+i,32767&o);}return a;}__inplaceSub(t,n,r){let a=0;if(1&n){n>>=1;let i=this.__digit(n),o=32767&i,s=0;for(;s<r-1>>>1;s++){const d=t.__digit(s),c=(i>>>15)-(32767&d)-a;a=1&c>>>15,this.__setDigit(n+s,(32767&c)<<15|32767&o),i=this.__digit(n+s+1),o=(32767&i)-(d>>>15)-a,a=1&o>>>15;}const l=t.__digit(s),u=(i>>>15)-(32767&l)-a;if(a=1&u>>>15,this.__setDigit(n+s,(32767&u)<<15|32767&o),n+s+1>=this.length)throw new RangeError("out of bounds");(1&r)==0&&(i=this.__digit(n+s+1),o=(32767&i)-(l>>>15)-a,a=1&o>>>15,this.__setDigit(n+t.length,1073709056&i|32767&o));}else{n>>=1;let i=0;for(;i<t.length-1;i++){const d=this.__digit(n+i),c=t.__digit(i),p=(32767&d)-(32767&c)-a;a=1&p>>>15;const y=(d>>>15)-(c>>>15)-a;a=1&y>>>15,this.__setDigit(n+i,(32767&y)<<15|32767&p);}const o=this.__digit(n+i),s=t.__digit(i),l=(32767&o)-(32767&s)-a;a=1&l>>>15;let u=0;(1&r)==0&&(u=(o>>>15)-(s>>>15)-a,a=1&u>>>15),this.__setDigit(n+i,(32767&u)<<15|32767&l);}return a;}__inplaceRightShift(t){if(t===0)return;let n=this.__digit(0)>>>t;const r=this.length-1;for(let a=0;a<r;a++){const i=this.__digit(a+1);this.__setDigit(a,1073741823&i<<30-t|n),n=i>>>t;}this.__setDigit(r,n);}static __specialLeftShift(t,n,r){const a=t.length,i=new f(a+r,!1);if(n===0){for(let s=0;s<a;s++)i.__setDigit(s,t.__digit(s));return 0<r&&i.__setDigit(a,0),i;}let o=0;for(let s=0;s<a;s++){const l=t.__digit(s);i.__setDigit(s,1073741823&l<<n|o),o=l>>>30-n;}return 0<r&&i.__setDigit(a,o),i;}static __leftShiftByAbsolute(t,n){const r=f.__toShiftAmount(n);if(0>r)throw new RangeError("BigInt too big");const a=0|r/30,i=r%30,o=t.length,s=i!==0&&t.__digit(o-1)>>>30-i!=0,l=o+a+(s?1:0),u=new f(l,t.sign);if(i===0){let d=0;for(;d<a;d++)u.__setDigit(d,0);for(;d<l;d++)u.__setDigit(d,t.__digit(d-a));}else{let d=0;for(let c=0;c<a;c++)u.__setDigit(c,0);for(let c=0;c<o;c++){const p=t.__digit(c);u.__setDigit(c+a,1073741823&p<<i|d),d=p>>>30-i;}if(s)u.__setDigit(o+a,d);else if(d!==0)throw new Error("implementation bug");}return u.__trim();}static __rightShiftByAbsolute(t,n){const r=t.length,a=t.sign,i=f.__toShiftAmount(n);if(0>i)return f.__rightShiftByMaximum(a);const o=0|i/30,s=i%30;let l=r-o;if(0>=l)return f.__rightShiftByMaximum(a);let u=!1;if(a){if((t.__digit(o)&(1<<s)-1)!=0)u=!0;else for(let c=0;c<o;c++)if(t.__digit(c)!==0){u=!0;break;}}u&&s===0&&~t.__digit(r-1)==0&&l++;let d=new f(l,a);if(s===0){d.__setDigit(l-1,0);for(let c=o;c<r;c++)d.__setDigit(c-o,t.__digit(c));}else{let c=t.__digit(o)>>>s;const p=r-o-1;for(let y=0;y<p;y++){const b=t.__digit(y+o+1);d.__setDigit(y,1073741823&b<<30-s|c),c=b>>>s;}d.__setDigit(p,c);}return u&&(d=f.__absoluteAddOne(d,!0,d)),d.__trim();}static __rightShiftByMaximum(t){return t?f.__oneDigit(1,!0):f.__zero();}static __toShiftAmount(t){if(1<t.length)return-1;const n=t.__unsignedDigit(0);return n>f.__kMaxLengthBits?-1:n;}static __toPrimitive(t,n="default"){if(typeof t!="object"||t.constructor===f)return t;if(typeof Symbol<"u"&&typeof Symbol.toPrimitive=="symbol"){const i=t[Symbol.toPrimitive];if(i){const o=i(n);if(typeof o!="object")return o;throw new TypeError("Cannot convert object to primitive value");}}const r=t.valueOf;if(r){const i=r.call(t);if(typeof i!="object")return i;}const a=t.toString;if(a){const i=a.call(t);if(typeof i!="object")return i;}throw new TypeError("Cannot convert object to primitive value");}static __toNumeric(t){return f.__isBigInt(t)?t:+t;}static __isBigInt(t){return typeof t=="object"&&t!==null&&t.constructor===f;}static __truncateToNBits(t,n){const r=0|(t+29)/30,a=new f(r,n.sign),i=r-1;for(let s=0;s<i;s++)a.__setDigit(s,n.__digit(s));let o=n.__digit(i);if(t%30!=0){const s=32-t%30;o=o<<s>>>s;}return a.__setDigit(i,o),a.__trim();}static __truncateAndSubFromPowerOfTwo(t,n,r){var a=Math.min;const i=0|(t+29)/30,o=new f(i,r);let s=0;const l=i-1;let u=0;for(const y=a(l,n.length);s<y;s++){const b=0-n.__digit(s)-u;u=1&b>>>30,o.__setDigit(s,1073741823&b);}for(;s<l;s++)o.__setDigit(s,0|1073741823&-u);let d=l<n.length?n.__digit(l):0;const c=t%30;let p;if(c==0)p=0-d-u,p&=1073741823;else{const y=32-c;d=d<<y>>>y;const b=1<<32-y;p=b-d-u,p&=b-1;}return o.__setDigit(l,p),o.__trim();}__digit(t){return this[t];}__unsignedDigit(t){return this[t]>>>0;}__setDigit(t,n){this[t]=0|n;}__setDigitGrow(t,n){this[t]=0|n;}__halfDigitLength(){const t=this.length;return 32767>=this.__unsignedDigit(t-1)?2*t-1:2*t;}__halfDigit(t){return 32767&this[t>>>1]>>>15*(1&t);}__setHalfDigit(t,n){const r=t>>>1,a=this.__digit(r),i=1&t?32767&a|n<<15:1073709056&a|32767&n;this.__setDigit(r,i);}static __digitPow(t,n){let r=1;for(;0<n;)1&n&&(r*=t),n>>>=1,t*=t;return r;}static __isOneDigitInt(t){return(1073741823&t)===t;}}f.__kMaxLength=33554432,f.__kMaxLengthBits=f.__kMaxLength<<5,f.__kMaxBitsPerChar=[0,0,32,51,64,75,83,90,96,102,107,111,115,119,122,126,128,131,134,136,139,141,143,145,147,149,151,153,154,156,158,159,160,162,163,165,166],f.__kBitsPerCharTableShift=5,f.__kBitsPerCharTableMultiplier=1<<f.__kBitsPerCharTableShift,f.__kConversionChars=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"],f.__kBitConversionBuffer=new ArrayBuffer(8),f.__kBitConversionDouble=new Float64Array(f.__kBitConversionBuffer),f.__kBitConversionInts=new Int32Array(f.__kBitConversionBuffer),f.__clz30=Math.clz32?function(e){return Math.clz32(e)-2;}:function(e){return e===0?30:0|29-(0|Math.log(e>>>0)/Math.LN2);},f.__imul=Math.imul||function(e,t){return 0|e*t;};var Za;(function(e){e[e.EXACT_INPUT=0]="EXACT_INPUT",e[e.EXACT_OUTPUT=1]="EXACT_OUTPUT";})(Za||(Za={}));var Ja;(function(e){e[e.ROUND_DOWN=0]="ROUND_DOWN",e[e.ROUND_HALF_UP=1]="ROUND_HALF_UP",e[e.ROUND_UP=2]="ROUND_UP";})(Ja||(Ja={}));const er=f.BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var zs="Invariant failed";function Qe(e,t){throw new Error(zs);}var Yt=1e9,Gs={// These values must be integers within the stated ranges (inclusive).
|
|
2
|
+
// Most of these values can be changed during run-time using `Decimal.config`.
|
|
3
|
+
// The maximum number of significant digits of the result of a calculation or base conversion.
|
|
4
|
+
// E.g. `Decimal.config({ precision: 20 });`
|
|
5
|
+
precision:20,// 1 to MAX_DIGITS
|
|
6
|
+
// The rounding mode used by default by `toInteger`, `toDecimalPlaces`, `toExponential`,
|
|
7
|
+
// `toFixed`, `toPrecision` and `toSignificantDigits`.
|
|
8
|
+
//
|
|
9
|
+
// ROUND_UP 0 Away from zero.
|
|
10
|
+
// ROUND_DOWN 1 Towards zero.
|
|
11
|
+
// ROUND_CEIL 2 Towards +Infinity.
|
|
12
|
+
// ROUND_FLOOR 3 Towards -Infinity.
|
|
13
|
+
// ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up.
|
|
14
|
+
// ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
|
|
15
|
+
// ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
|
|
16
|
+
// ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
|
|
17
|
+
// ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
|
|
18
|
+
//
|
|
19
|
+
// E.g.
|
|
20
|
+
// `Decimal.rounding = 4;`
|
|
21
|
+
// `Decimal.rounding = Decimal.ROUND_HALF_UP;`
|
|
22
|
+
rounding:4,// 0 to 8
|
|
23
|
+
// The exponent value at and beneath which `toString` returns exponential notation.
|
|
24
|
+
// JavaScript numbers: -7
|
|
25
|
+
toExpNeg:-7,// 0 to -MAX_E
|
|
26
|
+
// The exponent value at and above which `toString` returns exponential notation.
|
|
27
|
+
// JavaScript numbers: 21
|
|
28
|
+
toExpPos:21,// 0 to MAX_E
|
|
29
|
+
// The natural logarithm of 10.
|
|
30
|
+
// 115 digits
|
|
31
|
+
LN10:"2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"},ua,xe=!0,Ge="[DecimalError] ",kt=Ge+"Invalid argument: ",la=Ge+"Exponent out of range: ",Qt=Math.floor,Tt=Math.pow,js=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,He,Re=1e7,Ee=7,ro=9007199254740991,Vn=Qt(ro/Ee),U={};U.absoluteValue=U.abs=function(){var e=new this.constructor(this);return e.s&&(e.s=1),e;};U.comparedTo=U.cmp=function(e){var t,n,r,a,i=this;if(e=new i.constructor(e),i.s!==e.s)return i.s||-e.s;if(i.e!==e.e)return i.e>e.e^i.s<0?1:-1;for(r=i.d.length,a=e.d.length,t=0,n=r<a?r:a;t<n;++t)if(i.d[t]!==e.d[t])return i.d[t]>e.d[t]^i.s<0?1:-1;return r===a?0:r>a^i.s<0?1:-1;};U.decimalPlaces=U.dp=function(){var e=this,t=e.d.length-1,n=(t-e.e)*Ee;if(t=e.d[t],t)for(;t%10==0;t/=10)n--;return n<0?0:n;};U.dividedBy=U.div=function(e){return dt(this,new this.constructor(e));};U.dividedToIntegerBy=U.idiv=function(e){var t=this,n=t.constructor;return we(dt(t,new n(e),0,1),n.precision);};U.equals=U.eq=function(e){return!this.cmp(e);};U.exponent=function(){return Pe(this);};U.greaterThan=U.gt=function(e){return this.cmp(e)>0;};U.greaterThanOrEqualTo=U.gte=function(e){return this.cmp(e)>=0;};U.isInteger=U.isint=function(){return this.e>this.d.length-2;};U.isNegative=U.isneg=function(){return this.s<0;};U.isPositive=U.ispos=function(){return this.s>0;};U.isZero=function(){return this.s===0;};U.lessThan=U.lt=function(e){return this.cmp(e)<0;};U.lessThanOrEqualTo=U.lte=function(e){return this.cmp(e)<1;};U.logarithm=U.log=function(e){var t,n=this,r=n.constructor,a=r.precision,i=a+5;if(e===void 0)e=new r(10);else if(e=new r(e),e.s<1||e.eq(He))throw Error(Ge+"NaN");if(n.s<1)throw Error(Ge+(n.s?"NaN":"-Infinity"));return n.eq(He)?new r(0):(xe=!1,t=dt(fn(n,i),fn(e,i),i),xe=!0,we(t,a));};U.minus=U.sub=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?oo(t,e):ao(t,(e.s=-e.s,e));};U.modulo=U.mod=function(e){var t,n=this,r=n.constructor,a=r.precision;if(e=new r(e),!e.s)throw Error(Ge+"NaN");return n.s?(xe=!1,t=dt(n,e,0,1).times(e),xe=!0,n.minus(t)):we(new r(n),a);};U.naturalExponential=U.exp=function(){return io(this);};U.naturalLogarithm=U.ln=function(){return fn(this);};U.negated=U.neg=function(){var e=new this.constructor(this);return e.s=-e.s||0,e;};U.plus=U.add=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?ao(t,e):oo(t,(e.s=-e.s,e));};U.precision=U.sd=function(e){var t,n,r,a=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(kt+e);if(t=Pe(a)+1,r=a.d.length-1,n=r*Ee+1,r=a.d[r],r){for(;r%10==0;r/=10)n--;for(r=a.d[0];r>=10;r/=10)n++;}return e&&t>n?t:n;};U.squareRoot=U.sqrt=function(){var e,t,n,r,a,i,o,s=this,l=s.constructor;if(s.s<1){if(!s.s)return new l(0);throw Error(Ge+"NaN");}for(e=Pe(s),xe=!1,a=Math.sqrt(+s),a==0||a==1/0?(t=tt(s.d),(t.length+e)%2==0&&(t+="0"),a=Math.sqrt(t),e=Qt((e+1)/2)-(e<0||e%2),a==1/0?t="5e"+e:(t=a.toExponential(),t=t.slice(0,t.indexOf("e")+1)+e),r=new l(t)):r=new l(a.toString()),n=l.precision,a=o=n+3;;)if(i=r,r=i.plus(dt(s,i,o+2)).times(0.5),tt(i.d).slice(0,o)===(t=tt(r.d)).slice(0,o)){if(t=t.slice(o-3,o+1),a==o&&t=="4999"){if(we(i,n+1,0),i.times(i).eq(s)){r=i;break;}}else if(t!="9999")break;o+=4;}return xe=!0,we(r,n);};U.times=U.mul=function(e){var t,n,r,a,i,o,s,l,u,d=this,c=d.constructor,p=d.d,y=(e=new c(e)).d;if(!d.s||!e.s)return new c(0);for(e.s*=d.s,n=d.e+e.e,l=p.length,u=y.length,l<u&&(i=p,p=y,y=i,o=l,l=u,u=o),i=[],o=l+u,r=o;r--;)i.push(0);for(r=u;--r>=0;){for(t=0,a=l+r;a>r;)s=i[a]+y[r]*p[a-r-1]+t,i[a--]=s%Re|0,t=s/Re|0;i[a]=(i[a]+t)%Re|0;}for(;!i[--o];)i.pop();return t?++n:i.shift(),e.d=i,e.e=n,xe?we(e,c.precision):e;};U.toDecimalPlaces=U.todp=function(e,t){var n=this,r=n.constructor;return n=new r(n),e===void 0?n:(rt(e,0,Yt),t===void 0?t=r.rounding:rt(t,0,8),we(n,e+Pe(n)+1,t));};U.toExponential=function(e,t){var n,r=this,a=r.constructor;return e===void 0?n=Lt(r,!0):(rt(e,0,Yt),t===void 0?t=a.rounding:rt(t,0,8),r=we(new a(r),e+1,t),n=Lt(r,!0,e+1)),n;};U.toFixed=function(e,t){var n,r,a=this,i=a.constructor;return e===void 0?Lt(a):(rt(e,0,Yt),t===void 0?t=i.rounding:rt(t,0,8),r=we(new i(a),e+Pe(a)+1,t),n=Lt(r.abs(),!1,e+Pe(r)+1),a.isneg()&&!a.isZero()?"-"+n:n);};U.toInteger=U.toint=function(){var e=this,t=e.constructor;return we(new t(e),Pe(e)+1,t.rounding);};U.toNumber=function(){return+this;};U.toPower=U.pow=function(e){var t,n,r,a,i,o,s=this,l=s.constructor,u=12,d=+(e=new l(e));if(!e.s)return new l(He);if(s=new l(s),!s.s){if(e.s<1)throw Error(Ge+"Infinity");return s;}if(s.eq(He))return s;if(r=l.precision,e.eq(He))return we(s,r);if(t=e.e,n=e.d.length-1,o=t>=n,i=s.s,o){if((n=d<0?-d:d)<=ro){for(a=new l(He),t=Math.ceil(r/Ee+4),xe=!1;n%2&&(a=a.times(s),ti(a.d,t)),n=Qt(n/2),n!==0;)s=s.times(s),ti(s.d,t);return xe=!0,e.s<0?new l(He).div(a):we(a,r);}}else if(i<0)throw Error(Ge+"NaN");return i=i<0&&e.d[Math.max(t,n)]&1?-1:1,s.s=1,xe=!1,a=e.times(fn(s,r+u)),xe=!0,a=io(a),a.s=i,a;};U.toPrecision=function(e,t){var n,r,a=this,i=a.constructor;return e===void 0?(n=Pe(a),r=Lt(a,n<=i.toExpNeg||n>=i.toExpPos)):(rt(e,1,Yt),t===void 0?t=i.rounding:rt(t,0,8),a=we(new i(a),e,t),n=Pe(a),r=Lt(a,e<=n||n<=i.toExpNeg,e)),r;};U.toSignificantDigits=U.tosd=function(e,t){var n=this,r=n.constructor;return e===void 0?(e=r.precision,t=r.rounding):(rt(e,1,Yt),t===void 0?t=r.rounding:rt(t,0,8)),we(new r(n),e,t);};U.toString=U.valueOf=U.val=U.toJSON=U[Symbol.for("nodejs.util.inspect.custom")]=function(){var e=this,t=Pe(e),n=e.constructor;return Lt(e,t<=n.toExpNeg||t>=n.toExpPos);};function ao(e,t){var n,r,a,i,o,s,l,u,d=e.constructor,c=d.precision;if(!e.s||!t.s)return t.s||(t=new d(e)),xe?we(t,c):t;if(l=e.d,u=t.d,o=e.e,a=t.e,l=l.slice(),i=o-a,i){for(i<0?(r=l,i=-i,s=u.length):(r=u,a=o,s=l.length),o=Math.ceil(c/Ee),s=o>s?o+1:s+1,i>s&&(i=s,r.length=1),r.reverse();i--;)r.push(0);r.reverse();}for(s=l.length,i=u.length,s-i<0&&(i=s,r=u,u=l,l=r),n=0;i;)n=(l[--i]=l[i]+u[i]+n)/Re|0,l[i]%=Re;for(n&&(l.unshift(n),++a),s=l.length;l[--s]==0;)l.pop();return t.d=l,t.e=a,xe?we(t,c):t;}function rt(e,t,n){if(e!==~~e||e<t||e>n)throw Error(kt+e);}function tt(e){var t,n,r,a=e.length-1,i="",o=e[0];if(a>0){for(i+=o,t=1;t<a;t++)r=e[t]+"",n=Ee-r.length,n&&(i+=ht(n)),i+=r;o=e[t],r=o+"",n=Ee-r.length,n&&(i+=ht(n));}else if(o===0)return"0";for(;o%10===0;)o/=10;return i+o;}var dt=/* @__PURE__ */function(){function e(r,a){var i,o=0,s=r.length;for(r=r.slice();s--;)i=r[s]*a+o,r[s]=i%Re|0,o=i/Re|0;return o&&r.unshift(o),r;}function t(r,a,i,o){var s,l;if(i!=o)l=i>o?1:-1;else for(s=l=0;s<i;s++)if(r[s]!=a[s]){l=r[s]>a[s]?1:-1;break;}return l;}function n(r,a,i){for(var o=0;i--;)r[i]-=o,o=r[i]<a[i]?1:0,r[i]=o*Re+r[i]-a[i];for(;!r[0]&&r.length>1;)r.shift();}return function(r,a,i,o){var s,l,u,d,c,p,y,b,m,h,g,v,w,E,A,I,T,L,x=r.constructor,k=r.s==a.s?1:-1,_=r.d,D=a.d;if(!r.s)return new x(r);if(!a.s)throw Error(Ge+"Division by zero");for(l=r.e-a.e,T=D.length,A=_.length,y=new x(k),b=y.d=[],u=0;D[u]==(_[u]||0);)++u;if(D[u]>(_[u]||0)&&--l,i==null?v=i=x.precision:o?v=i+(Pe(r)-Pe(a))+1:v=i,v<0)return new x(0);if(v=v/Ee+2|0,u=0,T==1)for(d=0,D=D[0],v++;(u<A||d)&&v--;u++)w=d*Re+(_[u]||0),b[u]=w/D|0,d=w%D|0;else{for(d=Re/(D[0]+1)|0,d>1&&(D=e(D,d),_=e(_,d),T=D.length,A=_.length),E=T,m=_.slice(0,T),h=m.length;h<T;)m[h++]=0;L=D.slice(),L.unshift(0),I=D[0],D[1]>=Re/2&&++I;do d=0,s=t(D,m,T,h),s<0?(g=m[0],T!=h&&(g=g*Re+(m[1]||0)),d=g/I|0,d>1?(d>=Re&&(d=Re-1),c=e(D,d),p=c.length,h=m.length,s=t(c,m,p,h),s==1&&(d--,n(c,T<p?L:D,p))):(d==0&&(s=d=1),c=D.slice()),p=c.length,p<h&&c.unshift(0),n(m,c,h),s==-1&&(h=m.length,s=t(D,m,T,h),s<1&&(d++,n(m,T<h?L:D,h))),h=m.length):s===0&&(d++,m=[0]),b[u++]=d,s&&m[0]?m[h++]=_[E]||0:(m=[_[E]],h=1);while((E++<A||m[0]!==void 0)&&v--);}return b[0]||b.shift(),y.e=l,we(y,o?i+Pe(y)+1:i);};}();function io(e,t){var n,r,a,i,o,s,l=0,u=0,d=e.constructor,c=d.precision;if(Pe(e)>16)throw Error(la+Pe(e));if(!e.s)return new d(He);for(xe=!1,s=c,o=new d(0.03125);e.abs().gte(0.1);)e=e.times(o),u+=5;for(r=Math.log(Tt(2,u))/Math.LN10*2+5|0,s+=r,n=a=i=new d(He),d.precision=s;;){if(a=we(a.times(e),s),n=n.times(++l),o=i.plus(dt(a,n,s)),tt(o.d).slice(0,s)===tt(i.d).slice(0,s)){for(;u--;)i=we(i.times(i),s);return d.precision=c,t==null?(xe=!0,we(i,c)):i;}i=o;}}function Pe(e){for(var t=e.e*Ee,n=e.d[0];n>=10;n/=10)t++;return t;}function pr(e,t,n){if(t>e.LN10.sd())throw xe=!0,n&&(e.precision=n),Error(Ge+"LN10 precision limit exceeded");return we(new e(e.LN10),t);}function ht(e){for(var t="";e--;)t+="0";return t;}function fn(e,t){var n,r,a,i,o,s,l,u,d,c=1,p=10,y=e,b=y.d,m=y.constructor,h=m.precision;if(y.s<1)throw Error(Ge+(y.s?"NaN":"-Infinity"));if(y.eq(He))return new m(0);if(t==null?(xe=!1,u=h):u=t,y.eq(10))return t==null&&(xe=!0),pr(m,u);if(u+=p,m.precision=u,n=tt(b),r=n.charAt(0),i=Pe(y),Math.abs(i)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)y=y.times(e),n=tt(y.d),r=n.charAt(0),c++;i=Pe(y),r>1?(y=new m("0."+n),i++):y=new m(r+"."+n.slice(1));}else return l=pr(m,u+2,h).times(i+""),y=fn(new m(r+"."+n.slice(1)),u-p).plus(l),m.precision=h,t==null?(xe=!0,we(y,h)):y;for(s=o=y=dt(y.minus(He),y.plus(He),u),d=we(y.times(y),u),a=3;;){if(o=we(o.times(d),u),l=s.plus(dt(o,new m(a),u)),tt(l.d).slice(0,u)===tt(s.d).slice(0,u))return s=s.times(2),i!==0&&(s=s.plus(pr(m,u+2,h).times(i+""))),s=dt(s,new m(c),u),m.precision=h,t==null?(xe=!0,we(s,h)):s;s=l,a+=2;}}function ei(e,t){var n,r,a;for((n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;)++r;for(a=t.length;t.charCodeAt(a-1)===48;)--a;if(t=t.slice(r,a),t){if(a-=r,n=n-r-1,e.e=Qt(n/Ee),e.d=[],r=(n+1)%Ee,n<0&&(r+=Ee),r<a){for(r&&e.d.push(+t.slice(0,r)),a-=Ee;r<a;)e.d.push(+t.slice(r,r+=Ee));t=t.slice(r),r=Ee-t.length;}else r-=a;for(;r--;)t+="0";if(e.d.push(+t),xe&&(e.e>Vn||e.e<-Vn))throw Error(la+n);}else e.s=0,e.e=0,e.d=[0];return e;}function we(e,t,n){var r,a,i,o,s,l,u,d,c=e.d;for(o=1,i=c[0];i>=10;i/=10)o++;if(r=t-o,r<0)r+=Ee,a=t,u=c[d=0];else{if(d=Math.ceil((r+1)/Ee),i=c.length,d>=i)return e;for(u=i=c[d],o=1;i>=10;i/=10)o++;r%=Ee,a=r-Ee+o;}if(n!==void 0&&(i=Tt(10,o-a-1),s=u/i%10|0,l=t<0||c[d+1]!==void 0||u%i,l=n<4?(s||l)&&(n==0||n==(e.s<0?3:2)):s>5||s==5&&(n==4||l||n==6&&// Check whether the digit to the left of the rounding digit is odd.
|
|
32
|
+
(r>0?a>0?u/Tt(10,o-a):0:c[d-1])%10&1||n==(e.s<0?8:7))),t<1||!c[0])return l?(i=Pe(e),c.length=1,t=t-i-1,c[0]=Tt(10,(Ee-t%Ee)%Ee),e.e=Qt(-t/Ee)||0):(c.length=1,c[0]=e.e=e.s=0),e;if(r==0?(c.length=d,i=1,d--):(c.length=d+1,i=Tt(10,Ee-r),c[d]=a>0?(u/Tt(10,o-a)%Tt(10,a)|0)*i:0),l)for(;;)if(d==0){(c[0]+=i)==Re&&(c[0]=1,++e.e);break;}else{if(c[d]+=i,c[d]!=Re)break;c[d--]=0,i=1;}for(r=c.length;c[--r]===0;)c.pop();if(xe&&(e.e>Vn||e.e<-Vn))throw Error(la+Pe(e));return e;}function oo(e,t){var n,r,a,i,o,s,l,u,d,c,p=e.constructor,y=p.precision;if(!e.s||!t.s)return t.s?t.s=-t.s:t=new p(e),xe?we(t,y):t;if(l=e.d,c=t.d,r=t.e,u=e.e,l=l.slice(),o=u-r,o){for(d=o<0,d?(n=l,o=-o,s=c.length):(n=c,r=u,s=l.length),a=Math.max(Math.ceil(y/Ee),s)+2,o>a&&(o=a,n.length=1),n.reverse(),a=o;a--;)n.push(0);n.reverse();}else{for(a=l.length,s=c.length,d=a<s,d&&(s=a),a=0;a<s;a++)if(l[a]!=c[a]){d=l[a]<c[a];break;}o=0;}for(d&&(n=l,l=c,c=n,t.s=-t.s),s=l.length,a=c.length-s;a>0;--a)l[s++]=0;for(a=c.length;a>o;){if(l[--a]<c[a]){for(i=a;i&&l[--i]===0;)l[i]=Re-1;--l[i],l[a]+=Re;}l[a]-=c[a];}for(;l[--s]===0;)l.pop();for(;l[0]===0;l.shift())--r;return l[0]?(t.d=l,t.e=r,xe?we(t,y):t):new p(0);}function Lt(e,t,n){var r,a=Pe(e),i=tt(e.d),o=i.length;return t?(n&&(r=n-o)>0?i=i.charAt(0)+"."+i.slice(1)+ht(r):o>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+ht(-a-1)+i,n&&(r=n-o)>0&&(i+=ht(r))):a>=o?(i+=ht(a+1-o),n&&(r=n-a-1)>0&&(i=i+"."+ht(r))):((r=a+1)<o&&(i=i.slice(0,r)+"."+i.slice(r)),n&&(r=n-o)>0&&(a+1===o&&(i+="."),i+=ht(r))),e.s<0?"-"+i:i;}function ti(e,t){if(e.length>t)return e.length=t,!0;}function so(e){var t,n,r;function a(i){var o=this;if(!(o instanceof a))return new a(i);if(o.constructor=a,i instanceof a){o.s=i.s,o.e=i.e,o.d=(i=i.d)?i.slice():i;return;}if(typeof i=="number"){if(i*0!==0)throw Error(kt+i);if(i>0)o.s=1;else if(i<0)i=-i,o.s=-1;else{o.s=0,o.e=0,o.d=[0];return;}if(i===~~i&&i<1e7){o.e=0,o.d=[i];return;}return ei(o,i.toString());}else if(typeof i!="string")throw Error(kt+i);if(i.charCodeAt(0)===45?(i=i.slice(1),o.s=-1):o.s=1,js.test(i))ei(o,i);else throw Error(kt+i);}if(a.prototype=U,a.ROUND_UP=0,a.ROUND_DOWN=1,a.ROUND_CEIL=2,a.ROUND_FLOOR=3,a.ROUND_HALF_UP=4,a.ROUND_HALF_DOWN=5,a.ROUND_HALF_EVEN=6,a.ROUND_HALF_CEIL=7,a.ROUND_HALF_FLOOR=8,a.clone=so,a.config=a.set=Ks,e===void 0&&(e={}),e)for(r=["precision","rounding","toExpNeg","toExpPos","LN10"],t=0;t<r.length;)e.hasOwnProperty(n=r[t++])||(e[n]=this[n]);return a.config(e),a;}function Ks(e){if(!e||typeof e!="object")throw Error(Ge+"Object expected");var t,n,r,a=["precision",1,Yt,"rounding",0,8,"toExpNeg",-1/0,0,"toExpPos",0,1/0];for(t=0;t<a.length;t+=3)if((r=e[n=a[t]])!==void 0)if(Qt(r)===r&&r>=a[t+1]&&r<=a[t+2])this[n]=r;else throw Error(kt+n+": "+r);if((r=e[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(kt+n+": "+r);return this;}var ua=so(Gs);He=new ua(1);const Ys=ua;var Qs=20,Xs=1,Un=1e6,ni=1e6,Zs=-7,Js=21,ca="[big.js] ",An=ca+"Invalid ",da=An+"decimal places",ri=An+"rounding mode",lo=ca+"Division by zero",Ie={},Pt=void 0,el=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function uo(){function e(t){var n=this;if(!(n instanceof e))return t===Pt?uo():new e(t);t instanceof e?(n.s=t.s,n.e=t.e,n.c=t.c.slice()):tl(n,t),n.constructor=e;}return e.prototype=Ie,e.DP=Qs,e.RM=Xs,e.NE=Zs,e.PE=Js,e.version="5.2.2",e;}function tl(e,t){var n,r,a;if(t===0&&1/t<0)t="-0";else if(!el.test(t+=""))throw Error(An+"number");for(e.s=t.charAt(0)=="-"?(t=t.slice(1),-1):1,(n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),a=t.length,r=0;r<a&&t.charAt(r)=="0";)++r;if(r==a)e.c=[e.e=0];else{for(;a>0&&t.charAt(--a)=="0";);for(e.e=n-r-1,e.c=[],n=0;r<=a;)e.c[n++]=+t.charAt(r++);}return e;}function tr(e,t,n,r){var a=e.c,i=e.e+t+1;if(i<a.length){if(n===1)r=a[i]>=5;else if(n===2)r=a[i]>5||a[i]==5&&(r||i<0||a[i+1]!==Pt||a[i-1]&1);else if(n===3)r=r||!!a[0];else if(r=!1,n!==0)throw Error(ri);if(i<1)a.length=1,r?(e.e=-t,a[0]=1):a[0]=e.e=0;else{if(a.length=i--,r)for(;++a[i]>9;)a[i]=0,i--||(++e.e,a.unshift(1));for(i=a.length;!a[--i];)a.pop();}}else if(n<0||n>3||n!==~~n)throw Error(ri);return e;}function Tn(e,t,n,r){var a,i,o=e.constructor,s=!e.c[0];if(n!==Pt){if(n!==~~n||n<(t==3)||n>Un)throw Error(t==3?An+"precision":da);for(e=new o(e),n=r-e.e,e.c.length>++r&&tr(e,n,o.RM),t==2&&(r=e.e+n+1);e.c.length<r;)e.c.push(0);}if(a=e.e,i=e.c.join(""),n=i.length,t!=2&&(t==1||t==3&&r<=a||a<=o.NE||a>=o.PE))i=i.charAt(0)+(n>1?"."+i.slice(1):"")+(a<0?"e":"e+")+a;else if(a<0){for(;++a;)i="0"+i;i="0."+i;}else if(a>0){if(++a>n)for(a-=n;a--;)i+="0";else a<n&&(i=i.slice(0,a)+"."+i.slice(a));}else n>1&&(i=i.charAt(0)+"."+i.slice(1));return e.s<0&&(!s||t==4)?"-"+i:i;}Ie.abs=function(){var e=new this.constructor(this);return e.s=1,e;};Ie.cmp=function(e){var t,n=this,r=n.c,a=(e=new n.constructor(e)).c,i=n.s,o=e.s,s=n.e,l=e.e;if(!r[0]||!a[0])return r[0]?i:a[0]?-o:0;if(i!=o)return i;if(t=i<0,s!=l)return s>l^t?1:-1;for(o=(s=r.length)<(l=a.length)?s:l,i=-1;++i<o;)if(r[i]!=a[i])return r[i]>a[i]^t?1:-1;return s==l?0:s>l^t?1:-1;};Ie.div=function(e){var t=this,n=t.constructor,r=t.c,a=(e=new n(e)).c,i=t.s==e.s?1:-1,o=n.DP;if(o!==~~o||o<0||o>Un)throw Error(da);if(!a[0])throw Error(lo);if(!r[0])return new n(i*0);var s,l,u,d,c,p=a.slice(),y=s=a.length,b=r.length,m=r.slice(0,s),h=m.length,g=e,v=g.c=[],w=0,E=o+(g.e=t.e-e.e)+1;for(g.s=i,i=E<0?0:E,p.unshift(0);h++<s;)m.push(0);do{for(u=0;u<10;u++){if(s!=(h=m.length))d=s>h?1:-1;else for(c=-1,d=0;++c<s;)if(a[c]!=m[c]){d=a[c]>m[c]?1:-1;break;}if(d<0){for(l=h==s?a:p;h;){if(m[--h]<l[h]){for(c=h;c&&!m[--c];)m[c]=9;--m[c],m[h]+=10;}m[h]-=l[h];}for(;!m[0];)m.shift();}else break;}v[w++]=d?u:++u,m[0]&&d?m[h]=r[y]||0:m=[r[y]];}while((y++<b||m[0]!==Pt)&&i--);return!v[0]&&w!=1&&(v.shift(),g.e--),w>E&&tr(g,o,n.RM,m[0]!==Pt),g;};Ie.eq=function(e){return!this.cmp(e);};Ie.gt=function(e){return this.cmp(e)>0;};Ie.gte=function(e){return this.cmp(e)>-1;};Ie.lt=function(e){return this.cmp(e)<0;};Ie.lte=function(e){return this.cmp(e)<1;};Ie.minus=Ie.sub=function(e){var t,n,r,a,i=this,o=i.constructor,s=i.s,l=(e=new o(e)).s;if(s!=l)return e.s=-l,i.plus(e);var u=i.c.slice(),d=i.e,c=e.c,p=e.e;if(!u[0]||!c[0])return c[0]?(e.s=-l,e):new o(u[0]?i:0);if(s=d-p){for((a=s<0)?(s=-s,r=u):(p=d,r=c),r.reverse(),l=s;l--;)r.push(0);r.reverse();}else for(n=((a=u.length<c.length)?u:c).length,s=l=0;l<n;l++)if(u[l]!=c[l]){a=u[l]<c[l];break;}if(a&&(r=u,u=c,c=r,e.s=-e.s),(l=(n=c.length)-(t=u.length))>0)for(;l--;)u[t++]=0;for(l=t;n>s;){if(u[--n]<c[n]){for(t=n;t&&!u[--t];)u[t]=9;--u[t],u[n]+=10;}u[n]-=c[n];}for(;u[--l]===0;)u.pop();for(;u[0]===0;)u.shift(),--p;return u[0]||(e.s=1,u=[p=0]),e.c=u,e.e=p,e;};Ie.mod=function(e){var t,n=this,r=n.constructor,a=n.s,i=(e=new r(e)).s;if(!e.c[0])throw Error(lo);return n.s=e.s=1,t=e.cmp(n)==1,n.s=a,e.s=i,t?new r(n):(a=r.DP,i=r.RM,r.DP=r.RM=0,n=n.div(e),r.DP=a,r.RM=i,this.minus(n.times(e)));};Ie.plus=Ie.add=function(e){var t,n=this,r=n.constructor,a=n.s,i=(e=new r(e)).s;if(a!=i)return e.s=-i,n.minus(e);var o=n.e,s=n.c,l=e.e,u=e.c;if(!s[0]||!u[0])return u[0]?e:new r(s[0]?n:a*0);if(s=s.slice(),a=o-l){for(a>0?(l=o,t=u):(a=-a,t=s),t.reverse();a--;)t.push(0);t.reverse();}for(s.length-u.length<0&&(t=u,u=s,s=t),a=u.length,i=0;a;s[a]%=10)i=(s[--a]=s[a]+u[a]+i)/10|0;for(i&&(s.unshift(i),++l),a=s.length;s[--a]===0;)s.pop();return e.c=s,e.e=l,e;};Ie.pow=function(e){var t=this,n=new t.constructor(1),r=n,a=e<0;if(e!==~~e||e<-ni||e>ni)throw Error(An+"exponent");for(a&&(e=-e);e&1&&(r=r.times(t)),e>>=1,!!e;)t=t.times(t);return a?n.div(r):r;};Ie.round=function(e,t){var n=this.constructor;if(e===Pt)e=0;else if(e!==~~e||e<-Un||e>Un)throw Error(da);return tr(new n(this),e,t===Pt?n.RM:t);};Ie.sqrt=function(){var e,t,n,r=this,a=r.constructor,i=r.s,o=r.e,s=new a(0.5);if(!r.c[0])return new a(r);if(i<0)throw Error(ca+"No square root");i=Math.sqrt(r+""),i===0||i===1/0?(t=r.c.join(""),t.length+o&1||(t+="0"),i=Math.sqrt(t),o=((o+1)/2|0)-(o<0||o&1),e=new a((i==1/0?"1e":(i=i.toExponential()).slice(0,i.indexOf("e")+1))+o)):e=new a(i),o=e.e+(a.DP+=4);do n=e,e=s.times(n.plus(r.div(n)));while(n.c.slice(0,o).join("")!==e.c.slice(0,o).join(""));return tr(e,a.DP-=4,a.RM);};Ie.times=Ie.mul=function(e){var t,n=this,r=n.constructor,a=n.c,i=(e=new r(e)).c,o=a.length,s=i.length,l=n.e,u=e.e;if(e.s=n.s==e.s?1:-1,!a[0]||!i[0])return new r(e.s*0);for(e.e=l+u,o<s&&(t=a,a=i,i=t,u=o,o=s,s=u),t=new Array(u=o+s);u--;)t[u]=0;for(l=s;l--;){for(s=0,u=o+l;u>l;)s=t[u]+i[l]*a[u-l-1]+s,t[u--]=s%10,s=s/10|0;t[u]=(t[u]+s)%10;}for(s?++e.e:t.shift(),l=t.length;!t[--l];)t.pop();return e.c=t,e;};Ie.toExponential=function(e){return Tn(this,1,e,e);};Ie.toFixed=function(e){return Tn(this,2,e,this.e+e);};Ie.toPrecision=function(e){return Tn(this,3,e,e-1);};Ie.toString=function(){return Tn(this);};Ie.valueOf=Ie.toJSON=function(){return Tn(this,4);};uo();function nl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e;}var fr={exports:{}},ai;function rl(){return ai||(ai=1,function(e){function t(n){return n.prototype.toFormat=function(a,i,o){if(!this.e&&this.e!==0)return this.toString();var s,l,u,d,c,p,y,b,m,h,g,v,w,E,A,I=this.format||{},T=this.constructor.format||{};if(a!=c?typeof a=="object"?(o=a,a=c):i!=c?typeof i=="object"?(o=i,i=c):typeof o!="object"&&(o={}):o={}:o={},s=this.toFixed(a,i).split("."),b=s[0],m=s[1],y=this.s<0?b.slice(1):b,p=y.length,h=o.decimalSeparator,h==c&&(h=I.decimalSeparator,h==c&&(h=T.decimalSeparator,h==c&&(h="."))),g=o.groupSeparator,g==c&&(g=I.groupSeparator,g==c&&(g=T.groupSeparator)),g&&(v=o.groupSize,v==c&&(v=I.groupSize,v==c&&(v=T.groupSize,v==c&&(v=0))),w=o.secondaryGroupSize,w==c&&(w=I.secondaryGroupSize,w==c&&(w=T.secondaryGroupSize,w==c&&(w=0))),w?(l=+w,u=+v,p-=u):(l=+v,u=+w),l>0&&p>0)){for(d=p%l||l,b=y.substr(0,d);d<p;d+=l)b+=g+y.substr(d,l);u>0&&(b+=g+y.slice(d)),this.s<0&&(b="-"+b);}return m?(E=o.fractionGroupSeparator,E==c&&(E=I.fractionGroupSeparator,E==c&&(E=T.fractionGroupSeparator)),E&&(A=o.fractionGroupSize,A==c&&(A=I.fractionGroupSize,A==c&&(A=T.fractionGroupSize,A==c&&(A=0))),A=+A,A&&(m=m.replace(new RegExp("\\d{"+A+"}\\B","g"),"$&"+E))),b+h+m):b;},n.format={decimalSeparator:".",groupSeparator:",",groupSize:3,secondaryGroupSize:0,fractionGroupSeparator:"",fractionGroupSize:0},n;}e.exports&&(e.exports=t);}(fr)),fr.exports;}var al=rl();const il=/* @__PURE__ */nl(al);function ii(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r;}function ol(e,t){var n=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=sl(e))||t){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]};};}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
33
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`);}function sl(e,t){if(e){if(typeof e=="string")return ii(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ii(e,t):void 0;}}var ot,lt;(function(e){e[e.LOWEST=100]="LOWEST",e[e.LOW_200=200]="LOW_200",e[e.LOW_300=300]="LOW_300",e[e.LOW_400=400]="LOW_400",e[e.LOW=500]="LOW",e[e.MEDIUM=3e3]="MEDIUM",e[e.HIGH=1e4]="HIGH";})(lt||(lt={}));ot={},ot[lt.LOWEST]=1,ot[lt.LOW_200]=4,ot[lt.LOW_300]=6,ot[lt.LOW_400]=8,ot[lt.LOW]=10,ot[lt.MEDIUM]=60,ot[lt.HIGH]=200;var gt=/* @__PURE__ */f.BigInt(0),mn=/* @__PURE__ */f.BigInt(1),Ut=/* @__PURE__ */f.exponentiate(/* @__PURE__ */f.BigInt(2),/* @__PURE__ */f.BigInt(96)),At=/* @__PURE__ */function(){function e(){}return e.mulDivRoundingUp=function(n,r,a){var i=f.multiply(n,r),o=f.divide(i,a);return f.notEqual(f.remainder(i,a),gt)&&(o=f.add(o,mn)),o;},e;}(),ll=/* @__PURE__ */f.subtract(/* @__PURE__ */f.exponentiate(/* @__PURE__ */f.BigInt(2),/* @__PURE__ */f.BigInt(160)),mn);function oi(e,t){var n=f.multiply(e,t);return f.bitwiseAnd(n,er);}function ul(e,t){var n=f.add(e,t);return f.bitwiseAnd(n,er);}var co=/* @__PURE__ */function(){function e(){}return e.getAmount0Delta=function(n,r,a,i){if(f.greaterThan(n,r)){var o=[r,n];n=o[0],r=o[1];}var s=f.leftShift(a,f.BigInt(96)),l=f.subtract(r,n);return i?At.mulDivRoundingUp(At.mulDivRoundingUp(s,l,r),mn,n):f.divide(f.divide(f.multiply(s,l),r),n);},e.getAmount1Delta=function(n,r,a,i){if(f.greaterThan(n,r)){var o=[r,n];n=o[0],r=o[1];}return i?At.mulDivRoundingUp(a,f.subtract(r,n),Ut):f.divide(f.multiply(a,f.subtract(r,n)),Ut);},e.getNextSqrtPriceFromInput=function(n,r,a,i){return f.greaterThan(n,gt)||Qe(),f.greaterThan(r,gt)||Qe(),i?this.getNextSqrtPriceFromAmount0RoundingUp(n,r,a,!0):this.getNextSqrtPriceFromAmount1RoundingDown(n,r,a,!0);},e.getNextSqrtPriceFromOutput=function(n,r,a,i){return f.greaterThan(n,gt)||Qe(),f.greaterThan(r,gt)||Qe(),i?this.getNextSqrtPriceFromAmount1RoundingDown(n,r,a,!1):this.getNextSqrtPriceFromAmount0RoundingUp(n,r,a,!1);},e.getNextSqrtPriceFromAmount0RoundingUp=function(n,r,a,i){if(f.equal(a,gt))return n;var o=f.leftShift(r,f.BigInt(96));if(i){var s=oi(a,n);if(f.equal(f.divide(s,a),n)){var l=ul(o,s);if(f.greaterThanOrEqual(l,o))return At.mulDivRoundingUp(o,n,l);}return At.mulDivRoundingUp(o,mn,f.add(f.divide(o,n),a));}else{var u=oi(a,n);f.equal(f.divide(u,a),n)||Qe(),f.greaterThan(o,u)||Qe();var d=f.subtract(o,u);return At.mulDivRoundingUp(o,n,d);}},e.getNextSqrtPriceFromAmount1RoundingDown=function(n,r,a,i){if(i){var o=f.lessThanOrEqual(a,ll)?f.divide(f.leftShift(a,f.BigInt(96)),r):f.divide(f.multiply(a,Ut),r);return f.add(n,o);}else{var s=At.mulDivRoundingUp(a,Ut,r);return f.greaterThan(n,s)||Qe(),f.subtract(n,s);}},e;}(),cl=/* @__PURE__ */f.BigInt(2),dl=/* @__PURE__ */[128,64,32,16,8,4,2,1].map(function(e){return[e,f.exponentiate(cl,f.BigInt(e))];});function pl(e){f.greaterThan(e,gt)||Qe(),f.lessThanOrEqual(e,er)||Qe();for(var t=0,n=ol(dl),r;!(r=n()).done;){var a=r.value,i=a[0],o=a[1];f.greaterThanOrEqual(e,o)&&(e=f.signedRightShift(e,f.BigInt(i)),t+=i);}return t;}function Ce(e,t){return f.signedRightShift(f.multiply(e,f.BigInt(t)),f.BigInt(128));}var mr=/* @__PURE__ */f.exponentiate(/* @__PURE__ */f.BigInt(2),/* @__PURE__ */f.BigInt(32)),wt=/* @__PURE__ */function(){function e(){}return e.getSqrtRatioAtTick=function(n){n>=e.MIN_TICK&&n<=e.MAX_TICK&&Number.isInteger(n)||Qe();var r=n<0?n*-1:n,a=(r&1)!==0?f.BigInt("0xfffcb933bd6fad37aa2d162d1a594001"):f.BigInt("0x100000000000000000000000000000000");return(r&2)!==0&&(a=Ce(a,"0xfff97272373d413259a46990580e213a")),(r&4)!==0&&(a=Ce(a,"0xfff2e50f5f656932ef12357cf3c7fdcc")),(r&8)!==0&&(a=Ce(a,"0xffe5caca7e10e4e61c3624eaa0941cd0")),(r&16)!==0&&(a=Ce(a,"0xffcb9843d60f6159c9db58835c926644")),(r&32)!==0&&(a=Ce(a,"0xff973b41fa98c081472e6896dfb254c0")),(r&64)!==0&&(a=Ce(a,"0xff2ea16466c96a3843ec78b326b52861")),(r&128)!==0&&(a=Ce(a,"0xfe5dee046a99a2a811c461f1969c3053")),(r&256)!==0&&(a=Ce(a,"0xfcbe86c7900a88aedcffc83b479aa3a4")),(r&512)!==0&&(a=Ce(a,"0xf987a7253ac413176f2b074cf7815e54")),(r&1024)!==0&&(a=Ce(a,"0xf3392b0822b70005940c7a398e4b70f3")),(r&2048)!==0&&(a=Ce(a,"0xe7159475a2c29b7443b29c7fa6e889d9")),(r&4096)!==0&&(a=Ce(a,"0xd097f3bdfd2022b8845ad8f792aa5825")),(r&8192)!==0&&(a=Ce(a,"0xa9f746462d870fdf8a65dc1f90e061e5")),(r&16384)!==0&&(a=Ce(a,"0x70d869a156d2a1b890bb3df62baf32f7")),(r&32768)!==0&&(a=Ce(a,"0x31be135f97d08fd981231505542fcfa6")),(r&65536)!==0&&(a=Ce(a,"0x9aa508b5b7a84e1c677de54f3e99bc9")),(r&131072)!==0&&(a=Ce(a,"0x5d6af8dedb81196699c329225ee604")),(r&262144)!==0&&(a=Ce(a,"0x2216e584f5fa1ea926041bedfe98")),(r&524288)!==0&&(a=Ce(a,"0x48a170391f7dc42444e8fa2")),n>0&&(a=f.divide(er,a)),f.greaterThan(f.remainder(a,mr),gt)?f.add(f.divide(a,mr),mn):f.divide(a,mr);},e.getTickAtSqrtRatio=function(n){f.greaterThanOrEqual(n,e.MIN_SQRT_RATIO)&&f.lessThan(n,e.MAX_SQRT_RATIO)||Qe();var r=f.leftShift(n,f.BigInt(32)),a=pl(r),i;f.greaterThanOrEqual(f.BigInt(a),f.BigInt(128))?i=f.signedRightShift(r,f.BigInt(a-127)):i=f.leftShift(r,f.BigInt(127-a));for(var o=f.leftShift(f.subtract(f.BigInt(a),f.BigInt(128)),f.BigInt(64)),s=0;s<14;s++){i=f.signedRightShift(f.multiply(i,i),f.BigInt(127));var l=f.signedRightShift(i,f.BigInt(128));o=f.bitwiseOr(o,f.leftShift(l,f.BigInt(63-s))),i=f.signedRightShift(i,l);}var u=f.multiply(o,f.BigInt("255738958999603826347141")),d=f.toNumber(f.signedRightShift(f.subtract(u,f.BigInt("3402992956809132418596140100660247210")),f.BigInt(128))),c=f.toNumber(f.signedRightShift(f.add(u,f.BigInt("291339464771989622907027621153398088495")),f.BigInt(128)));return d===c?d:f.lessThanOrEqual(e.getSqrtRatioAtTick(c),n)?c:d;},e;}();wt.MIN_TICK=-887272;wt.MAX_TICK=-wt.MIN_TICK;wt.MIN_SQRT_RATIO=/* @__PURE__ */f.BigInt("4295128739");wt.MAX_SQRT_RATIO=/* @__PURE__ */f.BigInt("1461446703485210103287273052203988822378723970342");function fl(e,t,n){if(f.greaterThan(e,t)){var r=[t,e];e=r[0],t=r[1];}var a=f.multiply(f.multiply(f.BigInt(n),e),t),i=f.multiply(Ut,f.subtract(t,e));return f.divide(a,i);}function si(e,t,n){if(f.greaterThan(e,t)){var r=[t,e];e=r[0],t=r[1];}return f.divide(f.multiply(f.BigInt(n),Ut),f.subtract(t,e));}function ml(e,t,n,r,a,i){if(f.greaterThan(t,n)){var o=[n,t];t=o[0],n=o[1];}var s=fl;if(f.lessThanOrEqual(e,t))return s(t,n,r);if(f.lessThan(e,n)){var l=s(e,n,r),u=si(t,e,a);return f.lessThan(l,u)?l:u;}else return si(t,n,a);}function yn(){return yn=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r]);}return e;},yn.apply(this,arguments);}var M;(function(e){e[e.MAINNET=1]="MAINNET",e[e.GOERLI=5]="GOERLI",e[e.SEPOLIA=11155111]="SEPOLIA",e[e.OPTIMISM=10]="OPTIMISM",e[e.OPTIMISM_GOERLI=420]="OPTIMISM_GOERLI",e[e.OPTIMISM_SEPOLIA=11155420]="OPTIMISM_SEPOLIA",e[e.ARBITRUM_ONE=42161]="ARBITRUM_ONE",e[e.ARBITRUM_GOERLI=421613]="ARBITRUM_GOERLI",e[e.ARBITRUM_SEPOLIA=421614]="ARBITRUM_SEPOLIA",e[e.POLYGON=137]="POLYGON",e[e.POLYGON_MUMBAI=80001]="POLYGON_MUMBAI",e[e.CELO=42220]="CELO",e[e.CELO_ALFAJORES=44787]="CELO_ALFAJORES",e[e.GNOSIS=100]="GNOSIS",e[e.MOONBEAM=1284]="MOONBEAM",e[e.BNB=56]="BNB",e[e.AVALANCHE=43114]="AVALANCHE",e[e.BASE_GOERLI=84531]="BASE_GOERLI",e[e.BASE=8453]="BASE",e[e.ZORA=7777777]="ZORA",e[e.ZORA_SEPOLIA=999999999]="ZORA_SEPOLIA",e[e.ROOTSTOCK=30]="ROOTSTOCK",e[e.BLAST=81457]="BLAST",e[e.ZKSYNC=324]="ZKSYNC",e[e.WORLDCHAIN=480]="WORLDCHAIN",e[e.UNICHAIN_SEPOLIA=1301]="UNICHAIN_SEPOLIA",e[e.UNICHAIN=130]="UNICHAIN",e[e.MONAD_TESTNET=41454]="MONAD_TESTNET";})(M||(M={}));M.MAINNET,M.OPTIMISM,M.OPTIMISM_GOERLI,M.OPTIMISM_SEPOLIA,M.ARBITRUM_ONE,M.ARBITRUM_GOERLI,M.ARBITRUM_SEPOLIA,M.POLYGON,M.POLYGON_MUMBAI,M.GOERLI,M.SEPOLIA,M.CELO_ALFAJORES,M.CELO,M.BNB,M.AVALANCHE,M.BASE,M.BASE_GOERLI,M.ZORA,M.ZORA_SEPOLIA,M.ROOTSTOCK,M.BLAST,M.ZKSYNC,M.WORLDCHAIN,M.UNICHAIN_SEPOLIA,M.UNICHAIN;var li;(function(e){e.ETHER="ETH",e.MATIC="MATIC",e.CELO="CELO",e.GNOSIS="XDAI",e.MOONBEAM="GLMR",e.BNB="BNB",e.AVAX="AVAX",e.ROOTSTOCK="RBTC";})(li||(li={}));var qe,Fe,ve,yr,hr,br,gr,vr,yl=[M.MAINNET,M.GOERLI,M.SEPOLIA];function hl(e,t){return t===void 0&&(t=[]),yl.concat(t).reduce(function(n,r){return n[r]=e,n;},{});}M.OPTIMISM,M.ARBITRUM_ONE,M.POLYGON,M.POLYGON_MUMBAI,M.SEPOLIA;qe={},qe[M.MAINNET]="0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f",qe[M.GOERLI]="0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f",qe[M.SEPOLIA]="0xF62c03E08ada871A0bEb309762E260a7a6a880E6",qe[M.OPTIMISM]="0x0c3c1c532F1e39EdF36BE9Fe0bE1410313E074Bf",qe[M.ARBITRUM_ONE]="0xf1D7CC64Fb4452F05c498126312eBE29f30Fbcf9",qe[M.AVALANCHE]="0x9e5A52f57b3038F1B8EeE45F28b3C1967e22799C",qe[M.BASE]="0x8909dc15e40173ff4699343b6eb8132c65e18ec6",qe[M.BNB]="0x8909Dc15e40173Ff4699343b6eB8132c65e18eC6",qe[M.POLYGON]="0x9e5A52f57b3038F1B8EeE45F28b3C1967e22799C",qe[M.CELO]="0x79a530c8e2fA8748B7B40dd3629C0520c2cCf03f",qe[M.BLAST]="0x5C346464d33F90bABaf70dB6388507CC889C1070",qe[M.WORLDCHAIN]="0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f",qe[M.UNICHAIN_SEPOLIA]="0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f",qe[M.UNICHAIN]="0x1f98400000000000000000000000000000000002";Fe={},Fe[M.MAINNET]="0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D",Fe[M.GOERLI]="0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D",Fe[M.SEPOLIA]="0xeE567Fe1712Faf6149d80dA1E6934E354124CfE3",Fe[M.ARBITRUM_ONE]="0x4752ba5dbc23f44d87826276bf6fd6b1c372ad24",Fe[M.OPTIMISM]="0x4a7b5da61326a6379179b40d00f57e5bbdc962c2",Fe[M.BASE]="0x4752ba5dbc23f44d87826276bf6fd6b1c372ad24",Fe[M.AVALANCHE]="0x4752ba5dbc23f44d87826276bf6fd6b1c372ad24",Fe[M.BNB]="0x4752ba5dbc23f44d87826276bf6fd6b1c372ad24",Fe[M.POLYGON]="0xedf6066a2b290c185783862c7f4776a2c8077ad1",Fe[M.BLAST]="0xBB66Eb1c5e875933D44DAe661dbD80e5D9B03035",Fe[M.WORLDCHAIN]="0x541aB7c31A119441eF3575F6973277DE0eF460bd",Fe[M.UNICHAIN_SEPOLIA]="0x920b806E40A00E02E7D2b94fFc89860fDaEd3640",Fe[M.UNICHAIN]="0x284f11109359a7e1306c3e447ef14d38400063ff";var En={v3CoreFactoryAddress:"0x1F98431c8aD98523631AE4a59f267346ea31F984",multicallAddress:"0x1F98415757620B543A52E61c46B32eB19261F984",quoterAddress:"0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6",v3MigratorAddress:"0xA5644E29708357803b5A882D272c41cC0dF92B34",nonfungiblePositionManagerAddress:"0xC36442b4a4522E871399CD717aBDD847Ab11FE88"},bl=/* @__PURE__ */yn({},En,{mixedRouteQuoterV1Address:"0x84E44095eeBfEC7793Cd7d5b57B7e401D7f1cA2E"}),gl=/* @__PURE__ */yn({},En,{mixedRouteQuoterV1Address:"0xBa60b6e6fF25488308789E6e0A65D838be34194e"}),vl=En,wl=/* @__PURE__ */yn({},En,{multicallAddress:"0xadF885960B47eA2CD9B55E6DAc6B42b7Cb2806dB",tickLensAddress:"0xbfd8137f7d1516D3ea5cA83523914859ec47F573"}),ui=En,ci={v3CoreFactoryAddress:"0xAfE208a311B21f13EF87E33A90049fC17A7acDEc",multicallAddress:"0x633987602DE5C4F337e3DbF265303A1080324204",quoterAddress:"0x82825d0554fA07f7FC52Ab63c961F330fdEFa8E8",v3MigratorAddress:"0x3cFd4d48EDfDCC53D3f173F596f621064614C582",nonfungiblePositionManagerAddress:"0x3d79EdAaBC0EaB6F08ED885C05Fc0B014290D95A",tickLensAddress:"0x5f115D9113F88e0a0Db1b5033D90D4a9690AcD3D"},Al={v3CoreFactoryAddress:"0xdB1d10011AD0Ff90774D0C6Bb92e5C5c8b4461F7",multicallAddress:"0x963Df249eD09c358A4819E39d9Cd5736c3087184",quoterAddress:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",v3MigratorAddress:"0x32681814957e0C13117ddc0c2aba232b5c9e760f",nonfungiblePositionManagerAddress:"0x7b8A01B39D58278b5DE7e48c8449c9f4F5170613",tickLensAddress:"0xD9270014D396281579760619CCf4c3af0501A47C",swapRouter02Address:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2"},Tl={v3CoreFactoryAddress:"0xB656dA17129e7EB733A557f4EBc57B76CFbB5d10",multicallAddress:"0x07F2D8a2a02251B62af965f22fC4744A5f96BCCd",quoterAddress:"0x9569CbA925c8ca2248772A9A4976A516743A246F",v3MigratorAddress:"0xf6c55fBe84B1C8c3283533c53F51bC32F5C7Aba8",nonfungiblePositionManagerAddress:"0x39Ca85Af2F383190cBf7d7c41ED9202D27426EF6",tickLensAddress:"0xe6140Bd164b63E8BfCfc40D5dF952f83e171758e"},El={v3CoreFactoryAddress:"0x8CE191193D15ea94e11d327b4c7ad8bbE520f6aF",multicallAddress:"0x80e4e06841bb76AA9735E0448cB8d003C0EF009a",quoterAddress:"0x0FBEa6cf957d95ee9313490050F6A0DA68039404",v3MigratorAddress:"0xE7EcbAAaA54D007A00dbb6c1d2f150066D69dA07",nonfungiblePositionManagerAddress:"0xdA75cEf1C93078e8b736FCA5D5a30adb97C8957d",tickLensAddress:"0xCb7f54747F58F8944973cea5b8f4ac2209BadDC5",swapRouter02Address:"0x94cC0AaC535CCDB3C01d6787D6413C739ae12bc4"},Il={v3CoreFactoryAddress:"0x4893376342d5D7b3e31d4184c08b265e5aB2A3f6",multicallAddress:"0x8260CB40247290317a4c062F3542622367F206Ee",quoterAddress:"0x1dd92b83591781D0C6d98d07391eea4b9a6008FA",v3MigratorAddress:"0xA815919D2584Ac3F76ea9CB62E6Fd40a43BCe0C3",nonfungiblePositionManagerAddress:"0x622e4726a167799826d1E1D150b076A7725f5D81",tickLensAddress:"0xb52429333da969a0C79a60930a4Bf0020E5D1DE8"},xl={v3CoreFactoryAddress:"0x248AB79Bbb9bC29bB72f7Cd42F17e054Fc40188e",multicallAddress:"0x2B718b475e385eD29F56775a66aAB1F5cC6B2A0A",quoterAddress:"0x2779a0CC1c3e0E44D2542EC3e79e3864Ae93Ef0B",v3MigratorAddress:"0x398f43ef2c67B941147157DA1c5a868E906E043D",nonfungiblePositionManagerAddress:"0x6b2937Bde17889EDCf8fbD8dE31C3C2a70Bc4d65",tickLensAddress:"0x0fd18587734e5C2dcE2dccDcC7DD1EC89ba557d9",swapRouter02Address:"0x101F443B4d1b059569D643917553c771E1b9663E",v4PoolManagerAddress:"0xFB3e0C6F74eB1a21CC1Da29aeC80D2Dfe6C9a317",v4PositionManagerAddress:"0xAc631556d3d4019C95769033B5E719dD77124BAc",v4StateView:"0x9d467fa9062b6e9b1a46e26007ad82db116c67cb",v4QuoterAddress:"0x7de51022d70a725b508085468052e25e22b5c4c9"},kl={v3CoreFactoryAddress:"0x0227628f3F023bb0B980b67D528571c95c6DaC1c",multicallAddress:"0xD7F33bCdb21b359c8ee6F0251d30E94832baAd07",quoterAddress:"0xEd1f6473345F45b75F8179591dd5bA1888cf2FB3",v3MigratorAddress:"0x729004182cF005CEC8Bd85df140094b6aCbe8b15",nonfungiblePositionManagerAddress:"0x1238536071E1c677A632429e3655c799b22cDA52",tickLensAddress:"0xd7f33bcdb21b359c8ee6f0251d30e94832baad07",swapRouter02Address:"0x3bFA4769FB09eefC5a80d6E87c3B9C650f7Ae48E",// TODO: update mixedRouteQuoterV2Address once v4 on sepolia redeployed
|
|
34
|
+
mixedRouteQuoterV2Address:"0x4745f77b56a0e2294426e3936dc4fab68d9543cd",// TODO: update all below once v4 on sepolia redeployed
|
|
35
|
+
v4PoolManagerAddress:"0xE03A1074c86CFeDd5C142C4F04F1a1536e203543",v4PositionManagerAddress:"0x429ba70129df741B2Ca2a85BC3A2a3328e5c09b4",v4StateView:"0xe1dd9c3fa50edb962e442f60dfbc432e24537e4c",v4QuoterAddress:"0x61b3f2011a92d183c7dbadbda940a7555ccf9227"},Dl={v3CoreFactoryAddress:"0x740b1c1de25031C31FF4fC9A62f554A55cdC1baD",multicallAddress:"0x0139141Cd4Ee88dF3Cdb65881D411bAE271Ef0C2",quoterAddress:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",v3MigratorAddress:"0x44f5f1f5E452ea8d29C890E8F6e893fC0f1f0f97",nonfungiblePositionManagerAddress:"0x655C406EBFa14EE2006250925e54ec43AD184f8B",tickLensAddress:"0xEB9fFC8bf81b4fFd11fb6A63a6B0f098c6e21950",swapRouter02Address:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE"},Nl={v3CoreFactoryAddress:"0x33128a8fC17869897dcE68Ed026d694621f6FDfD",multicallAddress:"0x091e99cb1C49331a94dD62755D168E941AbD0693",quoterAddress:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",v3MigratorAddress:"0x23cF10b1ee3AdfCA73B0eF17C07F7577e7ACd2d7",nonfungiblePositionManagerAddress:"0x03a520b32C04BF3bEEf7BEb72E919cf822Ed34f1",tickLensAddress:"0x0CdeE061c75D43c82520eD998C23ac2991c9ac6d",swapRouter02Address:"0x2626664c2603336E57B271c5C0b26F421741e481",mixedRouteQuoterV1Address:"0xe544efae946f0008ae9a8d64493efa7886b73776"},Ll={v3CoreFactoryAddress:"0x9323c1d6D800ed51Bd7C6B216cfBec678B7d0BC2",multicallAddress:"0xB206027a9E0E13F05eBEFa5D2402Bab3eA716439",quoterAddress:"0xedf539058e28E5937dAef3f69cEd0b25fbE66Ae9",v3MigratorAddress:"0x3efe5d02a04b7351D671Db7008ec6eBA9AD9e3aE",nonfungiblePositionManagerAddress:"0x3c61369ef0D1D2AFa70d8feC2F31C5D6Ce134F30",tickLensAddress:"0x1acB873Ee909D0c98adB18e4474943249F931b92",swapRouter02Address:"0x8357227D4eDc78991Db6FDB9bD6ADE250536dE1d"},Pl={v3CoreFactoryAddress:"0x7145F8aeef1f6510E92164038E1B6F8cB2c42Cbb",multicallAddress:"0xA51c76bEE6746cB487a7e9312E43e2b8f4A37C15",quoterAddress:"0x11867e1b3348F3ce4FcC170BC5af3d23E07E64Df",v3MigratorAddress:"0x048352d8dCF13686982C799da63fA6426a9D0b60",nonfungiblePositionManagerAddress:"0xbC91e8DfA3fF18De43853372A3d7dfe585137D78",tickLensAddress:"0x209AAda09D74Ad3B8D0E92910Eaf85D2357e3044",swapRouter02Address:"0x7De04c96BE5159c3b5CeffC82aa176dc81281557"},_l={v3CoreFactoryAddress:"0x4324A677D74764f46f33ED447964252441aA8Db6",multicallAddress:"0xA1E7e3A69671C4494EC59Dbd442de930a93F911A",quoterAddress:"0xC195976fEF0985886E37036E2DF62bF371E12Df0",v3MigratorAddress:"0x65ef259b31bf1d977c37e9434658694267674897",nonfungiblePositionManagerAddress:"0xB8458EaAe43292e3c1F7994EFd016bd653d23c20",tickLensAddress:"0x23C0F71877a1Fc4e20A78018f9831365c85f3064"},Cl={v3CoreFactoryAddress:"0xaF37EC98A00FD63689CF3060BF3B6784E00caD82",multicallAddress:"0x996a9858cDfa45Ad68E47c9A30a7201E29c6a386",quoterAddress:"0xb51727c996C68E60F598A923a5006853cd2fEB31",v3MigratorAddress:"0x16678977CA4ec3DAD5efc7b15780295FE5f56162",nonfungiblePositionManagerAddress:"0x9d9386c042F194B460Ec424a1e57ACDE25f5C4b1",tickLensAddress:"0x55B9dF5bF68ADe972191a91980459f48ecA16afC",swapRouter02Address:"0x0B14ff67f0014046b4b99057Aec4509640b3947A"},Ml={v3CoreFactoryAddress:"0x792edAdE80af5fC680d96a2eD80A44247D2Cf6Fd",multicallAddress:"0xdC7f370de7631cE9e2c2e1DCDA6B3B5744Cf4705",quoterAddress:"0x6Cdcd65e03c1CEc3730AeeCd45bc140D57A25C77",v3MigratorAddress:"0x15CA7043CD84C5D21Ae76Ba0A1A967d42c40ecE0",nonfungiblePositionManagerAddress:"0xB218e4f7cF0533d4696fDfC419A0023D33345F28",tickLensAddress:"0x2E95185bCdD928a3e984B7e2D6560Ab1b17d7274",swapRouter02Address:"0x549FEB8c9bd4c12Ad2AB27022dA12492aC452B66"},Rl={v3CoreFactoryAddress:"0x8FdA5a7a8dCA67BBcDd10F02Fa0649A937215422",multicallAddress:"0x0c68a7C72f074d1c45C16d41fa74eEbC6D16a65C",quoterAddress:"0x8Cb537fc92E26d8EBBb760E632c95484b6Ea3e28",v3MigratorAddress:"0x611841b24E43C4ACfd290B427a3D6cf1A59dac8E",nonfungiblePositionManagerAddress:"0x0616e5762c1E7Dc3723c50663dF10a162D690a86",tickLensAddress:"0xe10FF11b809f8EE07b056B452c3B2caa7FE24f89",swapRouter02Address:"0x99c56385daBCE3E81d8499d0b8d0257aBC07E8A3"},Sl={v3CoreFactoryAddress:"0x7a5028BDa40e7B173C278C5342087826455ea25a",multicallAddress:"0x0a22c04215c97E3F532F4eF30e0aD9458792dAB9",quoterAddress:"0x10158D43e6cc414deE1Bd1eB0EfC6a5cBCfF244c",v3MigratorAddress:"0x9EBDdCBa71C9027E1eB45135672a30bcFEec9de3",nonfungiblePositionManagerAddress:"0xec12a9F9a09f50550686363766Cc153D03c27b5e",tickLensAddress:"0xE61df0CaC9d85876aCE5E3037005D80943570623",swapRouter02Address:"0x091AD9e2e6e5eD44c1c66dB50e49A601F9f36cF6"},Ol={v3CoreFactoryAddress:"0x1F98431c8aD98523631AE4a59f267346ea31F984",multicallAddress:"0x9D0F15f2cf58655fDDcD1EE6129C547fDaeD01b1",quoterAddress:"0x6Dd37329A1A225a6Fca658265D460423DCafBF89",v3MigratorAddress:"0xb5FA244C9d6D04B2FBac84418b3c4910ED1Ae5f2",nonfungiblePositionManagerAddress:"0xB7F724d6dDDFd008eFf5cc2834edDE5F9eF0d075",tickLensAddress:"0x5f739c790a48E97eec0efb81bab5D152c0A0ecA0",swapRouter02Address:"0xd1AAE39293221B77B0C71fBD6dCb7Ea29Bb5B166",v4PoolManagerAddress:"0x00b036b58a818b1bc34d502d3fe730db729e62ac",v4PositionManagerAddress:"0xf969aee60879c54baaed9f3ed26147db216fd664",v4StateView:"0xc199f1072a74d4e905aba1a84d9a45e2546b6222",v4QuoterAddress:"0x56dcd40a3f2d466f48e7f48bdbe5cc9b92ae4472"},ql={v3CoreFactoryAddress:"0x1f98400000000000000000000000000000000003",multicallAddress:"0xb7610f9b733e7d45184be3a1bc966960ccc54f0b",quoterAddress:"0x565ac8c7863d9bb16d07e809ff49fe5cd467634c",v3MigratorAddress:"0xb9d0c246f306b1aaf02ae6ba112d5ef25e5b60dc",nonfungiblePositionManagerAddress:"0x943e6e07a7e8e791dafc44083e54041d743c46e9",tickLensAddress:"0xd5d76fa166ab8d8ad4c9f61aaa81457b66cbe443",swapRouter02Address:"0x73855d06de49d0fe4a9c42636ba96c62da12ff9c"};ve={},ve[M.MAINNET]=bl,ve[M.OPTIMISM]=vl,ve[M.ARBITRUM_ONE]=wl,ve[M.POLYGON]=ui,ve[M.POLYGON_MUMBAI]=ui,ve[M.GOERLI]=gl,ve[M.CELO]=ci,ve[M.CELO_ALFAJORES]=ci,ve[M.BNB]=Al,ve[M.OPTIMISM_GOERLI]=Tl,ve[M.OPTIMISM_SEPOLIA]=El,ve[M.ARBITRUM_GOERLI]=Il,ve[M.ARBITRUM_SEPOLIA]=xl,ve[M.SEPOLIA]=kl,ve[M.AVALANCHE]=Dl,ve[M.BASE]=Nl,ve[M.BASE_GOERLI]=Ll,ve[M.ZORA]=Pl,ve[M.ZORA_SEPOLIA]=_l,ve[M.ROOTSTOCK]=Cl,ve[M.BLAST]=Ml,ve[M.ZKSYNC]=Rl,ve[M.WORLDCHAIN]=Sl,ve[M.UNICHAIN_SEPOLIA]=Ol,ve[M.UNICHAIN]=ql;yr={},yr[M.MAINNET]="0xC4e172459f1E7939D522503B81AFAaC1014CE6F6";hr={},hr[M.MAINNET]="0x408ED6354d4973f66138C91495F2f2FCbd8724C3";br={},br[M.MAINNET]="0x090D4613473dEE047c3f2706764f49E0821D256e";gr={},gr[M.MAINNET]="0xeca4B0bDBf7c55E9b7925919d03CbF8Dc82537E8";vr={},vr[M.MAINNET]="0x65770b5283117639760beA3F867b69b3697a91dd";var di;(function(e){e[e.EXACT_INPUT=0]="EXACT_INPUT",e[e.EXACT_OUTPUT=1]="EXACT_OUTPUT";})(di||(di={}));var vt;(function(e){e[e.ROUND_DOWN=0]="ROUND_DOWN",e[e.ROUND_HALF_UP=1]="ROUND_HALF_UP",e[e.ROUND_UP=2]="ROUND_UP";})(vt||(vt={}));var rn,an,wr=/* @__PURE__ */il(Ys);rn={},rn[vt.ROUND_DOWN]=wr.ROUND_DOWN,rn[vt.ROUND_HALF_UP]=wr.ROUND_HALF_UP,rn[vt.ROUND_UP]=wr.ROUND_UP;an={},an[vt.ROUND_DOWN]=0,an[vt.ROUND_HALF_UP]=1,an[vt.ROUND_UP]=3;class Dt extends Error{constructor(n,r){const a=`${Dt.extractMessage(n)}: ${JSON.stringify({response:n,request:r})}`;super(a);oe(this,"response");oe(this,"request");Object.setPrototypeOf(this,Dt.prototype),this.response=n,this.request=r,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Dt);}static extractMessage(n){var r,a;return((a=(r=n.errors)==null?void 0:r[0])==null?void 0:a.message)??`GraphQL Error (Code: ${String(n.status)})`;}}const pi=e=>e.toUpperCase(),Ar=e=>typeof e=="function"?e():e,po=(e,t)=>e.map((n,r)=>[n,t[r]]),Bt=e=>{let t={};return e instanceof Headers?t=Bl(e):Array.isArray(e)?e.forEach(([n,r])=>{n&&r!==void 0&&(t[n]=r);}):e&&(t=e),t;},Bl=e=>{const t={};return e.forEach((n,r)=>{t[r]=n;}),t;},Fl=e=>{try{const t=e();return Vl(t)?t.catch(n=>fi(n)):t;}catch(t){return fi(t);}},fi=e=>e instanceof Error?e:new Error(String(e)),Vl=e=>typeof e=="object"&&e!==null&&"then"in e&&typeof e.then=="function"&&"catch"in e&&typeof e.catch=="function"&&"finally"in e&&typeof e.finally=="function",pa=e=>{throw new Error(`Unhandled case: ${String(e)}`);},Rn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ul=(e,t)=>e.documents?e:{documents:e,requestHeaders:t,signal:void 0},Wl=(e,t,n)=>e.query?e:{query:e,variables:t,requestHeaders:n,signal:void 0};function Sn(e,t){if(!!!e)throw new Error(t);}function $l(e){return typeof e=="object"&&e!==null;}function Hl(e,t){if(!!!e)throw new Error("Unexpected invariant triggered.");}const zl=/\r\n|[\n\r]/g;function Br(e,t){let n=0,r=1;for(const a of e.body.matchAll(zl)){if(typeof a.index=="number"||Hl(!1),a.index>=t)break;n=a.index+a[0].length,r+=1;}return{line:r,column:t+1-n};}function Gl(e){return fo(e.source,Br(e.source,e.start));}function fo(e,t){const n=e.locationOffset.column-1,r="".padStart(n)+e.body,a=t.line-1,i=e.locationOffset.line-1,o=t.line+i,s=t.line===1?n:0,l=t.column+s,u=`${e.name}:${o}:${l}
|
|
36
|
+
`,d=r.split(/\r\n|[\n\r]/g),c=d[a];if(c.length>120){const p=Math.floor(l/80),y=l%80,b=[];for(let m=0;m<c.length;m+=80)b.push(c.slice(m,m+80));return u+mi([[`${o} |`,b[0]],...b.slice(1,p+1).map(m=>["|",m]),["|","^".padStart(y)],["|",b[p+1]]]);}return u+mi([// Lines specified like this: ["prefix", "string"],
|
|
37
|
+
[`${o-1} |`,d[a-1]],[`${o} |`,c],["|","^".padStart(l)],[`${o+1} |`,d[a+1]]]);}function mi(e){const t=e.filter(([r,a])=>a!==void 0),n=Math.max(...t.map(([r])=>r.length));return t.map(([r,a])=>r.padStart(n)+(a?" "+a:"")).join(`
|
|
38
|
+
`);}function jl(e){const t=e[0];return t==null||"kind"in t||"length"in t?{nodes:t,source:e[1],positions:e[2],path:e[3],originalError:e[4],extensions:e[5]}:t;}class fa extends Error{/**
|
|
39
|
+
* An array of `{ line, column }` locations within the source GraphQL document
|
|
40
|
+
* which correspond to this error.
|
|
41
|
+
*
|
|
42
|
+
* Errors during validation often contain multiple locations, for example to
|
|
43
|
+
* point out two things with the same name. Errors during execution include a
|
|
44
|
+
* single location, the field which produced the error.
|
|
45
|
+
*
|
|
46
|
+
* Enumerable, and appears in the result of JSON.stringify().
|
|
47
|
+
*//**
|
|
48
|
+
* An array describing the JSON-path into the execution response which
|
|
49
|
+
* corresponds to this error. Only included for errors during execution.
|
|
50
|
+
*
|
|
51
|
+
* Enumerable, and appears in the result of JSON.stringify().
|
|
52
|
+
*//** An array of GraphQL AST Nodes corresponding to this error. *//**
|
|
53
|
+
* The source GraphQL document for the first location of this error.
|
|
54
|
+
*
|
|
55
|
+
* Note that if this Error represents more than one node, the source may not
|
|
56
|
+
* represent nodes after the first node.
|
|
57
|
+
*//**
|
|
58
|
+
* An array of character offsets within the source GraphQL document
|
|
59
|
+
* which correspond to this error.
|
|
60
|
+
*//** Original error that caused this GraphQLError, if one exists. *//** Extension fields to add to the formatted error. *//**
|
|
61
|
+
* Creates a GraphQLError instance.
|
|
62
|
+
* @param message - Human-readable error message.
|
|
63
|
+
* @param options - Error metadata such as source locations, response path, original error, and extensions.
|
|
64
|
+
* This positional-arguments constructor overload is deprecated. Use the
|
|
65
|
+
* `GraphQLError(message, options)` overload instead.
|
|
66
|
+
* @example
|
|
67
|
+
* ```ts
|
|
68
|
+
* // Create an error from AST nodes and response metadata.
|
|
69
|
+
* import { parse } from 'graphql/language';
|
|
70
|
+
* import { GraphQLError } from 'graphql/error';
|
|
71
|
+
*
|
|
72
|
+
* const document = parse('{ greeting }');
|
|
73
|
+
* const fieldNode = document.definitions[0].selectionSet.selections[0];
|
|
74
|
+
* const error = new GraphQLError('Cannot query this field.', {
|
|
75
|
+
* nodes: fieldNode,
|
|
76
|
+
* path: ['greeting'],
|
|
77
|
+
* extensions: { code: 'FORBIDDEN' },
|
|
78
|
+
* });
|
|
79
|
+
*
|
|
80
|
+
* error.message; // => 'Cannot query this field.'
|
|
81
|
+
* error.locations; // => [{ line: 1, column: 3 }]
|
|
82
|
+
* error.path; // => ['greeting']
|
|
83
|
+
* error.extensions; // => { code: 'FORBIDDEN' }
|
|
84
|
+
* ```
|
|
85
|
+
* @example
|
|
86
|
+
* ```ts
|
|
87
|
+
* // This variant derives locations from source positions and preserves the original error.
|
|
88
|
+
* import { Source } from 'graphql/language';
|
|
89
|
+
* import { GraphQLError } from 'graphql/error';
|
|
90
|
+
*
|
|
91
|
+
* const source = new Source('{ greeting }');
|
|
92
|
+
* const originalError = new Error('Database unavailable.');
|
|
93
|
+
* const error = new GraphQLError('Resolver failed.', {
|
|
94
|
+
* source,
|
|
95
|
+
* positions: [2],
|
|
96
|
+
* path: ['greeting'],
|
|
97
|
+
* originalError,
|
|
98
|
+
* });
|
|
99
|
+
*
|
|
100
|
+
* error.locations; // => [{ line: 1, column: 3 }]
|
|
101
|
+
* error.path; // => ['greeting']
|
|
102
|
+
* error.originalError; // => originalError
|
|
103
|
+
* ```
|
|
104
|
+
*//**
|
|
105
|
+
* Creates a GraphQLError instance using the legacy positional constructor.
|
|
106
|
+
* This deprecated overload will be removed in v17. Prefer the
|
|
107
|
+
* `GraphQLErrorOptions` object overload, which keeps optional error metadata
|
|
108
|
+
* in a single options bag.
|
|
109
|
+
* @param message - Human-readable error message.
|
|
110
|
+
* @param nodes - AST node or nodes associated with this error.
|
|
111
|
+
* @param source - Source document used to derive error locations.
|
|
112
|
+
* @param positions - Character offsets in the source document associated with
|
|
113
|
+
* this error.
|
|
114
|
+
* @param path - Response path where this error occurred during execution.
|
|
115
|
+
* @param originalError - Original error that caused this GraphQLError, if one
|
|
116
|
+
* exists.
|
|
117
|
+
* @param extensions - Extension fields to include in the formatted error.
|
|
118
|
+
* @example
|
|
119
|
+
* ```ts
|
|
120
|
+
* import { Source } from 'graphql/language';
|
|
121
|
+
* import { GraphQLError } from 'graphql/error';
|
|
122
|
+
*
|
|
123
|
+
* const source = new Source('{ greeting }');
|
|
124
|
+
* const originalError = new Error('Database unavailable.');
|
|
125
|
+
* const error = new GraphQLError(
|
|
126
|
+
* 'Resolver failed.',
|
|
127
|
+
* undefined,
|
|
128
|
+
* source,
|
|
129
|
+
* [2],
|
|
130
|
+
* ['greeting'],
|
|
131
|
+
* originalError,
|
|
132
|
+
* { code: 'INTERNAL' },
|
|
133
|
+
* );
|
|
134
|
+
*
|
|
135
|
+
* error.locations; // => [{ line: 1, column: 3 }]
|
|
136
|
+
* error.path; // => ['greeting']
|
|
137
|
+
* error.originalError; // => originalError
|
|
138
|
+
* error.extensions; // => { code: 'INTERNAL' }
|
|
139
|
+
* ```
|
|
140
|
+
* @deprecated Please use the `GraphQLErrorOptions` constructor overload instead.
|
|
141
|
+
*/constructor(t,...n){var r,a,i;const{nodes:o,source:s,positions:l,path:u,originalError:d,extensions:c}=jl(n);super(t),this.name="GraphQLError",this.path=u??void 0,this.originalError=d??void 0,this.nodes=yi(Array.isArray(o)?o:o?[o]:void 0);const p=yi((r=this.nodes)===null||r===void 0?void 0:r.map(b=>b.loc).filter(b=>b!=null));this.source=s??(p==null||(a=p[0])===null||a===void 0?void 0:a.source),this.positions=l??(p==null?void 0:p.map(b=>b.start)),this.locations=l&&s?l.map(b=>Br(s,b)):p==null?void 0:p.map(b=>Br(b.source,b.start));const y=$l(d==null?void 0:d.extensions)?d==null?void 0:d.extensions:void 0;this.extensions=(i=c??y)!==null&&i!==void 0?i:/* @__PURE__ */Object.create(null),Object.defineProperties(this,{message:{writable:!0,enumerable:!0},name:{enumerable:!1},nodes:{enumerable:!1},source:{enumerable:!1},positions:{enumerable:!1},originalError:{enumerable:!1}}),d!=null&&d.stack?Object.defineProperty(this,"stack",{value:d.stack,writable:!0,configurable:!0}):Error.captureStackTrace?Error.captureStackTrace(this,fa):Object.defineProperty(this,"stack",{value:Error().stack,writable:!0,configurable:!0});}/**
|
|
142
|
+
* Returns the value used by `Object.prototype.toString`.
|
|
143
|
+
* @returns The built-in string tag for this object.
|
|
144
|
+
*/get[Symbol.toStringTag](){return"GraphQLError";}/**
|
|
145
|
+
* Returns this error as a human-readable message with source locations.
|
|
146
|
+
* @returns The formatted error string.
|
|
147
|
+
* @example
|
|
148
|
+
* ```ts
|
|
149
|
+
* import { Source } from 'graphql/language';
|
|
150
|
+
* import { GraphQLError } from 'graphql/error';
|
|
151
|
+
*
|
|
152
|
+
* const error = new GraphQLError('Cannot query field "name".', {
|
|
153
|
+
* source: new Source('{ name }'),
|
|
154
|
+
* positions: [2],
|
|
155
|
+
* });
|
|
156
|
+
*
|
|
157
|
+
* error.toString(); // => 'Cannot query field "name".\n\nGraphQL request:1:3\n1 | { name }\n | ^'
|
|
158
|
+
* ```
|
|
159
|
+
*/toString(){let t=this.message;if(this.nodes)for(const n of this.nodes)n.loc&&(t+=`
|
|
160
|
+
|
|
161
|
+
`+Gl(n.loc));else if(this.source&&this.locations)for(const n of this.locations)t+=`
|
|
162
|
+
|
|
163
|
+
`+fo(this.source,n);return t;}/**
|
|
164
|
+
* Returns the JSON representation used when this object is serialized.
|
|
165
|
+
* @returns The JSON-serializable representation.
|
|
166
|
+
* @example
|
|
167
|
+
* ```ts
|
|
168
|
+
* import { GraphQLError } from 'graphql/error';
|
|
169
|
+
*
|
|
170
|
+
* const error = new GraphQLError('Resolver failed.', {
|
|
171
|
+
* path: ['viewer', 'name'],
|
|
172
|
+
* extensions: { code: 'INTERNAL' },
|
|
173
|
+
* });
|
|
174
|
+
*
|
|
175
|
+
* error.toJSON(); // => { message: 'Resolver failed.', path: ['viewer', 'name'], extensions: { code: 'INTERNAL' } }
|
|
176
|
+
* ```
|
|
177
|
+
*/toJSON(){const t={message:this.message};return this.locations!=null&&(t.locations=this.locations),this.path!=null&&(t.path=this.path),this.extensions!=null&&Object.keys(this.extensions).length>0&&(t.extensions=this.extensions),t;}}function yi(e){return e===void 0||e.length===0?void 0:e;}function Me(e,t,n){return new fa(`Syntax Error: ${n}`,{source:e,positions:[t]});}class Kl{/** The character offset at which this Node begins. *//** The character offset at which this Node ends. *//** The Token at which this Node begins. *//** The Token at which this Node ends. *//** The Source document the AST represents. *//**
|
|
178
|
+
* Creates a Location instance.
|
|
179
|
+
* @param startToken - The start token.
|
|
180
|
+
* @param endToken - The end token.
|
|
181
|
+
* @param source - Source document used to derive error locations.
|
|
182
|
+
* @example
|
|
183
|
+
* ```ts
|
|
184
|
+
* import { Location, Source, Token, TokenKind } from 'graphql/language';
|
|
185
|
+
*
|
|
186
|
+
* const source = new Source('{ hello }');
|
|
187
|
+
* const startToken = new Token(TokenKind.BRACE_L, 0, 1, 1, 1);
|
|
188
|
+
* const endToken = new Token(TokenKind.BRACE_R, 8, 9, 1, 9);
|
|
189
|
+
* const location = new Location(startToken, endToken, source);
|
|
190
|
+
*
|
|
191
|
+
* location.start; // => 0
|
|
192
|
+
* location.end; // => 9
|
|
193
|
+
* location.source.body; // => '{ hello }'
|
|
194
|
+
* ```
|
|
195
|
+
*/constructor(t,n,r){this.start=t.start,this.end=n.end,this.startToken=t,this.endToken=n,this.source=r;}/**
|
|
196
|
+
* Returns the value used by `Object.prototype.toString`.
|
|
197
|
+
* @returns The built-in string tag for this object.
|
|
198
|
+
*/get[Symbol.toStringTag](){return"Location";}/**
|
|
199
|
+
* Returns a JSON representation of this location.
|
|
200
|
+
* @returns The JSON-serializable representation.
|
|
201
|
+
* @example
|
|
202
|
+
* ```ts
|
|
203
|
+
* import { parse } from 'graphql/language';
|
|
204
|
+
*
|
|
205
|
+
* const document = parse('{ hello }');
|
|
206
|
+
* const location = document.loc?.toJSON();
|
|
207
|
+
*
|
|
208
|
+
* location; // => { start: 0, end: 9 }
|
|
209
|
+
* ```
|
|
210
|
+
*/toJSON(){return{start:this.start,end:this.end};}}class mo{/** The kind of Token. *//** The character offset at which this Node begins. *//** The character offset at which this Node ends. *//** The 1-indexed line number on which this Token appears. *//** The 1-indexed column number at which this Token begins. *//**
|
|
211
|
+
* For non-punctuation tokens, represents the interpreted value of the token.
|
|
212
|
+
*
|
|
213
|
+
* Note: is undefined for punctuation tokens, but typed as string for
|
|
214
|
+
* convenience in the parser.
|
|
215
|
+
*//**
|
|
216
|
+
* Tokens exist as nodes in a double-linked-list amongst all tokens
|
|
217
|
+
* including ignored tokens. <SOF> is always the first node and <EOF>
|
|
218
|
+
* the last.
|
|
219
|
+
*//** Next token in the token stream, including ignored tokens. *//**
|
|
220
|
+
* Creates a Token instance.
|
|
221
|
+
* @param kind - Token kind produced by lexical analysis.
|
|
222
|
+
* @param start - Character offset where this token begins.
|
|
223
|
+
* @param end - Character offset where this token ends.
|
|
224
|
+
* @param line - One-indexed line number where this token begins.
|
|
225
|
+
* @param column - One-indexed column number where this token begins.
|
|
226
|
+
* @param value - Interpreted value for non-punctuation tokens.
|
|
227
|
+
* @example
|
|
228
|
+
* ```ts
|
|
229
|
+
* import { Token, TokenKind } from 'graphql/language';
|
|
230
|
+
*
|
|
231
|
+
* const token = new Token(TokenKind.NAME, 2, 7, 1, 3, 'hello');
|
|
232
|
+
*
|
|
233
|
+
* token.kind; // => TokenKind.NAME
|
|
234
|
+
* token.value; // => 'hello'
|
|
235
|
+
* token.toJSON(); // => { kind: 'Name', value: 'hello', line: 1, column: 3 }
|
|
236
|
+
* ```
|
|
237
|
+
*/constructor(t,n,r,a,i,o){this.kind=t,this.start=n,this.end=r,this.line=a,this.column=i,this.value=o,this.prev=null,this.next=null;}/**
|
|
238
|
+
* Returns the value used by `Object.prototype.toString`.
|
|
239
|
+
* @returns The built-in string tag for this object.
|
|
240
|
+
*/get[Symbol.toStringTag](){return"Token";}/**
|
|
241
|
+
* Returns a JSON representation of this token.
|
|
242
|
+
* @returns The JSON-serializable representation.
|
|
243
|
+
* @example
|
|
244
|
+
* ```ts
|
|
245
|
+
* import { Lexer, Source } from 'graphql/language';
|
|
246
|
+
*
|
|
247
|
+
* const lexer = new Lexer(new Source('{ hello }'));
|
|
248
|
+
* const token = lexer.advance().toJSON();
|
|
249
|
+
*
|
|
250
|
+
* token; // => { kind: '{', value: undefined, line: 1, column: 1 }
|
|
251
|
+
* ```
|
|
252
|
+
*/toJSON(){return{kind:this.kind,value:this.value,line:this.line,column:this.column};}}const yo={Name:[],Document:["definitions"],OperationDefinition:["description","name","variableDefinitions","directives","selectionSet"],VariableDefinition:["description","variable","type","defaultValue","directives"],Variable:["name"],SelectionSet:["selections"],Field:["alias","name","arguments","directives","selectionSet"],Argument:["name","value"],FragmentSpread:["name","directives"],InlineFragment:["typeCondition","directives","selectionSet"],FragmentDefinition:["description","name",// Note: fragment variable definitions are deprecated and will removed in v17.0.0
|
|
253
|
+
"variableDefinitions","typeCondition","directives","selectionSet"],IntValue:[],FloatValue:[],StringValue:[],BooleanValue:[],NullValue:[],EnumValue:[],ListValue:["values"],ObjectValue:["fields"],ObjectField:["name","value"],Directive:["name","arguments"],NamedType:["name"],ListType:["type"],NonNullType:["type"],SchemaDefinition:["description","directives","operationTypes"],OperationTypeDefinition:["type"],ScalarTypeDefinition:["description","name","directives"],ObjectTypeDefinition:["description","name","interfaces","directives","fields"],FieldDefinition:["description","name","arguments","type","directives"],InputValueDefinition:["description","name","type","defaultValue","directives"],InterfaceTypeDefinition:["description","name","interfaces","directives","fields"],UnionTypeDefinition:["description","name","directives","types"],EnumTypeDefinition:["description","name","directives","values"],EnumValueDefinition:["description","name","directives"],InputObjectTypeDefinition:["description","name","directives","fields"],DirectiveDefinition:["description","name","arguments","directives","locations"],SchemaExtension:["directives","operationTypes"],DirectiveExtension:["name","directives"],ScalarTypeExtension:["name","directives"],ObjectTypeExtension:["name","interfaces","directives","fields"],InterfaceTypeExtension:["name","interfaces","directives","fields"],UnionTypeExtension:["name","directives","types"],EnumTypeExtension:["name","directives","values"],InputObjectTypeExtension:["name","directives","fields"],TypeCoordinate:["name"],MemberCoordinate:["name","memberName"],ArgumentCoordinate:["name","fieldName","argumentName"],DirectiveCoordinate:["name"],DirectiveArgumentCoordinate:["name","argumentName"]},Yl=new Set(Object.keys(yo));function hi(e){const t=e==null?void 0:e.kind;return typeof t=="string"&&Yl.has(t);}var Wt;(function(e){e.QUERY="query",e.MUTATION="mutation",e.SUBSCRIPTION="subscription";})(Wt||(Wt={}));var Fr;(function(e){e.QUERY="QUERY",e.MUTATION="MUTATION",e.SUBSCRIPTION="SUBSCRIPTION",e.FIELD="FIELD",e.FRAGMENT_DEFINITION="FRAGMENT_DEFINITION",e.FRAGMENT_SPREAD="FRAGMENT_SPREAD",e.INLINE_FRAGMENT="INLINE_FRAGMENT",e.VARIABLE_DEFINITION="VARIABLE_DEFINITION",e.SCHEMA="SCHEMA",e.SCALAR="SCALAR",e.OBJECT="OBJECT",e.FIELD_DEFINITION="FIELD_DEFINITION",e.ARGUMENT_DEFINITION="ARGUMENT_DEFINITION",e.INTERFACE="INTERFACE",e.UNION="UNION",e.ENUM="ENUM",e.ENUM_VALUE="ENUM_VALUE",e.INPUT_OBJECT="INPUT_OBJECT",e.INPUT_FIELD_DEFINITION="INPUT_FIELD_DEFINITION",e.DIRECTIVE_DEFINITION="DIRECTIVE_DEFINITION";})(Fr||(Fr={}));var G;(function(e){e.NAME="Name",e.DOCUMENT="Document",e.OPERATION_DEFINITION="OperationDefinition",e.VARIABLE_DEFINITION="VariableDefinition",e.SELECTION_SET="SelectionSet",e.FIELD="Field",e.ARGUMENT="Argument",e.FRAGMENT_SPREAD="FragmentSpread",e.INLINE_FRAGMENT="InlineFragment",e.FRAGMENT_DEFINITION="FragmentDefinition",e.VARIABLE="Variable",e.INT="IntValue",e.FLOAT="FloatValue",e.STRING="StringValue",e.BOOLEAN="BooleanValue",e.NULL="NullValue",e.ENUM="EnumValue",e.LIST="ListValue",e.OBJECT="ObjectValue",e.OBJECT_FIELD="ObjectField",e.DIRECTIVE="Directive",e.NAMED_TYPE="NamedType",e.LIST_TYPE="ListType",e.NON_NULL_TYPE="NonNullType",e.SCHEMA_DEFINITION="SchemaDefinition",e.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",e.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",e.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",e.FIELD_DEFINITION="FieldDefinition",e.INPUT_VALUE_DEFINITION="InputValueDefinition",e.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",e.UNION_TYPE_DEFINITION="UnionTypeDefinition",e.ENUM_TYPE_DEFINITION="EnumTypeDefinition",e.ENUM_VALUE_DEFINITION="EnumValueDefinition",e.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",e.DIRECTIVE_DEFINITION="DirectiveDefinition",e.SCHEMA_EXTENSION="SchemaExtension",e.DIRECTIVE_EXTENSION="DirectiveExtension",e.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",e.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",e.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",e.UNION_TYPE_EXTENSION="UnionTypeExtension",e.ENUM_TYPE_EXTENSION="EnumTypeExtension",e.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension",e.TYPE_COORDINATE="TypeCoordinate",e.MEMBER_COORDINATE="MemberCoordinate",e.ARGUMENT_COORDINATE="ArgumentCoordinate",e.DIRECTIVE_COORDINATE="DirectiveCoordinate",e.DIRECTIVE_ARGUMENT_COORDINATE="DirectiveArgumentCoordinate";})(G||(G={}));function Vr(e){return e===9||e===32;}function hn(e){return e>=48&&e<=57;}function ho(e){return e>=97&&e<=122||// A-Z
|
|
254
|
+
e>=65&&e<=90;}function bo(e){return ho(e)||e===95;}function Ql(e){return ho(e)||hn(e)||e===95;}function Xl(e){var t;let n=Number.MAX_SAFE_INTEGER,r=null,a=-1;for(let o=0;o<e.length;++o){var i;const s=e[o],l=Zl(s);l!==s.length&&(r=(i=r)!==null&&i!==void 0?i:o,a=o,o!==0&&l<n&&(n=l));}return e.map((o,s)=>s===0?o:o.slice(n)).slice((t=r)!==null&&t!==void 0?t:0,a+1);}function Zl(e){let t=0;for(;t<e.length&&Vr(e.charCodeAt(t));)++t;return t;}function Jl(e,t){const n=e.replace(/"""/g,'\\"""'),r=n.split(/\r\n|[\n\r]/g),a=r.length===1,i=r.length>1&&r.slice(1).every(y=>y.length===0||Vr(y.charCodeAt(0))),o=n.endsWith('\\"""'),s=e.endsWith('"')&&!o,l=e.endsWith("\\"),u=s||l,d=// add leading and trailing new lines only if it improves readability
|
|
255
|
+
!a||e.length>70||u||i||o;let c="";const p=a&&Vr(e.charCodeAt(0));return(d&&!p||i)&&(c+=`
|
|
256
|
+
`),c+=n,(d||u)&&(c+=`
|
|
257
|
+
`),'"""'+c+'"""';}var N;(function(e){e.SOF="<SOF>",e.EOF="<EOF>",e.BANG="!",e.DOLLAR="$",e.AMP="&",e.PAREN_L="(",e.PAREN_R=")",e.DOT=".",e.SPREAD="...",e.COLON=":",e.EQUALS="=",e.AT="@",e.BRACKET_L="[",e.BRACKET_R="]",e.BRACE_L="{",e.PIPE="|",e.BRACE_R="}",e.NAME="Name",e.INT="Int",e.FLOAT="Float",e.STRING="String",e.BLOCK_STRING="BlockString",e.COMMENT="Comment";})(N||(N={}));class eu{/** Source document used to derive error locations. *//** Most recent non-ignored token returned by the lexer. *//** Current non-ignored token at the lexer cursor. *//** The (1-indexed) line containing the current token. *//** Character offset where the current line starts. *//**
|
|
258
|
+
* Creates a Lexer instance.
|
|
259
|
+
* @param source - Source document used to derive error locations.
|
|
260
|
+
* @example
|
|
261
|
+
* ```ts
|
|
262
|
+
* import { Lexer, Source, TokenKind } from 'graphql/language';
|
|
263
|
+
*
|
|
264
|
+
* const lexer = new Lexer(new Source('{ hello }'));
|
|
265
|
+
*
|
|
266
|
+
* lexer.token.kind; // => TokenKind.SOF
|
|
267
|
+
* lexer.advance().kind; // => TokenKind.BRACE_L
|
|
268
|
+
* lexer.advance().value; // => 'hello'
|
|
269
|
+
* lexer.advance().kind; // => TokenKind.BRACE_R
|
|
270
|
+
* ```
|
|
271
|
+
*/constructor(t){const n=new mo(N.SOF,0,0,0,0);this.source=t,this.lastToken=n,this.token=n,this.line=1,this.lineStart=0;}/**
|
|
272
|
+
* Returns the value used by `Object.prototype.toString`.
|
|
273
|
+
* @returns The built-in string tag for this object.
|
|
274
|
+
*/get[Symbol.toStringTag](){return"Lexer";}/**
|
|
275
|
+
* Advances the token stream to the next non-ignored token.
|
|
276
|
+
* @returns The next non-ignored token.
|
|
277
|
+
* @example
|
|
278
|
+
* ```ts
|
|
279
|
+
* import { Lexer, Source } from 'graphql/language';
|
|
280
|
+
*
|
|
281
|
+
* const lexer = new Lexer(new Source('{ hello }'));
|
|
282
|
+
* const token = lexer.advance();
|
|
283
|
+
*
|
|
284
|
+
* token.kind; // => '{'
|
|
285
|
+
* lexer.token; // => token
|
|
286
|
+
* ```
|
|
287
|
+
*/advance(){return this.lastToken=this.token,this.token=this.lookahead();}/**
|
|
288
|
+
* Looks ahead and returns the next non-ignored token, but does not change
|
|
289
|
+
* the state of Lexer.
|
|
290
|
+
* @returns The next non-ignored token without advancing the lexer.
|
|
291
|
+
* @example
|
|
292
|
+
* ```ts
|
|
293
|
+
* import { Lexer, Source } from 'graphql/language';
|
|
294
|
+
*
|
|
295
|
+
* const lexer = new Lexer(new Source('{ hello }'));
|
|
296
|
+
* const token = lexer.lookahead();
|
|
297
|
+
*
|
|
298
|
+
* token.kind; // => '{'
|
|
299
|
+
* lexer.token.kind; // => '<SOF>'
|
|
300
|
+
* ```
|
|
301
|
+
*/lookahead(){let t=this.token;if(t.kind!==N.EOF)do if(t.next)t=t.next;else{const n=nu(this,t.end);t.next=n,n.prev=t,t=n;}while(t.kind===N.COMMENT);return t;}}function tu(e){return e===N.BANG||e===N.DOLLAR||e===N.AMP||e===N.PAREN_L||e===N.PAREN_R||e===N.DOT||e===N.SPREAD||e===N.COLON||e===N.EQUALS||e===N.AT||e===N.BRACKET_L||e===N.BRACKET_R||e===N.BRACE_L||e===N.PIPE||e===N.BRACE_R;}function Xt(e){return e>=0&&e<=55295||e>=57344&&e<=1114111;}function nr(e,t){return go(e.charCodeAt(t))&&vo(e.charCodeAt(t+1));}function go(e){return e>=55296&&e<=56319;}function vo(e){return e>=56320&&e<=57343;}function _t(e,t){const n=e.source.body.codePointAt(t);if(n===void 0)return N.EOF;if(n>=32&&n<=126){const r=String.fromCodePoint(n);return r==='"'?`'"'`:`"${r}"`;}return"U+"+n.toString(16).toUpperCase().padStart(4,"0");}function Ne(e,t,n,r,a){const i=e.line,o=1+n-e.lineStart;return new mo(t,n,r,i,o,a);}function nu(e,t){const n=e.source.body,r=n.length;let a=t;for(;a<r;){const i=n.charCodeAt(a);switch(i){// Ignored ::
|
|
302
|
+
// - UnicodeBOM
|
|
303
|
+
// - WhiteSpace
|
|
304
|
+
// - LineTerminator
|
|
305
|
+
// - Comment
|
|
306
|
+
// - Comma
|
|
307
|
+
//
|
|
308
|
+
// UnicodeBOM :: "Byte Order Mark (U+FEFF)"
|
|
309
|
+
//
|
|
310
|
+
// WhiteSpace ::
|
|
311
|
+
// - "Horizontal Tab (U+0009)"
|
|
312
|
+
// - "Space (U+0020)"
|
|
313
|
+
//
|
|
314
|
+
// Comma :: ,
|
|
315
|
+
case 65279:// <BOM>
|
|
316
|
+
case 9:// \t
|
|
317
|
+
case 32:// <space>
|
|
318
|
+
case 44:++a;continue;// LineTerminator ::
|
|
319
|
+
// - "New Line (U+000A)"
|
|
320
|
+
// - "Carriage Return (U+000D)" [lookahead != "New Line (U+000A)"]
|
|
321
|
+
// - "Carriage Return (U+000D)" "New Line (U+000A)"
|
|
322
|
+
case 10:++a,++e.line,e.lineStart=a;continue;case 13:n.charCodeAt(a+1)===10?a+=2:++a,++e.line,e.lineStart=a;continue;// Comment
|
|
323
|
+
case 35:return ru(e,a);// Token ::
|
|
324
|
+
// - Punctuator
|
|
325
|
+
// - Name
|
|
326
|
+
// - IntValue
|
|
327
|
+
// - FloatValue
|
|
328
|
+
// - StringValue
|
|
329
|
+
//
|
|
330
|
+
// Punctuator :: one of ! $ & ( ) ... : = @ [ ] { | }
|
|
331
|
+
case 33:return Ne(e,N.BANG,a,a+1);case 36:return Ne(e,N.DOLLAR,a,a+1);case 38:return Ne(e,N.AMP,a,a+1);case 40:return Ne(e,N.PAREN_L,a,a+1);case 41:return Ne(e,N.PAREN_R,a,a+1);case 46:if(n.charCodeAt(a+1)===46&&n.charCodeAt(a+2)===46)return Ne(e,N.SPREAD,a,a+3);break;case 58:return Ne(e,N.COLON,a,a+1);case 61:return Ne(e,N.EQUALS,a,a+1);case 64:return Ne(e,N.AT,a,a+1);case 91:return Ne(e,N.BRACKET_L,a,a+1);case 93:return Ne(e,N.BRACKET_R,a,a+1);case 123:return Ne(e,N.BRACE_L,a,a+1);case 124:return Ne(e,N.PIPE,a,a+1);case 125:return Ne(e,N.BRACE_R,a,a+1);// StringValue
|
|
332
|
+
case 34:return n.charCodeAt(a+1)===34&&n.charCodeAt(a+2)===34?uu(e,a):iu(e,a);}if(hn(i)||i===45)return au(e,a,i);if(bo(i))return cu(e,a);throw Me(e.source,a,i===39?`Unexpected single quote character ('), did you mean to use a double quote (")?`:Xt(i)||nr(n,a)?`Unexpected character: ${_t(e,a)}.`:`Invalid character: ${_t(e,a)}.`);}return Ne(e,N.EOF,r,r);}function ru(e,t){const n=e.source.body,r=n.length;let a=t+1;for(;a<r;){const i=n.charCodeAt(a);if(i===10||i===13)break;if(Xt(i))++a;else if(nr(n,a))a+=2;else break;}return Ne(e,N.COMMENT,t,a,n.slice(t+1,a));}function au(e,t,n){const r=e.source.body;let a=t,i=n,o=!1;if(i===45&&(i=r.charCodeAt(++a)),i===48){if(i=r.charCodeAt(++a),hn(i))throw Me(e.source,a,`Invalid number, unexpected digit after 0: ${_t(e,a)}.`);}else a=Tr(e,a,i),i=r.charCodeAt(a);if(i===46&&(o=!0,i=r.charCodeAt(++a),a=Tr(e,a,i),i=r.charCodeAt(a)),(i===69||i===101)&&(o=!0,i=r.charCodeAt(++a),(i===43||i===45)&&(i=r.charCodeAt(++a)),a=Tr(e,a,i),i=r.charCodeAt(a)),i===46||bo(i))throw Me(e.source,a,`Invalid number, expected digit but got: ${_t(e,a)}.`);return Ne(e,o?N.FLOAT:N.INT,t,a,r.slice(t,a));}function Tr(e,t,n){if(!hn(n))throw Me(e.source,t,`Invalid number, expected digit but got: ${_t(e,t)}.`);const r=e.source.body;let a=t+1;for(;hn(r.charCodeAt(a));)++a;return a;}function iu(e,t){const n=e.source.body,r=n.length;let a=t+1,i=a,o="";for(;a<r;){const s=n.charCodeAt(a);if(s===34)return o+=n.slice(i,a),Ne(e,N.STRING,t,a+1,o);if(s===92){o+=n.slice(i,a);const l=n.charCodeAt(a+1)===117?n.charCodeAt(a+2)===123?ou(e,a):su(e,a):lu(e,a);o+=l.value,a+=l.size,i=a;continue;}if(s===10||s===13)break;if(Xt(s))++a;else if(nr(n,a))a+=2;else throw Me(e.source,a,`Invalid character within String: ${_t(e,a)}.`);}throw Me(e.source,a,"Unterminated string.");}function ou(e,t){const n=e.source.body;let r=0,a=3;for(;a<12;){const i=n.charCodeAt(t+a++);if(i===125){if(a<5||!Xt(r))break;return{value:String.fromCodePoint(r),size:a};}if(r=r<<4|ln(i),r<0)break;}throw Me(e.source,t,`Invalid Unicode escape sequence: "${n.slice(t,t+a)}".`);}function su(e,t){const n=e.source.body,r=bi(n,t+2);if(Xt(r))return{value:String.fromCodePoint(r),size:6};if(go(r)&&n.charCodeAt(t+6)===92&&n.charCodeAt(t+7)===117){const a=bi(n,t+8);if(vo(a))return{value:String.fromCodePoint(r,a),size:12};}throw Me(e.source,t,`Invalid Unicode escape sequence: "${n.slice(t,t+6)}".`);}function bi(e,t){return ln(e.charCodeAt(t))<<12|ln(e.charCodeAt(t+1))<<8|ln(e.charCodeAt(t+2))<<4|ln(e.charCodeAt(t+3));}function ln(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:-1;}function lu(e,t){const n=e.source.body;switch(n.charCodeAt(t+1)){case 34:return{value:'"',size:2};case 92:return{value:"\\",size:2};case 47:return{value:"/",size:2};case 98:return{value:"\b",size:2};case 102:return{value:"\f",size:2};case 110:return{value:`
|
|
333
|
+
`,size:2};case 114:return{value:"\r",size:2};case 116:return{value:" ",size:2};}throw Me(e.source,t,`Invalid character escape sequence: "${n.slice(t,t+2)}".`);}function uu(e,t){const n=e.source.body,r=n.length;let a=e.lineStart,i=t+3,o=i,s="";const l=[];for(;i<r;){const u=n.charCodeAt(i);if(u===34&&n.charCodeAt(i+1)===34&&n.charCodeAt(i+2)===34){s+=n.slice(o,i),l.push(s);const d=Ne(e,N.BLOCK_STRING,t,i+3,// Return a string of the lines joined with U+000A.
|
|
334
|
+
Xl(l).join(`
|
|
335
|
+
`));return e.line+=l.length-1,e.lineStart=a,d;}if(u===92&&n.charCodeAt(i+1)===34&&n.charCodeAt(i+2)===34&&n.charCodeAt(i+3)===34){s+=n.slice(o,i),o=i+1,i+=4;continue;}if(u===10||u===13){s+=n.slice(o,i),l.push(s),u===13&&n.charCodeAt(i+1)===10?i+=2:++i,s="",o=i,a=i;continue;}if(Xt(u))++i;else if(nr(n,i))i+=2;else throw Me(e.source,i,`Invalid character within String: ${_t(e,i)}.`);}throw Me(e.source,i,"Unterminated string.");}function cu(e,t){const n=e.source.body,r=n.length;let a=t+1;for(;a<r;){const i=n.charCodeAt(a);if(Ql(i))++a;else break;}return Ne(e,N.NAME,t,a,n.slice(t,a));}const du=10,wo=2;function ma(e){return rr(e,[]);}function rr(e,t){switch(typeof e){case"string":return JSON.stringify(e);case"function":return e.name?`[function ${e.name}]`:"[function]";case"object":return pu(e,t);default:return String(e);}}function pu(e,t){if(e===null)return"null";if(t.includes(e))return"[Circular]";const n=[...t,e];if(fu(e)){const r=e.toJSON();if(r!==e)return typeof r=="string"?r:rr(r,n);}else if(Array.isArray(e))return yu(e,n);return mu(e,n);}function fu(e){return typeof e.toJSON=="function";}function mu(e,t){const n=Object.entries(e);return n.length===0?"{}":t.length>wo?"["+hu(e)+"]":"{ "+n.map(([a,i])=>a+": "+rr(i,t)).join(", ")+" }";}function yu(e,t){if(e.length===0)return"[]";if(t.length>wo)return"[Array]";const n=Math.min(du,e.length),r=e.length-n,a=[];for(let i=0;i<n;++i)a.push(rr(e[i],t));return r===1?a.push("... 1 more item"):r>1&&a.push(`... ${r} more items`),"["+a.join(", ")+"]";}function hu(e){const t=Object.prototype.toString.call(e).replace(/^\[object /,"").replace(/]$/,"");if(t==="Object"&&typeof e.constructor=="function"){const n=e.constructor.name;if(typeof n=="string"&&n!=="")return n;}return t;}const bu=globalThis.process&&// eslint-disable-next-line no-undef
|
|
336
|
+
!0,gu=/* c8 ignore next 6 */// FIXME: https://github.com/graphql/graphql-js/issues/2317
|
|
337
|
+
bu?function(t,n){return t instanceof n;}:function(t,n){if(t instanceof n)return!0;if(typeof t=="object"&&t!==null){var r;const a=n.prototype[Symbol.toStringTag],i=// We still need to support constructor's name to detect conflicts with older versions of this library.
|
|
338
|
+
Symbol.toStringTag in t?t[Symbol.toStringTag]:(r=t.constructor)===null||r===void 0?void 0:r.name;if(a===i){const o=ma(t);throw new Error(`Cannot use ${a} "${o}" from another module or realm.
|
|
339
|
+
|
|
340
|
+
Ensure that there is only one instance of "graphql" in the node_modules
|
|
341
|
+
directory. If different versions of "graphql" are the dependencies of other
|
|
342
|
+
relied on modules, use "resolutions" to ensure only one version is installed.
|
|
343
|
+
|
|
344
|
+
https://yarnpkg.com/en/docs/selective-version-resolutions
|
|
345
|
+
|
|
346
|
+
Duplicate "graphql" modules cannot be used at the same time since different
|
|
347
|
+
versions may have different capabilities and behavior. The data from one
|
|
348
|
+
version used in the function from another could produce confusing and
|
|
349
|
+
spurious results.`);}}return!1;};class Ao{/** The GraphQL source text. *//** Name used in diagnostics for this source, such as a file path or request name. *//** One-indexed line and column where this source begins. *//**
|
|
350
|
+
* Creates a Source instance.
|
|
351
|
+
* @param body - The GraphQL source text.
|
|
352
|
+
* @param name - Name used in diagnostics for this source.
|
|
353
|
+
* @param locationOffset - One-indexed line and column where this source begins.
|
|
354
|
+
* @example
|
|
355
|
+
* ```ts
|
|
356
|
+
* import { Source } from 'graphql/language';
|
|
357
|
+
*
|
|
358
|
+
* const source = new Source(
|
|
359
|
+
* 'type Query { greeting: String }',
|
|
360
|
+
* 'schema.graphql',
|
|
361
|
+
* { line: 10, column: 1 },
|
|
362
|
+
* );
|
|
363
|
+
*
|
|
364
|
+
* source.body; // => 'type Query { greeting: String }'
|
|
365
|
+
* source.name; // => 'schema.graphql'
|
|
366
|
+
* source.locationOffset; // => { line: 10, column: 1 }
|
|
367
|
+
* ```
|
|
368
|
+
*/constructor(t,n="GraphQL request",r={line:1,column:1}){typeof t=="string"||Sn(!1,`Body must be a string. Received: ${ma(t)}.`),this.body=t,this.name=n,this.locationOffset=r,this.locationOffset.line>0||Sn(!1,"line in locationOffset is 1-indexed and must be positive."),this.locationOffset.column>0||Sn(!1,"column in locationOffset is 1-indexed and must be positive.");}/**
|
|
369
|
+
* Returns the value used by `Object.prototype.toString`.
|
|
370
|
+
* @returns The built-in string tag for this object.
|
|
371
|
+
*/get[Symbol.toStringTag](){return"Source";}}function vu(e){return gu(e,Ao);}function wu(e,t){const n=new Au(e,t),r=n.parseDocument();return Object.defineProperty(r,"tokenCount",{enumerable:!1,value:n.tokenCount}),r;}class Au{constructor(t,n={}){const{lexer:r,...a}=n;if(r)this._lexer=r;else{const i=vu(t)?t:new Ao(t);this._lexer=new eu(i);}this._options=a,this._tokenCounter=0;}get tokenCount(){return this._tokenCounter;}/**
|
|
372
|
+
* Converts a name lex token into a name parse node.
|
|
373
|
+
*
|
|
374
|
+
* @internal
|
|
375
|
+
*/parseName(){const t=this.expectToken(N.NAME);return this.node(t,{kind:G.NAME,value:t.value});}// Implements the parsing rules in the Document section.
|
|
376
|
+
/**
|
|
377
|
+
* Document : Definition+
|
|
378
|
+
*
|
|
379
|
+
* @internal
|
|
380
|
+
*/parseDocument(){return this.node(this._lexer.token,{kind:G.DOCUMENT,definitions:this.many(N.SOF,this.parseDefinition,N.EOF)});}/**
|
|
381
|
+
* Definition :
|
|
382
|
+
* - ExecutableDefinition
|
|
383
|
+
* - TypeSystemDefinition
|
|
384
|
+
* - TypeSystemExtension
|
|
385
|
+
*
|
|
386
|
+
* ExecutableDefinition :
|
|
387
|
+
* - OperationDefinition
|
|
388
|
+
* - FragmentDefinition
|
|
389
|
+
*
|
|
390
|
+
* TypeSystemDefinition :
|
|
391
|
+
* - SchemaDefinition
|
|
392
|
+
* - TypeDefinition
|
|
393
|
+
* - DirectiveDefinition
|
|
394
|
+
*
|
|
395
|
+
* TypeDefinition :
|
|
396
|
+
* - ScalarTypeDefinition
|
|
397
|
+
* - ObjectTypeDefinition
|
|
398
|
+
* - InterfaceTypeDefinition
|
|
399
|
+
* - UnionTypeDefinition
|
|
400
|
+
* - EnumTypeDefinition
|
|
401
|
+
* - InputObjectTypeDefinition
|
|
402
|
+
*
|
|
403
|
+
* @internal
|
|
404
|
+
*/parseDefinition(){if(this.peek(N.BRACE_L))return this.parseOperationDefinition();const t=this.peekDescription(),n=t?this._lexer.lookahead():this._lexer.token;if(t&&n.kind===N.BRACE_L)throw Me(this._lexer.source,this._lexer.token.start,"Unexpected description, descriptions are not supported on shorthand queries.");if(n.kind===N.NAME){switch(n.value){case"schema":return this.parseSchemaDefinition();case"scalar":return this.parseScalarTypeDefinition();case"type":return this.parseObjectTypeDefinition();case"interface":return this.parseInterfaceTypeDefinition();case"union":return this.parseUnionTypeDefinition();case"enum":return this.parseEnumTypeDefinition();case"input":return this.parseInputObjectTypeDefinition();case"directive":return this.parseDirectiveDefinition();}switch(n.value){case"query":case"mutation":case"subscription":return this.parseOperationDefinition();case"fragment":return this.parseFragmentDefinition();}if(t)throw Me(this._lexer.source,this._lexer.token.start,"Unexpected description, only GraphQL definitions support descriptions.");switch(n.value){case"extend":return this.parseTypeSystemExtension();}}throw this.unexpected(n);}// Implements the parsing rules in the Operations section.
|
|
405
|
+
/**
|
|
406
|
+
* OperationDefinition :
|
|
407
|
+
* - SelectionSet
|
|
408
|
+
* - OperationType Name? VariableDefinitions? Directives? SelectionSet
|
|
409
|
+
*
|
|
410
|
+
* @internal
|
|
411
|
+
*/parseOperationDefinition(){const t=this._lexer.token;if(this.peek(N.BRACE_L))return this.node(t,{kind:G.OPERATION_DEFINITION,operation:Wt.QUERY,description:void 0,name:void 0,variableDefinitions:[],directives:[],selectionSet:this.parseSelectionSet()});const n=this.parseDescription(),r=this.parseOperationType();let a;return this.peek(N.NAME)&&(a=this.parseName()),this.node(t,{kind:G.OPERATION_DEFINITION,operation:r,description:n,name:a,variableDefinitions:this.parseVariableDefinitions(),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()});}/**
|
|
412
|
+
* OperationType : one of query mutation subscription
|
|
413
|
+
*
|
|
414
|
+
* @internal
|
|
415
|
+
*/parseOperationType(){const t=this.expectToken(N.NAME);switch(t.value){case"query":return Wt.QUERY;case"mutation":return Wt.MUTATION;case"subscription":return Wt.SUBSCRIPTION;}throw this.unexpected(t);}/**
|
|
416
|
+
* VariableDefinitions : ( VariableDefinition+ )
|
|
417
|
+
*
|
|
418
|
+
* @internal
|
|
419
|
+
*/parseVariableDefinitions(){return this.optionalMany(N.PAREN_L,this.parseVariableDefinition,N.PAREN_R);}/**
|
|
420
|
+
* VariableDefinition : Variable : Type DefaultValue? Directives[Const]?
|
|
421
|
+
*
|
|
422
|
+
* @internal
|
|
423
|
+
*/parseVariableDefinition(){return this.node(this._lexer.token,{kind:G.VARIABLE_DEFINITION,description:this.parseDescription(),variable:this.parseVariable(),type:(this.expectToken(N.COLON),this.parseTypeReference()),defaultValue:this.expectOptionalToken(N.EQUALS)?this.parseConstValueLiteral():void 0,directives:this.parseConstDirectives()});}/**
|
|
424
|
+
* Variable : $ Name
|
|
425
|
+
*
|
|
426
|
+
* @internal
|
|
427
|
+
*/parseVariable(){const t=this._lexer.token;return this.expectToken(N.DOLLAR),this.node(t,{kind:G.VARIABLE,name:this.parseName()});}/**
|
|
428
|
+
* ```
|
|
429
|
+
* SelectionSet : { Selection+ }
|
|
430
|
+
* ```
|
|
431
|
+
*
|
|
432
|
+
* @internal
|
|
433
|
+
*/parseSelectionSet(){return this.node(this._lexer.token,{kind:G.SELECTION_SET,selections:this.many(N.BRACE_L,this.parseSelection,N.BRACE_R)});}/**
|
|
434
|
+
* Selection :
|
|
435
|
+
* - Field
|
|
436
|
+
* - FragmentSpread
|
|
437
|
+
* - InlineFragment
|
|
438
|
+
*
|
|
439
|
+
* @internal
|
|
440
|
+
*/parseSelection(){return this.peek(N.SPREAD)?this.parseFragment():this.parseField();}/**
|
|
441
|
+
* Field : Alias? Name Arguments? Directives? SelectionSet?
|
|
442
|
+
*
|
|
443
|
+
* Alias : Name :
|
|
444
|
+
*
|
|
445
|
+
* @internal
|
|
446
|
+
*/parseField(){const t=this._lexer.token,n=this.parseName();let r,a;return this.expectOptionalToken(N.COLON)?(r=n,a=this.parseName()):a=n,this.node(t,{kind:G.FIELD,alias:r,name:a,arguments:this.parseArguments(!1),directives:this.parseDirectives(!1),selectionSet:this.peek(N.BRACE_L)?this.parseSelectionSet():void 0});}/**
|
|
447
|
+
* Arguments[Const] : ( Argument[?Const]+ )
|
|
448
|
+
*
|
|
449
|
+
* @internal
|
|
450
|
+
*/parseArguments(t){const n=t?this.parseConstArgument:this.parseArgument;return this.optionalMany(N.PAREN_L,n,N.PAREN_R);}/**
|
|
451
|
+
* Argument[Const] : Name : Value[?Const]
|
|
452
|
+
*
|
|
453
|
+
* @internal
|
|
454
|
+
*/parseArgument(t=!1){const n=this._lexer.token,r=this.parseName();return this.expectToken(N.COLON),this.node(n,{kind:G.ARGUMENT,name:r,value:this.parseValueLiteral(t)});}parseConstArgument(){return this.parseArgument(!0);}// Implements the parsing rules in the Fragments section.
|
|
455
|
+
/**
|
|
456
|
+
* Corresponds to both FragmentSpread and InlineFragment in the spec.
|
|
457
|
+
*
|
|
458
|
+
* FragmentSpread : ... FragmentName Directives?
|
|
459
|
+
*
|
|
460
|
+
* InlineFragment : ... TypeCondition? Directives? SelectionSet
|
|
461
|
+
*
|
|
462
|
+
* @internal
|
|
463
|
+
*/parseFragment(){const t=this._lexer.token;this.expectToken(N.SPREAD);const n=this.expectOptionalKeyword("on");return!n&&this.peek(N.NAME)?this.node(t,{kind:G.FRAGMENT_SPREAD,name:this.parseFragmentName(),directives:this.parseDirectives(!1)}):this.node(t,{kind:G.INLINE_FRAGMENT,typeCondition:n?this.parseNamedType():void 0,directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()});}/**
|
|
464
|
+
* FragmentDefinition :
|
|
465
|
+
* - fragment FragmentName on TypeCondition Directives? SelectionSet
|
|
466
|
+
*
|
|
467
|
+
* TypeCondition : NamedType
|
|
468
|
+
*
|
|
469
|
+
* @internal
|
|
470
|
+
*/parseFragmentDefinition(){const t=this._lexer.token,n=this.parseDescription();return this.expectKeyword("fragment"),this._options.allowLegacyFragmentVariables===!0?this.node(t,{kind:G.FRAGMENT_DEFINITION,description:n,name:this.parseFragmentName(),variableDefinitions:this.parseVariableDefinitions(),typeCondition:(this.expectKeyword("on"),this.parseNamedType()),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()}):this.node(t,{kind:G.FRAGMENT_DEFINITION,description:n,name:this.parseFragmentName(),typeCondition:(this.expectKeyword("on"),this.parseNamedType()),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()});}/**
|
|
471
|
+
* FragmentName : Name but not `on`
|
|
472
|
+
*
|
|
473
|
+
* @internal
|
|
474
|
+
*/parseFragmentName(){if(this._lexer.token.value==="on")throw this.unexpected();return this.parseName();}// Implements the parsing rules in the Values section.
|
|
475
|
+
/**
|
|
476
|
+
* Value[Const] :
|
|
477
|
+
* - [~Const] Variable
|
|
478
|
+
* - IntValue
|
|
479
|
+
* - FloatValue
|
|
480
|
+
* - StringValue
|
|
481
|
+
* - BooleanValue
|
|
482
|
+
* - NullValue
|
|
483
|
+
* - EnumValue
|
|
484
|
+
* - ListValue[?Const]
|
|
485
|
+
* - ObjectValue[?Const]
|
|
486
|
+
*
|
|
487
|
+
* BooleanValue : one of `true` `false`
|
|
488
|
+
*
|
|
489
|
+
* NullValue : `null`
|
|
490
|
+
*
|
|
491
|
+
* EnumValue : Name but not `true`, `false` or `null`
|
|
492
|
+
*
|
|
493
|
+
* @internal
|
|
494
|
+
*/parseValueLiteral(t){const n=this._lexer.token;switch(n.kind){case N.BRACKET_L:return this.parseList(t);case N.BRACE_L:return this.parseObject(t);case N.INT:return this.advanceLexer(),this.node(n,{kind:G.INT,value:n.value});case N.FLOAT:return this.advanceLexer(),this.node(n,{kind:G.FLOAT,value:n.value});case N.STRING:case N.BLOCK_STRING:return this.parseStringLiteral();case N.NAME:switch(this.advanceLexer(),n.value){case"true":return this.node(n,{kind:G.BOOLEAN,value:!0});case"false":return this.node(n,{kind:G.BOOLEAN,value:!1});case"null":return this.node(n,{kind:G.NULL});default:return this.node(n,{kind:G.ENUM,value:n.value});}case N.DOLLAR:if(t)if(this.expectToken(N.DOLLAR),this._lexer.token.kind===N.NAME){const r=this._lexer.token.value;throw Me(this._lexer.source,n.start,`Unexpected variable "$${r}" in constant value.`);}else throw this.unexpected(n);return this.parseVariable();default:throw this.unexpected();}}parseConstValueLiteral(){return this.parseValueLiteral(!0);}parseStringLiteral(){const t=this._lexer.token;return this.advanceLexer(),this.node(t,{kind:G.STRING,value:t.value,block:t.kind===N.BLOCK_STRING});}/**
|
|
495
|
+
* ListValue[Const] :
|
|
496
|
+
* - [ ]
|
|
497
|
+
* - [ Value[?Const]+ ]
|
|
498
|
+
*
|
|
499
|
+
* @internal
|
|
500
|
+
*/parseList(t){const n=()=>this.parseValueLiteral(t);return this.node(this._lexer.token,{kind:G.LIST,values:this.any(N.BRACKET_L,n,N.BRACKET_R)});}/**
|
|
501
|
+
* ```
|
|
502
|
+
* ObjectValue[Const] :
|
|
503
|
+
* - { }
|
|
504
|
+
* - { ObjectField[?Const]+ }
|
|
505
|
+
* ```
|
|
506
|
+
*
|
|
507
|
+
* @internal
|
|
508
|
+
*/parseObject(t){const n=()=>this.parseObjectField(t);return this.node(this._lexer.token,{kind:G.OBJECT,fields:this.any(N.BRACE_L,n,N.BRACE_R)});}/**
|
|
509
|
+
* ObjectField[Const] : Name : Value[?Const]
|
|
510
|
+
*
|
|
511
|
+
* @internal
|
|
512
|
+
*/parseObjectField(t){const n=this._lexer.token,r=this.parseName();return this.expectToken(N.COLON),this.node(n,{kind:G.OBJECT_FIELD,name:r,value:this.parseValueLiteral(t)});}// Implements the parsing rules in the Directives section.
|
|
513
|
+
/**
|
|
514
|
+
* Directives[Const] : Directive[?Const]+
|
|
515
|
+
*
|
|
516
|
+
* @internal
|
|
517
|
+
*/parseDirectives(t){const n=[];for(;this.peek(N.AT);)n.push(this.parseDirective(t));return n;}parseConstDirectives(){return this.parseDirectives(!0);}/**
|
|
518
|
+
* ```
|
|
519
|
+
* Directive[Const] : @ Name Arguments[?Const]?
|
|
520
|
+
* ```
|
|
521
|
+
*
|
|
522
|
+
* @internal
|
|
523
|
+
*/parseDirective(t){const n=this._lexer.token;return this.expectToken(N.AT),this.node(n,{kind:G.DIRECTIVE,name:this.parseName(),arguments:this.parseArguments(t)});}// Implements the parsing rules in the Types section.
|
|
524
|
+
/**
|
|
525
|
+
* Type :
|
|
526
|
+
* - NamedType
|
|
527
|
+
* - ListType
|
|
528
|
+
* - NonNullType
|
|
529
|
+
*
|
|
530
|
+
* @internal
|
|
531
|
+
*/parseTypeReference(){const t=this._lexer.token;let n;if(this.expectOptionalToken(N.BRACKET_L)){const r=this.parseTypeReference();this.expectToken(N.BRACKET_R),n=this.node(t,{kind:G.LIST_TYPE,type:r});}else n=this.parseNamedType();return this.expectOptionalToken(N.BANG)?this.node(t,{kind:G.NON_NULL_TYPE,type:n}):n;}/**
|
|
532
|
+
* NamedType : Name
|
|
533
|
+
*
|
|
534
|
+
* @internal
|
|
535
|
+
*/parseNamedType(){return this.node(this._lexer.token,{kind:G.NAMED_TYPE,name:this.parseName()});}// Implements the parsing rules in the Type Definition section.
|
|
536
|
+
peekDescription(){return this.peek(N.STRING)||this.peek(N.BLOCK_STRING);}/**
|
|
537
|
+
* Description : StringValue
|
|
538
|
+
*
|
|
539
|
+
* @internal
|
|
540
|
+
*/parseDescription(){if(this.peekDescription())return this.parseStringLiteral();}/**
|
|
541
|
+
* ```
|
|
542
|
+
* SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ }
|
|
543
|
+
* ```
|
|
544
|
+
*
|
|
545
|
+
* @internal
|
|
546
|
+
*/parseSchemaDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("schema");const r=this.parseConstDirectives(),a=this.many(N.BRACE_L,this.parseOperationTypeDefinition,N.BRACE_R);return this.node(t,{kind:G.SCHEMA_DEFINITION,description:n,directives:r,operationTypes:a});}/**
|
|
547
|
+
* OperationTypeDefinition : OperationType : NamedType
|
|
548
|
+
*
|
|
549
|
+
* @internal
|
|
550
|
+
*/parseOperationTypeDefinition(){const t=this._lexer.token,n=this.parseOperationType();this.expectToken(N.COLON);const r=this.parseNamedType();return this.node(t,{kind:G.OPERATION_TYPE_DEFINITION,operation:n,type:r});}/**
|
|
551
|
+
* ScalarTypeDefinition : Description? scalar Name Directives[Const]?
|
|
552
|
+
*
|
|
553
|
+
* @internal
|
|
554
|
+
*/parseScalarTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("scalar");const r=this.parseName(),a=this.parseConstDirectives();return this.node(t,{kind:G.SCALAR_TYPE_DEFINITION,description:n,name:r,directives:a});}/**
|
|
555
|
+
* ObjectTypeDefinition :
|
|
556
|
+
* Description?
|
|
557
|
+
* type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition?
|
|
558
|
+
*
|
|
559
|
+
* @internal
|
|
560
|
+
*/parseObjectTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("type");const r=this.parseName(),a=this.parseImplementsInterfaces(),i=this.parseConstDirectives(),o=this.parseFieldsDefinition();return this.node(t,{kind:G.OBJECT_TYPE_DEFINITION,description:n,name:r,interfaces:a,directives:i,fields:o});}/**
|
|
561
|
+
* ImplementsInterfaces :
|
|
562
|
+
* - implements `&`? NamedType
|
|
563
|
+
* - ImplementsInterfaces & NamedType
|
|
564
|
+
*
|
|
565
|
+
* @internal
|
|
566
|
+
*/parseImplementsInterfaces(){return this.expectOptionalKeyword("implements")?this.delimitedMany(N.AMP,this.parseNamedType):[];}/**
|
|
567
|
+
* ```
|
|
568
|
+
* FieldsDefinition : { FieldDefinition+ }
|
|
569
|
+
* ```
|
|
570
|
+
*
|
|
571
|
+
* @internal
|
|
572
|
+
*/parseFieldsDefinition(){return this.optionalMany(N.BRACE_L,this.parseFieldDefinition,N.BRACE_R);}/**
|
|
573
|
+
* FieldDefinition :
|
|
574
|
+
* - Description? Name ArgumentsDefinition? : Type Directives[Const]?
|
|
575
|
+
*
|
|
576
|
+
* @internal
|
|
577
|
+
*/parseFieldDefinition(){const t=this._lexer.token,n=this.parseDescription(),r=this.parseName(),a=this.parseArgumentDefs();this.expectToken(N.COLON);const i=this.parseTypeReference(),o=this.parseConstDirectives();return this.node(t,{kind:G.FIELD_DEFINITION,description:n,name:r,arguments:a,type:i,directives:o});}/**
|
|
578
|
+
* ArgumentsDefinition : ( InputValueDefinition+ )
|
|
579
|
+
*
|
|
580
|
+
* @internal
|
|
581
|
+
*/parseArgumentDefs(){return this.optionalMany(N.PAREN_L,this.parseInputValueDef,N.PAREN_R);}/**
|
|
582
|
+
* InputValueDefinition :
|
|
583
|
+
* - Description? Name : Type DefaultValue? Directives[Const]?
|
|
584
|
+
*
|
|
585
|
+
* @internal
|
|
586
|
+
*/parseInputValueDef(){const t=this._lexer.token,n=this.parseDescription(),r=this.parseName();this.expectToken(N.COLON);const a=this.parseTypeReference();let i;this.expectOptionalToken(N.EQUALS)&&(i=this.parseConstValueLiteral());const o=this.parseConstDirectives();return this.node(t,{kind:G.INPUT_VALUE_DEFINITION,description:n,name:r,type:a,defaultValue:i,directives:o});}/**
|
|
587
|
+
* InterfaceTypeDefinition :
|
|
588
|
+
* - Description? interface Name Directives[Const]? FieldsDefinition?
|
|
589
|
+
*
|
|
590
|
+
* @internal
|
|
591
|
+
*/parseInterfaceTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("interface");const r=this.parseName(),a=this.parseImplementsInterfaces(),i=this.parseConstDirectives(),o=this.parseFieldsDefinition();return this.node(t,{kind:G.INTERFACE_TYPE_DEFINITION,description:n,name:r,interfaces:a,directives:i,fields:o});}/**
|
|
592
|
+
* UnionTypeDefinition :
|
|
593
|
+
* - Description? union Name Directives[Const]? UnionMemberTypes?
|
|
594
|
+
*
|
|
595
|
+
* @internal
|
|
596
|
+
*/parseUnionTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("union");const r=this.parseName(),a=this.parseConstDirectives(),i=this.parseUnionMemberTypes();return this.node(t,{kind:G.UNION_TYPE_DEFINITION,description:n,name:r,directives:a,types:i});}/**
|
|
597
|
+
* UnionMemberTypes :
|
|
598
|
+
* - = `|`? NamedType
|
|
599
|
+
* - UnionMemberTypes | NamedType
|
|
600
|
+
*
|
|
601
|
+
* @internal
|
|
602
|
+
*/parseUnionMemberTypes(){return this.expectOptionalToken(N.EQUALS)?this.delimitedMany(N.PIPE,this.parseNamedType):[];}/**
|
|
603
|
+
* EnumTypeDefinition :
|
|
604
|
+
* - Description? enum Name Directives[Const]? EnumValuesDefinition?
|
|
605
|
+
*
|
|
606
|
+
* @internal
|
|
607
|
+
*/parseEnumTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("enum");const r=this.parseName(),a=this.parseConstDirectives(),i=this.parseEnumValuesDefinition();return this.node(t,{kind:G.ENUM_TYPE_DEFINITION,description:n,name:r,directives:a,values:i});}/**
|
|
608
|
+
* ```
|
|
609
|
+
* EnumValuesDefinition : { EnumValueDefinition+ }
|
|
610
|
+
* ```
|
|
611
|
+
*
|
|
612
|
+
* @internal
|
|
613
|
+
*/parseEnumValuesDefinition(){return this.optionalMany(N.BRACE_L,this.parseEnumValueDefinition,N.BRACE_R);}/**
|
|
614
|
+
* EnumValueDefinition : Description? EnumValue Directives[Const]?
|
|
615
|
+
*
|
|
616
|
+
* @internal
|
|
617
|
+
*/parseEnumValueDefinition(){const t=this._lexer.token,n=this.parseDescription(),r=this.parseEnumValueName(),a=this.parseConstDirectives();return this.node(t,{kind:G.ENUM_VALUE_DEFINITION,description:n,name:r,directives:a});}/**
|
|
618
|
+
* EnumValue : Name but not `true`, `false` or `null`
|
|
619
|
+
*
|
|
620
|
+
* @internal
|
|
621
|
+
*/parseEnumValueName(){if(this._lexer.token.value==="true"||this._lexer.token.value==="false"||this._lexer.token.value==="null")throw Me(this._lexer.source,this._lexer.token.start,`${Pn(this._lexer.token)} is reserved and cannot be used for an enum value.`);return this.parseName();}/**
|
|
622
|
+
* InputObjectTypeDefinition :
|
|
623
|
+
* - Description? input Name Directives[Const]? InputFieldsDefinition?
|
|
624
|
+
*
|
|
625
|
+
* @internal
|
|
626
|
+
*/parseInputObjectTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("input");const r=this.parseName(),a=this.parseConstDirectives(),i=this.parseInputFieldsDefinition();return this.node(t,{kind:G.INPUT_OBJECT_TYPE_DEFINITION,description:n,name:r,directives:a,fields:i});}/**
|
|
627
|
+
* ```
|
|
628
|
+
* InputFieldsDefinition : { InputValueDefinition+ }
|
|
629
|
+
* ```
|
|
630
|
+
*
|
|
631
|
+
* @internal
|
|
632
|
+
*/parseInputFieldsDefinition(){return this.optionalMany(N.BRACE_L,this.parseInputValueDef,N.BRACE_R);}/**
|
|
633
|
+
* TypeSystemExtension :
|
|
634
|
+
* - SchemaExtension
|
|
635
|
+
* - TypeExtension
|
|
636
|
+
*
|
|
637
|
+
* TypeExtension :
|
|
638
|
+
* - ScalarTypeExtension
|
|
639
|
+
* - ObjectTypeExtension
|
|
640
|
+
* - InterfaceTypeExtension
|
|
641
|
+
* - UnionTypeExtension
|
|
642
|
+
* - EnumTypeExtension
|
|
643
|
+
* - InputObjectTypeDefinition
|
|
644
|
+
* - DirectiveDefinitionExtension
|
|
645
|
+
*
|
|
646
|
+
* @internal
|
|
647
|
+
*/parseTypeSystemExtension(){const t=this._lexer.lookahead();if(t.kind===N.NAME)switch(t.value){case"schema":return this.parseSchemaExtension();case"scalar":return this.parseScalarTypeExtension();case"type":return this.parseObjectTypeExtension();case"interface":return this.parseInterfaceTypeExtension();case"union":return this.parseUnionTypeExtension();case"enum":return this.parseEnumTypeExtension();case"input":return this.parseInputObjectTypeExtension();case"directive":if(this._options.experimentalDirectivesOnDirectiveDefinitions)return this.parseDirectiveDefinitionExtension();break;}throw this.unexpected(t);}/**
|
|
648
|
+
* ```
|
|
649
|
+
* SchemaExtension :
|
|
650
|
+
* - extend schema Directives[Const]? { OperationTypeDefinition+ }
|
|
651
|
+
* - extend schema Directives[Const]
|
|
652
|
+
* ```
|
|
653
|
+
*
|
|
654
|
+
* @internal
|
|
655
|
+
*/parseSchemaExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("schema");const n=this.parseConstDirectives(),r=this.optionalMany(N.BRACE_L,this.parseOperationTypeDefinition,N.BRACE_R);if(n.length===0&&r.length===0)throw this.unexpected();return this.node(t,{kind:G.SCHEMA_EXTENSION,directives:n,operationTypes:r});}/**
|
|
656
|
+
* ScalarTypeExtension :
|
|
657
|
+
* - extend scalar Name Directives[Const]
|
|
658
|
+
*
|
|
659
|
+
* @internal
|
|
660
|
+
*/parseScalarTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("scalar");const n=this.parseName(),r=this.parseConstDirectives();if(r.length===0)throw this.unexpected();return this.node(t,{kind:G.SCALAR_TYPE_EXTENSION,name:n,directives:r});}/**
|
|
661
|
+
* ObjectTypeExtension :
|
|
662
|
+
* - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition
|
|
663
|
+
* - extend type Name ImplementsInterfaces? Directives[Const]
|
|
664
|
+
* - extend type Name ImplementsInterfaces
|
|
665
|
+
*
|
|
666
|
+
* @internal
|
|
667
|
+
*/parseObjectTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("type");const n=this.parseName(),r=this.parseImplementsInterfaces(),a=this.parseConstDirectives(),i=this.parseFieldsDefinition();if(r.length===0&&a.length===0&&i.length===0)throw this.unexpected();return this.node(t,{kind:G.OBJECT_TYPE_EXTENSION,name:n,interfaces:r,directives:a,fields:i});}/**
|
|
668
|
+
* InterfaceTypeExtension :
|
|
669
|
+
* - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition
|
|
670
|
+
* - extend interface Name ImplementsInterfaces? Directives[Const]
|
|
671
|
+
* - extend interface Name ImplementsInterfaces
|
|
672
|
+
*
|
|
673
|
+
* @internal
|
|
674
|
+
*/parseInterfaceTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("interface");const n=this.parseName(),r=this.parseImplementsInterfaces(),a=this.parseConstDirectives(),i=this.parseFieldsDefinition();if(r.length===0&&a.length===0&&i.length===0)throw this.unexpected();return this.node(t,{kind:G.INTERFACE_TYPE_EXTENSION,name:n,interfaces:r,directives:a,fields:i});}/**
|
|
675
|
+
* UnionTypeExtension :
|
|
676
|
+
* - extend union Name Directives[Const]? UnionMemberTypes
|
|
677
|
+
* - extend union Name Directives[Const]
|
|
678
|
+
*
|
|
679
|
+
* @internal
|
|
680
|
+
*/parseUnionTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("union");const n=this.parseName(),r=this.parseConstDirectives(),a=this.parseUnionMemberTypes();if(r.length===0&&a.length===0)throw this.unexpected();return this.node(t,{kind:G.UNION_TYPE_EXTENSION,name:n,directives:r,types:a});}/**
|
|
681
|
+
* EnumTypeExtension :
|
|
682
|
+
* - extend enum Name Directives[Const]? EnumValuesDefinition
|
|
683
|
+
* - extend enum Name Directives[Const]
|
|
684
|
+
*
|
|
685
|
+
* @internal
|
|
686
|
+
*/parseEnumTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("enum");const n=this.parseName(),r=this.parseConstDirectives(),a=this.parseEnumValuesDefinition();if(r.length===0&&a.length===0)throw this.unexpected();return this.node(t,{kind:G.ENUM_TYPE_EXTENSION,name:n,directives:r,values:a});}/**
|
|
687
|
+
* InputObjectTypeExtension :
|
|
688
|
+
* - extend input Name Directives[Const]? InputFieldsDefinition
|
|
689
|
+
* - extend input Name Directives[Const]
|
|
690
|
+
*
|
|
691
|
+
* @internal
|
|
692
|
+
*/parseInputObjectTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("input");const n=this.parseName(),r=this.parseConstDirectives(),a=this.parseInputFieldsDefinition();if(r.length===0&&a.length===0)throw this.unexpected();return this.node(t,{kind:G.INPUT_OBJECT_TYPE_EXTENSION,name:n,directives:r,fields:a});}parseDirectiveDefinitionExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("directive"),this.expectToken(N.AT);const n=this.parseName(),r=this.parseConstDirectives();if(r.length===0)throw this.unexpected();return this.node(t,{kind:G.DIRECTIVE_EXTENSION,name:n,directives:r});}/**
|
|
693
|
+
* ```
|
|
694
|
+
* DirectiveDefinition :
|
|
695
|
+
* - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations
|
|
696
|
+
* ```
|
|
697
|
+
*
|
|
698
|
+
* @internal
|
|
699
|
+
*/parseDirectiveDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("directive"),this.expectToken(N.AT);const r=this.parseName(),a=this.parseArgumentDefs(),i=this._options.experimentalDirectivesOnDirectiveDefinitions?this.parseConstDirectives():[],o=this.expectOptionalKeyword("repeatable");this.expectKeyword("on");const s=this.parseDirectiveLocations();return this.node(t,{kind:G.DIRECTIVE_DEFINITION,description:n,name:r,arguments:a,directives:i,repeatable:o,locations:s});}/**
|
|
700
|
+
* DirectiveLocations :
|
|
701
|
+
* - `|`? DirectiveLocation
|
|
702
|
+
* - DirectiveLocations | DirectiveLocation
|
|
703
|
+
*
|
|
704
|
+
* @internal
|
|
705
|
+
*/parseDirectiveLocations(){return this.delimitedMany(N.PIPE,this.parseDirectiveLocation);}/*
|
|
706
|
+
* DirectiveLocation :
|
|
707
|
+
* - ExecutableDirectiveLocation
|
|
708
|
+
* - TypeSystemDirectiveLocation
|
|
709
|
+
*
|
|
710
|
+
* ExecutableDirectiveLocation : one of
|
|
711
|
+
* `QUERY`
|
|
712
|
+
* `MUTATION`
|
|
713
|
+
* `SUBSCRIPTION`
|
|
714
|
+
* `FIELD`
|
|
715
|
+
* `FRAGMENT_DEFINITION`
|
|
716
|
+
* `FRAGMENT_SPREAD`
|
|
717
|
+
* `INLINE_FRAGMENT`
|
|
718
|
+
*
|
|
719
|
+
* TypeSystemDirectiveLocation : one of
|
|
720
|
+
* `SCHEMA`
|
|
721
|
+
* `SCALAR`
|
|
722
|
+
* `OBJECT`
|
|
723
|
+
* `FIELD_DEFINITION`
|
|
724
|
+
* `ARGUMENT_DEFINITION`
|
|
725
|
+
* `INTERFACE`
|
|
726
|
+
* `UNION`
|
|
727
|
+
* `ENUM`
|
|
728
|
+
* `ENUM_VALUE`
|
|
729
|
+
* `INPUT_OBJECT`
|
|
730
|
+
* `INPUT_FIELD_DEFINITION`
|
|
731
|
+
* `DIRECTIVE_DEFINITION`
|
|
732
|
+
*/parseDirectiveLocation(){const t=this._lexer.token,n=this.parseName();if(Object.prototype.hasOwnProperty.call(Fr,n.value))return n;throw this.unexpected(t);}// Schema Coordinates
|
|
733
|
+
/**
|
|
734
|
+
* SchemaCoordinate :
|
|
735
|
+
* - Name
|
|
736
|
+
* - Name . Name
|
|
737
|
+
* - Name . Name ( Name : )
|
|
738
|
+
* - \@ Name
|
|
739
|
+
* - \@ Name ( Name : )
|
|
740
|
+
* @returns Parsed schema coordinate AST.
|
|
741
|
+
* @example
|
|
742
|
+
* ```ts
|
|
743
|
+
* import { Parser, Source } from 'graphql/language';
|
|
744
|
+
*
|
|
745
|
+
* const typeCoordinate = new Parser(new Source('User.name')).parseSchemaCoordinate();
|
|
746
|
+
* const directiveCoordinate = new Parser(new Source('@include(if:)')).parseSchemaCoordinate();
|
|
747
|
+
*
|
|
748
|
+
* typeCoordinate.name.value; // => 'User'
|
|
749
|
+
* typeCoordinate.memberName?.value; // => 'name'
|
|
750
|
+
* directiveCoordinate.name.value; // => 'deprecated'
|
|
751
|
+
* directiveCoordinate.argumentName?.value; // => 'reason'
|
|
752
|
+
* ```
|
|
753
|
+
*/parseSchemaCoordinate(){const t=this._lexer.token,n=this.expectOptionalToken(N.AT),r=this.parseName();let a;!n&&this.expectOptionalToken(N.DOT)&&(a=this.parseName());let i;return(n||a)&&this.expectOptionalToken(N.PAREN_L)&&(i=this.parseName(),this.expectToken(N.COLON),this.expectToken(N.PAREN_R)),n?i?this.node(t,{kind:G.DIRECTIVE_ARGUMENT_COORDINATE,name:r,argumentName:i}):this.node(t,{kind:G.DIRECTIVE_COORDINATE,name:r}):a?i?this.node(t,{kind:G.ARGUMENT_COORDINATE,name:r,fieldName:a,argumentName:i}):this.node(t,{kind:G.MEMBER_COORDINATE,name:r,memberName:a}):this.node(t,{kind:G.TYPE_COORDINATE,name:r});}// Core parsing utility functions
|
|
754
|
+
/**
|
|
755
|
+
* Returns a node that, if configured to do so, sets a "loc" field as a
|
|
756
|
+
* location object, used to identify the place in the source that created a
|
|
757
|
+
* given parsed object.
|
|
758
|
+
*
|
|
759
|
+
* @internal
|
|
760
|
+
*/node(t,n){return this._options.noLocation!==!0&&(n.loc=new Kl(t,this._lexer.lastToken,this._lexer.source)),n;}/**
|
|
761
|
+
* Determines if the next token is of a given kind
|
|
762
|
+
*
|
|
763
|
+
* @internal
|
|
764
|
+
*/peek(t){return this._lexer.token.kind===t;}/**
|
|
765
|
+
* If the next token is of the given kind, return that token after advancing the lexer.
|
|
766
|
+
* Otherwise, do not change the parser state and throw an error.
|
|
767
|
+
*
|
|
768
|
+
* @internal
|
|
769
|
+
*/expectToken(t){const n=this._lexer.token;if(n.kind===t)return this.advanceLexer(),n;throw Me(this._lexer.source,n.start,`Expected ${To(t)}, found ${Pn(n)}.`);}/**
|
|
770
|
+
* If the next token is of the given kind, return "true" after advancing the lexer.
|
|
771
|
+
* Otherwise, do not change the parser state and return "false".
|
|
772
|
+
*
|
|
773
|
+
* @internal
|
|
774
|
+
*/expectOptionalToken(t){return this._lexer.token.kind===t?(this.advanceLexer(),!0):!1;}/**
|
|
775
|
+
* If the next token is a given keyword, advance the lexer.
|
|
776
|
+
* Otherwise, do not change the parser state and throw an error.
|
|
777
|
+
*
|
|
778
|
+
* @internal
|
|
779
|
+
*/expectKeyword(t){const n=this._lexer.token;if(n.kind===N.NAME&&n.value===t)this.advanceLexer();else throw Me(this._lexer.source,n.start,`Expected "${t}", found ${Pn(n)}.`);}/**
|
|
780
|
+
* If the next token is a given keyword, return "true" after advancing the lexer.
|
|
781
|
+
* Otherwise, do not change the parser state and return "false".
|
|
782
|
+
*
|
|
783
|
+
* @internal
|
|
784
|
+
*/expectOptionalKeyword(t){const n=this._lexer.token;return n.kind===N.NAME&&n.value===t?(this.advanceLexer(),!0):!1;}/**
|
|
785
|
+
* Helper function for creating an error when an unexpected lexed token is encountered.
|
|
786
|
+
*
|
|
787
|
+
* @internal
|
|
788
|
+
*/unexpected(t){const n=t??this._lexer.token;return Me(this._lexer.source,n.start,`Unexpected ${Pn(n)}.`);}/**
|
|
789
|
+
* Returns a possibly empty list of parse nodes, determined by the parseFn.
|
|
790
|
+
* This list begins with a lex token of openKind and ends with a lex token of closeKind.
|
|
791
|
+
* Advances the parser to the next lex token after the closing token.
|
|
792
|
+
*
|
|
793
|
+
* @internal
|
|
794
|
+
*/any(t,n,r){this.expectToken(t);const a=[];for(;!this.expectOptionalToken(r);)a.push(n.call(this));return a;}/**
|
|
795
|
+
* Returns a list of parse nodes, determined by the parseFn.
|
|
796
|
+
* It can be empty only if open token is missing otherwise it will always return non-empty list
|
|
797
|
+
* that begins with a lex token of openKind and ends with a lex token of closeKind.
|
|
798
|
+
* Advances the parser to the next lex token after the closing token.
|
|
799
|
+
*
|
|
800
|
+
* @internal
|
|
801
|
+
*/optionalMany(t,n,r){if(this.expectOptionalToken(t)){const a=[];do a.push(n.call(this));while(!this.expectOptionalToken(r));return a;}return[];}/**
|
|
802
|
+
* Returns a non-empty list of parse nodes, determined by the parseFn.
|
|
803
|
+
* This list begins with a lex token of openKind and ends with a lex token of closeKind.
|
|
804
|
+
* Advances the parser to the next lex token after the closing token.
|
|
805
|
+
*
|
|
806
|
+
* @internal
|
|
807
|
+
*/many(t,n,r){this.expectToken(t);const a=[];do a.push(n.call(this));while(!this.expectOptionalToken(r));return a;}/**
|
|
808
|
+
* Returns a non-empty list of parse nodes, determined by the parseFn.
|
|
809
|
+
* This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind.
|
|
810
|
+
* Advances the parser to the next lex token after last item in the list.
|
|
811
|
+
*
|
|
812
|
+
* @internal
|
|
813
|
+
*/delimitedMany(t,n){this.expectOptionalToken(t);const r=[];do r.push(n.call(this));while(this.expectOptionalToken(t));return r;}advanceLexer(){const{maxTokens:t}=this._options,n=this._lexer.advance();if(n.kind!==N.EOF&&(++this._tokenCounter,t!==void 0&&this._tokenCounter>t))throw Me(this._lexer.source,n.start,`Document contains more that ${t} tokens. Parsing aborted.`);}}function Pn(e){const t=e.value;return To(e.kind)+(t!=null?` "${t}"`:"");}function To(e){return tu(e)?`"${e}"`:e;}function Tu(e){return`"${e.replace(Eu,Iu)}"`;}const Eu=/[\x00-\x1f\x22\x5c\x7f-\x9f]/g;function Iu(e){return xu[e.charCodeAt(0)];}const xu=["\\u0000","\\u0001","\\u0002","\\u0003","\\u0004","\\u0005","\\u0006","\\u0007","\\b","\\t","\\n","\\u000B","\\f","\\r","\\u000E","\\u000F","\\u0010","\\u0011","\\u0012","\\u0013","\\u0014","\\u0015","\\u0016","\\u0017","\\u0018","\\u0019","\\u001A","\\u001B","\\u001C","\\u001D","\\u001E","\\u001F","","",'\\"',"","","","","","","","","","","","","",// 2F
|
|
814
|
+
"","","","","","","","","","","","","","","","",// 3F
|
|
815
|
+
"","","","","","","","","","","","","","","","",// 4F
|
|
816
|
+
"","","","","","","","","","","","","\\\\","","","",// 5F
|
|
817
|
+
"","","","","","","","","","","","","","","","",// 6F
|
|
818
|
+
"","","","","","","","","","","","","","","","\\u007F","\\u0080","\\u0081","\\u0082","\\u0083","\\u0084","\\u0085","\\u0086","\\u0087","\\u0088","\\u0089","\\u008A","\\u008B","\\u008C","\\u008D","\\u008E","\\u008F","\\u0090","\\u0091","\\u0092","\\u0093","\\u0094","\\u0095","\\u0096","\\u0097","\\u0098","\\u0099","\\u009A","\\u009B","\\u009C","\\u009D","\\u009E","\\u009F"],ku=Object.freeze({});function Du(e,t,n=yo){const r=/* @__PURE__ */new Map();for(const g of Object.values(G))r.set(g,Nu(t,g));let a,i=Array.isArray(e),o=[e],s=-1,l=[],u=e,d,c;const p=[],y=[];do{s++;const g=s===o.length,v=g&&l.length!==0;if(g){if(d=y.length===0?void 0:p[p.length-1],u=c,c=y.pop(),v)if(i){u=u.slice();let E=0;for(const[A,I]of l){const T=A-E;I===null?(u.splice(T,1),E++):u[T]=I;}}else{u={...u};for(const[E,A]of l)u[E]=A;}s=a.index,o=a.keys,l=a.edits,i=a.inArray,a=a.prev;}else if(c){if(d=i?s:o[s],u=c[d],u==null)continue;p.push(d);}let w;if(!Array.isArray(u)){var b,m;hi(u)||Sn(!1,`Invalid AST Node: ${ma(u)}.`);const E=g?(b=r.get(u.kind))===null||b===void 0?void 0:b.leave:(m=r.get(u.kind))===null||m===void 0?void 0:m.enter;if(w=E==null?void 0:E.call(t,u,d,c,p,y),w===ku)break;if(w===!1){if(!g){p.pop();continue;}}else if(w!==void 0&&(l.push([d,w]),!g))if(hi(w))u=w;else{p.pop();continue;}}if(w===void 0&&v&&l.push([d,u]),g)p.pop();else{var h;a={inArray:i,index:s,keys:o,edits:l,prev:a},i=Array.isArray(u),o=i?u:(h=n[u.kind])!==null&&h!==void 0?h:[],s=-1,l=[],c&&y.push(c),c=u;}}while(a!==void 0);return l.length!==0?l[l.length-1][1]:e;}function Nu(e,t){const n=e[t];return typeof n=="object"?n:typeof n=="function"?{enter:n,leave:void 0}:{enter:e.enter,leave:e.leave};}function Lu(e){return Du(e,_u);}const Pu=80,_u={Name:{leave:e=>e.value},Variable:{leave:e=>"$"+e.name},// Document
|
|
819
|
+
Document:{leave:e=>B(e.definitions,`
|
|
820
|
+
|
|
821
|
+
`)},OperationDefinition:{leave(e){const t=Er(e.variableDefinitions)?X(`(
|
|
822
|
+
`,B(e.variableDefinitions,`
|
|
823
|
+
`),`
|
|
824
|
+
)`):X("(",B(e.variableDefinitions,", "),")"),n=X("",e.description,`
|
|
825
|
+
`)+B([e.operation,B([e.name,t]),B(e.directives," ")]," ");return(n==="query"?"":n+" ")+e.selectionSet;}},VariableDefinition:{leave:({variable:e,type:t,defaultValue:n,directives:r,description:a})=>X("",a,`
|
|
826
|
+
`)+e+": "+t+X(" = ",n)+X(" ",B(r," "))},SelectionSet:{leave:({selections:e})=>Ye(e)},Field:{leave({alias:e,name:t,arguments:n,directives:r,selectionSet:a}){const i=X("",e,": ")+t;let o=i+X("(",B(n,", "),")");return o.length>Pu&&(o=i+X(`(
|
|
827
|
+
`,On(B(n,`
|
|
828
|
+
`)),`
|
|
829
|
+
)`)),B([o,B(r," "),a]," ");}},Argument:{leave:({name:e,value:t})=>e+": "+t},// Fragments
|
|
830
|
+
FragmentSpread:{leave:({name:e,directives:t})=>"..."+e+X(" ",B(t," "))},InlineFragment:{leave:({typeCondition:e,directives:t,selectionSet:n})=>B(["...",X("on ",e),B(t," "),n]," ")},FragmentDefinition:{leave:({name:e,typeCondition:t,variableDefinitions:n,directives:r,selectionSet:a,description:i})=>X("",i,`
|
|
831
|
+
`)+// Note: fragment variable definitions are experimental and may be changed
|
|
832
|
+
// or removed in the future.
|
|
833
|
+
`fragment ${e}${X("(",B(n,", "),")")} on ${t} ${X("",B(r," ")," ")}`+a},// Value
|
|
834
|
+
IntValue:{leave:({value:e})=>e},FloatValue:{leave:({value:e})=>e},StringValue:{leave:({value:e,block:t})=>t?Jl(e):Tu(e)},BooleanValue:{leave:({value:e})=>e?"true":"false"},NullValue:{leave:()=>"null"},EnumValue:{leave:({value:e})=>e},ListValue:{leave:({values:e})=>"["+B(e,", ")+"]"},ObjectValue:{leave:({fields:e})=>"{"+B(e,", ")+"}"},ObjectField:{leave:({name:e,value:t})=>e+": "+t},// Directive
|
|
835
|
+
Directive:{leave:({name:e,arguments:t})=>"@"+e+X("(",B(t,", "),")")},// Type
|
|
836
|
+
NamedType:{leave:({name:e})=>e},ListType:{leave:({type:e})=>"["+e+"]"},NonNullType:{leave:({type:e})=>e+"!"},// Type System Definitions
|
|
837
|
+
SchemaDefinition:{leave:({description:e,directives:t,operationTypes:n})=>X("",e,`
|
|
838
|
+
`)+B(["schema",B(t," "),Ye(n)]," ")},OperationTypeDefinition:{leave:({operation:e,type:t})=>e+": "+t},ScalarTypeDefinition:{leave:({description:e,name:t,directives:n})=>X("",e,`
|
|
839
|
+
`)+B(["scalar",t,B(n," ")]," ")},ObjectTypeDefinition:{leave:({description:e,name:t,interfaces:n,directives:r,fields:a})=>X("",e,`
|
|
840
|
+
`)+B(["type",t,X("implements ",B(n," & ")),B(r," "),Ye(a)]," ")},FieldDefinition:{leave:({description:e,name:t,arguments:n,type:r,directives:a})=>X("",e,`
|
|
841
|
+
`)+t+(Er(n)?X(`(
|
|
842
|
+
`,On(B(n,`
|
|
843
|
+
`)),`
|
|
844
|
+
)`):X("(",B(n,", "),")"))+": "+r+X(" ",B(a," "))},InputValueDefinition:{leave:({description:e,name:t,type:n,defaultValue:r,directives:a})=>X("",e,`
|
|
845
|
+
`)+B([t+": "+n,X("= ",r),B(a," ")]," ")},InterfaceTypeDefinition:{leave:({description:e,name:t,interfaces:n,directives:r,fields:a})=>X("",e,`
|
|
846
|
+
`)+B(["interface",t,X("implements ",B(n," & ")),B(r," "),Ye(a)]," ")},UnionTypeDefinition:{leave:({description:e,name:t,directives:n,types:r})=>X("",e,`
|
|
847
|
+
`)+B(["union",t,B(n," "),X("= ",B(r," | "))]," ")},EnumTypeDefinition:{leave:({description:e,name:t,directives:n,values:r})=>X("",e,`
|
|
848
|
+
`)+B(["enum",t,B(n," "),Ye(r)]," ")},EnumValueDefinition:{leave:({description:e,name:t,directives:n})=>X("",e,`
|
|
849
|
+
`)+B([t,B(n," ")]," ")},InputObjectTypeDefinition:{leave:({description:e,name:t,directives:n,fields:r})=>X("",e,`
|
|
850
|
+
`)+B(["input",t,B(n," "),Ye(r)]," ")},DirectiveDefinition:{leave:({description:e,name:t,arguments:n,directives:r,repeatable:a,locations:i})=>X("",e,`
|
|
851
|
+
`)+"directive @"+t+(Er(n)?X(`(
|
|
852
|
+
`,On(B(n,`
|
|
853
|
+
`)),`
|
|
854
|
+
)`):X("(",B(n,", "),")"))+X(" ",B(r," "))+(a?" repeatable":"")+" on "+B(i," | ")},SchemaExtension:{leave:({directives:e,operationTypes:t})=>B(["extend schema",B(e," "),Ye(t)]," ")},ScalarTypeExtension:{leave:({name:e,directives:t})=>B(["extend scalar",e,B(t," ")]," ")},ObjectTypeExtension:{leave:({name:e,interfaces:t,directives:n,fields:r})=>B(["extend type",e,X("implements ",B(t," & ")),B(n," "),Ye(r)]," ")},InterfaceTypeExtension:{leave:({name:e,interfaces:t,directives:n,fields:r})=>B(["extend interface",e,X("implements ",B(t," & ")),B(n," "),Ye(r)]," ")},UnionTypeExtension:{leave:({name:e,directives:t,types:n})=>B(["extend union",e,B(t," "),X("= ",B(n," | "))]," ")},EnumTypeExtension:{leave:({name:e,directives:t,values:n})=>B(["extend enum",e,B(t," "),Ye(n)]," ")},InputObjectTypeExtension:{leave:({name:e,directives:t,fields:n})=>B(["extend input",e,B(t," "),Ye(n)]," ")},DirectiveExtension:{leave:({name:e,directives:t})=>B(["extend directive @"+e,B(t," ")]," ")},// Schema Coordinates
|
|
855
|
+
TypeCoordinate:{leave:({name:e})=>e},MemberCoordinate:{leave:({name:e,memberName:t})=>B([e,X(".",t)])},ArgumentCoordinate:{leave:({name:e,fieldName:t,argumentName:n})=>B([e,X(".",t),X("(",n,":)")])},DirectiveCoordinate:{leave:({name:e})=>B(["@",e])},DirectiveArgumentCoordinate:{leave:({name:e,argumentName:t})=>B(["@",e,X("(",t,":)")])}};function B(e,t=""){var n;return(n=e==null?void 0:e.filter(r=>r).join(t))!==null&&n!==void 0?n:"";}function Ye(e){return X(`{
|
|
856
|
+
`,On(B(e,`
|
|
857
|
+
`)),`
|
|
858
|
+
}`);}function X(e,t,n=""){return t!=null&&t!==""?e+t+n:"";}function On(e){return X(" ",e.replace(/\n/g,`
|
|
859
|
+
`));}function Er(e){var t;return(t=e==null?void 0:e.some(n=>n.includes(`
|
|
860
|
+
`)))!==null&&t!==void 0?t:!1;}const gi="Accept",Ur="Content-Type",Wr="application/json",Eo="application/graphql-response+json",vi=e=>e.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),Cu=e=>{const t=e.toLowerCase();return t.includes(Eo)||t.includes(Wr);},wi=e=>{try{if(Array.isArray(e))return{_tag:"Batch",executionResults:e.map(Ai)};if(Rn(e))return{_tag:"Single",executionResult:Ai(e)};throw new Error(`Invalid execution result: result is not object or array.
|
|
861
|
+
Got:
|
|
862
|
+
${String(e)}`);}catch(t){return t;}},Ai=e=>{if(typeof e!="object"||e===null)throw new Error("Invalid execution result: result is not object");let t,n,r;if("errors"in e){if(!Rn(e.errors)&&!Array.isArray(e.errors))throw new Error("Invalid execution result: errors is not plain object OR array");t=e.errors;}if("data"in e){if(!Rn(e.data)&&e.data!==null)throw new Error("Invalid execution result: data is not plain object");n=e.data;}if("extensions"in e){if(!Rn(e.extensions))throw new Error("Invalid execution result: extensions is not plain object");r=e.extensions;}return{data:n,errors:t,extensions:r};},Mu=e=>e._tag==="Batch"?e.executionResults.some(Ti):Ti(e.executionResult),Ti=e=>Array.isArray(e.errors)?e.errors.length>0:!!e.errors,Io=e=>typeof e=="object"&&e!==null&&"kind"in e&&e.kind===G.OPERATION_DEFINITION,Ru=e=>{var r;let t;const n=e.definitions.filter(Io);return n.length===1&&(t=(r=n[0].name)==null?void 0:r.value),t;},Su=e=>{let t=!1;const n=e.definitions.filter(Io);return n.length===1&&(t=n[0].operation==="mutation"),t;},Ir=(e,t)=>{const n=typeof e=="string"||"kind"in e?e:String(e),r=typeof n=="string"?n:Lu(n);let a=!1,i;if(t)return{expression:r,isMutation:a,operationName:i};const o=Fl(()=>typeof n=="string"?wu(n):n);return o instanceof Error?{expression:r,isMutation:a,operationName:i}:(i=Ru(o),a=Su(o),{expression:r,operationName:i,isMutation:a});},ya=JSON,xr=async e=>{const t={...e,method:e.request._tag==="Single"?e.request.document.isMutation?"POST":pi(e.method??"post"):e.request.hasMutations?"POST":pi(e.method??"post"),fetchOptions:{...e.fetchOptions,errorPolicy:e.fetchOptions.errorPolicy??"none"}},r=await qu(t.method)(t),a=await r.text();let i;try{i=Ou(a,r.headers.get(Ur),e.fetchOptions.jsonSerializer??ya);}catch(s){i=s;}const o={status:r.status,headers:r.headers,body:a};if(!r.ok){if(i instanceof Error)return new Dt({...o},{query:e.request._tag==="Single"?e.request.document.expression:e.request.query,variables:e.request.variables});const s=i._tag==="Batch"?{...i.executionResults,...o}:{...i.executionResult,...o};return new Dt(s,{query:e.request._tag==="Single"?e.request.document.expression:e.request.query,variables:e.request.variables});}if(i instanceof Error)throw i;if(Mu(i)&&t.fetchOptions.errorPolicy==="none"){const s=i._tag==="Batch"?{...i.executionResults,...o}:{...i.executionResult,...o};return new Dt(s,{query:e.request._tag==="Single"?e.request.document.expression:e.request.query,variables:e.request.variables});}switch(i._tag){case"Single":return{...o,...Ei(t)(i.executionResult)};case"Batch":return{...o,data:i.executionResults.map(Ei(t))};default:pa(i);}},Ei=e=>t=>({extensions:t.extensions,data:t.data,errors:e.fetchOptions.errorPolicy==="all"?t.errors:void 0}),Ou=(e,t,n)=>t&&Cu(t)?wi(n.parse(e)):wi(e),qu=e=>async t=>{const n=new Headers(t.headers);let r=null,a;n.has(gi)||n.set(gi,[Eo,Wr].join(", ")),e==="POST"?(a=(t.fetchOptions.jsonSerializer??ya).stringify(Bu(t)),typeof a=="string"&&!n.has(Ur)&&n.set(Ur,Wr)):r=Fu(t);const i={method:e,headers:n,body:a,...t.fetchOptions};let o=new URL(t.url),s=i;if(t.middleware){const u=await Promise.resolve(t.middleware({...i,url:t.url,operationName:t.request._tag==="Single"?t.request.document.operationName:void 0,variables:t.request.variables})),{url:d,...c}=u;o=new URL(d),s=c;}return r&&r.forEach((u,d)=>{o.searchParams.append(d,u);}),await(t.fetch??fetch)(o,s);},Bu=e=>{switch(e.request._tag){case"Single":return{query:e.request.document.expression,variables:e.request.variables,operationName:e.request.document.operationName};case"Batch":return po(e.request.query,e.request.variables??[]).map(([t,n])=>({query:t,variables:n}));default:throw pa(e.request);}},Fu=e=>{var r;const t=e.fetchOptions.jsonSerializer??ya,n=new URLSearchParams();switch(e.request._tag){case"Single":return n.append("query",vi(e.request.document.expression)),e.request.variables&&n.append("variables",t.stringify(e.request.variables)),e.request.document.operationName&&n.append("operationName",e.request.document.operationName),n;case"Batch":{const a=((r=e.request.variables)==null?void 0:r.map(s=>t.stringify(s)))??[],i=e.request.query.map(vi),o=po(i,a).map(([s,l])=>({query:s,variables:l}));return n.append("query",t.stringify(o)),n;}default:throw pa(e.request);}};class Vu{constructor(t,n={}){oe(this,"url");oe(this,"requestConfig");/**
|
|
863
|
+
* Send a GraphQL query to the server.
|
|
864
|
+
*/oe(this,"rawRequest",async(...t)=>{const[n,r,a]=t,i=Wl(n,r,a),{headers:o,fetch:s=globalThis.fetch,method:l="POST",requestMiddleware:u,responseMiddleware:d,excludeOperationName:c,...p}=this.requestConfig,{url:y}=this;i.signal!==void 0&&(p.signal=i.signal);const b=Ir(i.query,c),m=await xr({url:y,request:{_tag:"Single",document:b,variables:i.variables},headers:{...Bt(Ar(o)),...Bt(i.requestHeaders)},fetch:s,method:l,fetchOptions:p,middleware:u});if(d&&(await d(m,{operationName:b.operationName,variables:r,url:this.url})),m instanceof Error)throw m;return m;});this.url=t,this.requestConfig=n;}async request(t,...n){const[r,a]=n,i=Uu(t,r,a),{headers:o,fetch:s=globalThis.fetch,method:l="POST",requestMiddleware:u,responseMiddleware:d,excludeOperationName:c,...p}=this.requestConfig,{url:y}=this;i.signal!==void 0&&(p.signal=i.signal);const b=Ir(i.document,c),m=await xr({url:y,request:{_tag:"Single",document:b,variables:i.variables},headers:{...Bt(Ar(o)),...Bt(i.requestHeaders)},fetch:s,method:l,fetchOptions:p,middleware:u});if(d&&(await d(m,{operationName:b.operationName,variables:i.variables,url:this.url})),m instanceof Error)throw m;return m.data;}async batchRequests(t,n){const r=Ul(t,n),{headers:a,excludeOperationName:i,...o}=this.requestConfig;r.signal!==void 0&&(o.signal=r.signal);const s=r.documents.map(({document:p})=>Ir(p,i)),l=s.map(({expression:p})=>p),u=s.some(({isMutation:p})=>p),d=r.documents.map(({variables:p})=>p),c=await xr({url:this.url,request:{_tag:"Batch",operationName:void 0,query:l,hasMutations:u,variables:d},headers:{...Bt(Ar(a)),...Bt(r.requestHeaders)},fetch:this.requestConfig.fetch??globalThis.fetch,method:this.requestConfig.method||"POST",fetchOptions:o,middleware:this.requestConfig.requestMiddleware});if(this.requestConfig.responseMiddleware&&(await this.requestConfig.responseMiddleware(c,{operationName:void 0,variables:d,url:this.url})),c instanceof Error)throw c;return c.data;}setHeaders(t){return this.requestConfig.headers=t,this;}/**
|
|
865
|
+
* Attach a header to the client. All subsequent requests will have this header.
|
|
866
|
+
*/setHeader(t,n){const{headers:r}=this.requestConfig;return r?r[t]=n:this.requestConfig.headers={[t]:n},this;}/**
|
|
867
|
+
* Change the client endpoint. All subsequent requests will send to this endpoint.
|
|
868
|
+
*/setEndpoint(t){return this.url=t,this;}}const Uu=(e,t,n)=>e.document?e:{document:e,variables:t,requestHeaders:n,signal:void 0};function Be(e,t){if(!e)throw new Error(t);}var ie=10n**18n,_e=1000000n,xo=1000n,In=950000n;function ar(e){return xt(eo(Ws("address, address, uint24, int24, address"),[e.currency0,e.currency1,e.fee,e.tickSpacing,e.hooks]));}var Wu=class ko{/**
|
|
869
|
+
* Creates a new AegisMarket instance.
|
|
870
|
+
*
|
|
871
|
+
* @param params - Market parameters
|
|
872
|
+
* @throws Error if market is not initialized or has invalid state
|
|
873
|
+
*/constructor(t){/**
|
|
874
|
+
* The pool identifier (keccak256 hash of PoolKey).
|
|
875
|
+
*/oe(this,"poolId");/**
|
|
876
|
+
* The Uniswap V4 PoolKey identifying the underlying pool.
|
|
877
|
+
*/oe(this,"poolKey");/**
|
|
878
|
+
* Whether the market has been initialized in the engine.
|
|
879
|
+
*/oe(this,"initialized");/**
|
|
880
|
+
* Total borrowed principal in L-units (before applying borrow index).
|
|
881
|
+
*/oe(this,"totalRlBorrowed");/**
|
|
882
|
+
* Timestamp of the last interest accrual.
|
|
883
|
+
*/oe(this,"lastAccrue");/**
|
|
884
|
+
* Protocol fee rate in pips (0-1,000,000 = 0%-100%).
|
|
885
|
+
*/oe(this,"protocolFeePips");/**
|
|
886
|
+
* MAX LTV threshold in pips (micro-liquidation start, lock guard).
|
|
887
|
+
*/oe(this,"maxLtvPips");/**
|
|
888
|
+
* HARD LTV threshold in pips (full repay required, max keeper fee).
|
|
889
|
+
*/oe(this,"hardLtvPips");/**
|
|
890
|
+
* Borrow index in WAD precision (1e18).
|
|
891
|
+
* Used to compute actual debt: actualDebt = rL * borrowIndexWad / WAD
|
|
892
|
+
*/oe(this,"borrowIndexWad");/**
|
|
893
|
+
* Total lender equity in L-units with WAD precision.
|
|
894
|
+
* Represents lender deposits + accumulated fees.
|
|
895
|
+
*/oe(this,"equityLWad");/**
|
|
896
|
+
* Address of the variable interest rate oracle.
|
|
897
|
+
*/oe(this,"rateOracle");/**
|
|
898
|
+
* Full utilization rate cached from the rate oracle.
|
|
899
|
+
*/oe(this,"fullUtilizationRate");/**
|
|
900
|
+
* Fee residues pending reinvestment as liquidity.
|
|
901
|
+
* One-sided accumulations not yet minted to equity.
|
|
902
|
+
*/oe(this,"residues");// Lazy-cached computed values
|
|
903
|
+
oe(this,"_utilizationPips");oe(this,"_borrowedLWad");Be(t.initialized,"AegisMarket: market not initialized"),Be(t.borrowIndexWad>=ie,"AegisMarket: borrowIndex must be >= WAD"),Be(t.maxLtvPips<t.hardLtvPips,"AegisMarket: maxLtv must be < hardLtv"),this.poolId=t.poolId,this.poolKey=t.poolKey,this.initialized=t.initialized,this.totalRlBorrowed=t.totalRlBorrowed,this.lastAccrue=t.lastAccrue,this.protocolFeePips=t.protocolFeePips,this.maxLtvPips=t.maxLtvPips,this.hardLtvPips=t.hardLtvPips,this.borrowIndexWad=t.borrowIndexWad,this.equityLWad=t.equityLWad,this.rateOracle=t.rateOracle,this.fullUtilizationRate=t.fullUtilizationRate,this.residues=t.residues;}/**
|
|
904
|
+
* Creates an AegisMarket from raw state returned by AegisStateView.
|
|
905
|
+
*
|
|
906
|
+
* @param state - Raw market state from contract
|
|
907
|
+
* @returns A new AegisMarket instance
|
|
908
|
+
*/static fromRaw(t){const n=ar(t.key);return new ko({poolId:n,poolKey:t.key,initialized:t.initialized,totalRlBorrowed:t.totalRlBorrowed,lastAccrue:t.lastAccrue,protocolFeePips:t.protocolFeePips,maxLtvPips:t.maxLtvPips,hardLtvPips:t.hardLtvPips,borrowIndexWad:t.borrowIndexWad,equityLWad:t.equityLWad,rateOracle:t.rateOracle,fullUtilizationRate:t.fullUtilizationRate,residues:t.residues});}/**
|
|
909
|
+
* Token0 address of the pool (lower address).
|
|
910
|
+
*/get currency0(){return this.poolKey.currency0;}/**
|
|
911
|
+
* Token1 address of the pool (higher address).
|
|
912
|
+
*/get currency1(){return this.poolKey.currency1;}/**
|
|
913
|
+
* Pool fee in pips.
|
|
914
|
+
*/get fee(){return this.poolKey.fee;}/**
|
|
915
|
+
* Pool tick spacing.
|
|
916
|
+
*/get tickSpacing(){return this.poolKey.tickSpacing;}/**
|
|
917
|
+
* Hook contract address.
|
|
918
|
+
*/get hooks(){return this.poolKey.hooks;}/**
|
|
919
|
+
* Total borrowed liquidity in WAD-scaled L-units.
|
|
920
|
+
* Computed as rL * borrowIndexWad.
|
|
921
|
+
*/get borrowedLWad(){return this._borrowedLWad===void 0&&(this._borrowedLWad=this.totalRlBorrowed*this.borrowIndexWad),this._borrowedLWad;}/**
|
|
922
|
+
* Market utilization rate in pips (0-1,000,000 = 0%-100%).
|
|
923
|
+
* Computed as borrowedLWad / equityLWad.
|
|
924
|
+
*/get utilizationPips(){return this._utilizationPips===void 0&&(this.equityLWad===0n?this._utilizationPips=0n:this._utilizationPips=this.borrowedLWad*_e/this.equityLWad),this._utilizationPips;}/**
|
|
925
|
+
* Per-share price in WAD precision.
|
|
926
|
+
* Computed as equityLWad / totalShares.
|
|
927
|
+
*
|
|
928
|
+
* Note: This requires totalShares which is stored in ERC6909.
|
|
929
|
+
* Returns WAD (1:1) if totalShares is not available.
|
|
930
|
+
*
|
|
931
|
+
* @param totalShares - Total supply of market shares (from ERC6909)
|
|
932
|
+
*/sharePriceWad(t){return t===0n?ie:this.equityLWad*ie/(t*ie);}/**
|
|
933
|
+
* Equity in L-units (without WAD scaling).
|
|
934
|
+
*/get equityL(){return this.equityLWad/ie;}/**
|
|
935
|
+
* Total borrowed in L-units (without WAD scaling).
|
|
936
|
+
*/get borrowedL(){return this.borrowedLWad/ie;}/**
|
|
937
|
+
* Available liquidity for borrowing (equityL - borrowedL).
|
|
938
|
+
*/get availableLiquidity(){const t=this.equityL,n=this.borrowedL;return t>n?t-n:0n;}/**
|
|
939
|
+
* Returns true if the market has any borrowed funds.
|
|
940
|
+
*/get hasBorrows(){return this.totalRlBorrowed>0n;}/**
|
|
941
|
+
* Returns true if the market has any equity.
|
|
942
|
+
*/get hasEquity(){return this.equityLWad>0n;}/**
|
|
943
|
+
* Checks if a given LTV is above the MAX threshold (liquidatable).
|
|
944
|
+
*
|
|
945
|
+
* @param ltvPips - LTV in pips to check
|
|
946
|
+
*/isAboveMaxLtv(t){return t>BigInt(this.maxLtvPips);}/**
|
|
947
|
+
* Checks if a given LTV is above the HARD threshold (requires full repay).
|
|
948
|
+
*
|
|
949
|
+
* @param ltvPips - LTV in pips to check
|
|
950
|
+
*/isAboveHardLtv(t){return t>BigInt(this.hardLtvPips);}/**
|
|
951
|
+
* Checks equality with another AegisMarket based on poolId.
|
|
952
|
+
*
|
|
953
|
+
* @param other - The other market to compare
|
|
954
|
+
*/equals(t){return this.poolId===t.poolId;}/**
|
|
955
|
+
* Returns the poolId as a hex string.
|
|
956
|
+
*/toString(){return this.poolId;}},ha=/* @__PURE__ */(e=>(e[e.ETHEREUM_MAINNET=1]="ETHEREUM_MAINNET",e[e.BSC_MAINNET=56]="BSC_MAINNET",e[e.UNICHAIN_MAINNET=130]="UNICHAIN_MAINNET",e[e.MONAD_MAINNET=143]="MONAD_MAINNET",e[e.UNICHAIN_SEPOLIA=1301]="UNICHAIN_SEPOLIA",e[e.XLAYER_MAINNET=196]="XLAYER_MAINNET",e[e.ROBINHOOD_MAINNET=4663]="ROBINHOOD_MAINNET",e[e.BASE_MAINNET=8453]="BASE_MAINNET",e[e.INK_MAINNET=57073]="INK_MAINNET",e))(ha||{}),$u=class extends Error{constructor(t){super(`Unsupported Aegis version: ${String(t)}.`);oe(this,"code","UNSUPPORTED_AEGIS_VERSION");oe(this,"version");this.name="UnsupportedAegisVersionError",this.version=t;}};function ba(e,t){if(!Object.hasOwn(e,t))throw new $u(t);return e[t];}var Hu={chainId:57073,version:"v1.0.3",subgraphUrl:"https://api.goldsky.com/api/public/project_cmudvdf1fjmdg010c3qe3am2d/subgraphs/aegis-engine-ink-calamari/1.0.3/gn",addresses:{aegisEngine:"0x2fC2f4D1EEf9C5F63cdfC13BE3b842cBda8eF946",aegisHook:"0x2F449fa3f078960313749Bc45FfCDE0987F790cC",aegisRouterV1:"0xf1d885bc797825a22be65a6e2dc7184adf24cc90",aegisStateView:"0x84e582430fabce9feb4cbad2b2e50c811a7f0fc3",vaultRegistry:"0x7d0d5C516Fe82a90D9e1ef328fA036a689ff6786",variableInterestRate:"0x7aFcee2e41d48ec819f482f73C8d4Abc41B9e488",oracleManager:"0x1afFbAd0CFAdefE38E60746B0AcdA672cD95bFFD",limitOrderManager:"0xdbce2BBEC18113DcBF89F7c209EA75A28BE30cbb",dynamicFeeManager:"0xbcf84976a9ae569dd82f2078aa4778702d6f566d",poolManager:"0x6E4723A612831AfB9f5B2a5aE22723c37aAB9560",positionManager:"0x2Fb62913fe4EE086E8F21949c5Deeb088752DC78",stateView:"0x9Bf3f07e41e05D658248467760C745E278EF6211",uniswapV4Quoter:"0x0739Cbf29d499e8c6C3c0b2e3bC2151E986AAA3c",permit2:"0x000000000022D473030F116dDEE9F6B43aC78BA3",weth9:"0x4200000000000000000000000000000000000006"}},Do=["aegisEngine","aegisHook","aegisRouterV1","aegisStateView","vaultRegistry","variableInterestRate","oracleManager","limitOrderManager","dynamicFeeManager","poolManager","positionManager","stateView","uniswapV4Quoter","permit2","weth9"],zu={1:{poolManager:"0x000000000004444c5dc75cB358380D2e3dE08A90",positionManager:"0xbd216513d74c8cf14cf4747e6aaa6420ff64ee9e",stateView:"0x7ffe42c4a5deea5b0fec41c94c136cf115597227",uniswapV4Quoter:"0x52f0e24d1c21c8a0cb1e5a5dd6198556bd9e1203",permit2:"0x000000000022D473030F116dDEE9F6B43aC78BA3",weth9:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"},56:{poolManager:"0x28e2Ea090877bF75740558f6BFB36A5ffeE9e9dF",positionManager:"0x7A4a5c919aE2541AeD11041A1AEeE68f1287f95b",stateView:"0xd13Dd3D6E93f276FAfc9Db9E6BB47C1180aeE0c4",uniswapV4Quoter:"0x9F75dD27D6664c475B90e105573E550ff69437B0",permit2:"0x000000000022D473030F116dDEE9F6B43aC78BA3",weth9:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"},130:{poolManager:"0x1F98400000000000000000000000000000000004",positionManager:"0x4529A01c7A0410167c5740C487A8DE60232617bf",stateView:"0x86e8631a016f9068c3f085faf484ee3f5fdee8f2",uniswapV4Quoter:"0x333e3c607b141b18ff6de9f258db6e77fe7491e0",permit2:"0x000000000022D473030F116dDEE9F6B43aC78BA3",weth9:"0x4200000000000000000000000000000000000006"},143:{poolManager:"0x188d586Ddcf52439676Ca21A244753fA19F9Ea8e",positionManager:"0x5b7eC4a94fF9beDb700fb82aB09d5846972F4016",stateView:"0x77395F3b2E73aE90843717371294fa97cC419D64",uniswapV4Quoter:"0xa222Dd357A9076d1091Ed6Aa2e16C9742dD26891",permit2:"0x000000000022D473030F116dDEE9F6B43aC78BA3",weth9:"0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A"},1301:{poolManager:"0x00b036b58a818b1bc34d502d3fe730db729e62ac",positionManager:"0xf969Aee60879C54bAAed9F3eD26147Db216Fd664",stateView:"0xc199f1072a74d4e905aba1a84d9a45e2546b6222",uniswapV4Quoter:"0x56dcd40a3f2d466f48e7f48bdbe5cc9b92ae4472",permit2:"0x000000000022D473030F116dDEE9F6B43aC78BA3",weth9:"0x4200000000000000000000000000000000000006"},196:{poolManager:"0x360E68faCcca8cA495c1B759Fd9EEe466db9FB32",positionManager:"0xcF1EAFC6928dC385A342E7C6491d371d2871458b",stateView:"0x76Fd297e2D437cd7f76d50F01AfE6160f86e9990",uniswapV4Quoter:"0x8928074ca1b241d8ec02815881c1af11e8bc5219",permit2:"0x000000000022D473030F116dDEE9F6B43aC78BA3",weth9:"0xe538905cf8410324e03A5A23C1c177a474D59b2b"},4663:{poolManager:"0x8366a39CC670B4001A1121B8F6A443A643e40951",positionManager:"0x58daec3116aae6D93017bAAea7749052E8a04fA7",stateView:"0xf3334192d15450cdd385c8b70e03f9a6bd9e673b",uniswapV4Quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",permit2:"0x000000000022D473030F116dDEE9F6B43aC78BA3",weth9:"0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73"},8453:{poolManager:"0x498581ff718922c3f8e6a244956af099b2652b2b",positionManager:"0x7c5f5a4bbd8fd63184577525326123b519429bdc",stateView:"0xa3c0c9b65bad0b08107aa264b0f3db444b867a71",uniswapV4Quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",permit2:"0x000000000022D473030F116dDEE9F6B43aC78BA3",weth9:"0x4200000000000000000000000000000000000006"},57073:{poolManager:"0x360E68faCcca8cA495c1B759Fd9EEe466db9FB32",positionManager:"0x1b35d13a2E2528f192637F14B05f0Dc0e7dEB566",stateView:"0x76fd297e2d437cd7f76d50f01afe6160f86e9990",uniswapV4Quoter:"0x3972c00f7ed4885e145823eb7c655375d275a1c5",permit2:"0x000000000022D473030F116dDEE9F6B43aC78BA3",weth9:"0x4200000000000000000000000000000000000006"}},$r={"v0.4.0":{defaults:{aegisEngine:"0x2DDEA3c59b90d808AA980e9e5a460FdB3c87ccB0",aegisHook:"0x3476b53425a786e57aA246839C1837a62fc21ACC",aegisRouterV1:"0x9641682F95baD3305C18c549a483F413d23dC72e",aegisStateView:"0x907f323c608FCd4d70D77a4d944B4bffbC7C10Ce",vaultRegistry:"0xe19414e5C3DB1596f583d18d3Ac5bb43CBabc50D",variableInterestRate:"0xCCDECda074d8411651AC1B8FD87c5CA7551f28F6",oracleManager:"0x708c46aB579B7a9eBA70D39a059664EA6FD91737",limitOrderManager:"0xCc7F9dC1C6BA855E2507c9C65910B48A7F6497C1",dynamicFeeManager:"0xEC2eD4784e6aE796A75Ef9E5d74269f09AFC482C"},deployments:{130:{subgraphUrl:"https://gateway.thegraph.com/api/deployments/id/Qma8j6Pi9raqeFFrAd8jjY2cSS8pq9ZENY7WoYaLUZJLPV"},1301:{subgraphUrl:"https://api.goldsky.com/api/public/project_clwg93ryvd0mi01u59udc0ypo/subgraphs/aegis-engine/0.4.0/gn"},196:{subgraphUrl:"https://api.studio.thegraph.com/query/61136/aegis-engine/v0.4.1",aegisOverrides:{aegisEngine:"0x1b0ed1d21b5AB3Db311C1aC386DC874081914935",aegisHook:"0xc54aC33a60BeED0c10C32D8E4434166AF68550cc",aegisRouterV1:"0xb2830032E19A85e03cDE678FF93Da659C90CAFe5",aegisStateView:"0xE962612Dc9dcC3a7666F5Fa6B014b3b1D9287D27",oracleManager:"0x355dAd86872DE8248538E487Ef8898e0a4E31f70",dynamicFeeManager:"0xA5571554A47deDEb667f91d60ADCb645a2Ef1780"}}}},"v1.0.2":{defaults:{aegisEngine:"0x4d9BDd0cdfF5DC9149C2DaE8377a3352790C50c9",aegisHook:"0x8f29BD5c8429730fA4C46e6295c4e679eDEdd0cC",aegisRouterV1:"0x00581261a1200956ea05d1810fF28ffd66D8E254",aegisStateView:"0xB6191c5f5983Bf5c9B993e405781B6E88449bDB6",vaultRegistry:"0x5cfB5e914ECb2809C19E89b8A1c41F3e57958D87",variableInterestRate:"0xE929011f14FA04ce4EeDDFf0aC1ef923D1e1df23",oracleManager:"0x6Bc6fe74B3C360E6D838295EeeC8F58eBBcE3e5C",limitOrderManager:"0x5985c41edF54cca8aa2e16c7a22e1eB59948068E",dynamicFeeManager:"0x5cC0F3f0933b465a37124403739c80bE857Ca45E"},deployments:{8453:{subgraphUrl:"https://gateway.thegraph.com/api/deployments/id/QmYUKyoefWbimcvDMt7NSqan9PDXacRFbZZrxet9eQSLwr"},1:{subgraphUrl:"https://gateway.thegraph.com/api/subgraphs/id/CGsJsB7XEW2be5ZFUHCn8YTQ9Uycq56Kj77Yzv3PqU7t"}}},"v1.0.3":{defaults:{aegisEngine:"0x1a22457422B9308AB0C0dC6cef8629e061716009",aegisHook:"0xe449E013004DB4a5681E9622ca10c5Ba0eA610cc",aegisRouterV1:"0xe2820f3DA0abC9C65B3727A7103E3F59c00D686E",aegisStateView:"0xD64A84C0C2F56F5fC1C87760926083130B3fE5E0",vaultRegistry:"0xbABfccADC23629DE0D7E73433ABFC6D986083B09",variableInterestRate:"0xa2D9846A73f1134962F366d991B2080d39a427AB",oracleManager:"0x6e9B305B99d2ac39158e5D4bb5d42012D631F9e4",limitOrderManager:"0xFA5062a51A30d29AAb423123E9449e95bc8dB3a1",dynamicFeeManager:"0xc307E55749941e6B0Fc0D7B487fF01198cA48bE1"},deployments:{56:{subgraphUrl:"https://gateway.thegraph.com/api/subgraphs/id/4rWoQWjyeobnaBVaveo8NdQFQYbhoFEzdYpaUX4s1yVA"},143:{subgraphUrl:"https://api.goldsky.com/api/public/project_cmudvdf1fjmdg010c3qe3am2d/subgraphs/aegis-engine-monad/1.0.3/gn"},4663:{subgraphUrl:"https://api.goldsky.com/api/public/project_cmudvdf1fjmdg010c3qe3am2d/subgraphs/aegis-engine-robinhood/1.0.3/gn"},57073:{subgraphUrl:"https://api.goldsky.com/api/public/project_cmudvdf1fjmdg010c3qe3am2d/subgraphs/aegis-engine-ink/1.0.3/gn"}}}};function St(e){return ba($r,e);}function bn(e){return`${ha[e]} (${e})`;}function Gu(e){return e.length===0?"(none)":e.map(bn).join(", ");}var No=[{name:"calamari",config:Hu}];function Lo(e,t,n="default"){if(St(t),n==="default")return;const r=No.find(({name:a,config:i})=>a===n&&i.chainId===e&&i.version===t);if(r)return r.config;throw new Error(`Aegis deployment ${n} is not deployed on chain ${bn(e)} for ${t}.`);}function Po(e,t){const n=Qu(e).map(r=>({name:"default",version:r,addresses:ga(e,r)}));for(const{name:r,config:a}of No)a.chainId===e&&n.push({name:r,version:a.version,addresses:a.addresses});return n.filter(({addresses:r})=>r.aegisHook.toLowerCase()===t.toLowerCase());}function ju(e,t,n){return{chainId:e,version:t,addresses:ga(e,t,n),subgraphUrl:_o(e,t,n)};}function Ku(e,t,n){n!==void 0&&St(n);const r=Po(e,t);if(r.length!==1)throw new Error(`Aegis hook ${t} has ${r.length} configured deployments on chain ${e}.`);const a=r[0];if(n!==void 0&&a.version!==n)throw new Error(`Aegis hook ${t} uses version ${a.version}, not ${n}.`);return ju(e,a.version,{deployment:a.name});}function Hr(e,t,n){const r=n?je(e,n.version,n):void 0,a=Po(e,t);if(a.length>1)throw new Error(`Aegis hook ${t} has ${a.length} configured deployments on chain ${e}.`);const i=a[0];if(!i){if(!r)throw new Error(`Aegis hook ${t} has no configured deployment on chain ${e}.`);return xn(r,t),r;}const o={chainId:e,version:i.version,addresses:{...i.addresses}};if(r&&(r.version!==o.version||Do.some(l=>r.addresses[l].toLowerCase()!==o.addresses[l].toLowerCase())))throw new Error(`Aegis deployment does not match the configured deployment for hook ${t} on chain ${e}.`);return o;}function xn(e,t){if(t.toLowerCase()!==e.addresses.aegisHook.toLowerCase())throw new Error(`Market hook ${t} does not match Aegis deployment hook ${e.addresses.aegisHook}.`);}function ga(e,t,n){const r=Lo(e,t,n==null?void 0:n.deployment);if(r)return{...r.addresses};const a=St(t),i=a.deployments[e];if(!i)throw new Error(`Aegis ${t} is not deployed on chain ${bn(e)}. Supported chains for ${t}: ${Gu(Yu(t))}.`);const o=zu[e];return{...a.defaults,...i.aegisOverrides,...o};}function je(e,t,n){if(St(t),!n)return{chainId:e,version:t,addresses:ga(e,t)};if(n.chainId!==e)throw new Error(`Aegis deployment chainId ${n.chainId} does not match requested chainId ${e}.`);if(n.version!==t)throw new Error(`Aegis deployment version ${n.version} does not match requested version ${t}.`);const r=n.addresses;if(!r||typeof r!="object")throw new Error("Aegis deployment addresses must be a complete ChainAddresses object.");const a=r;for(const i of Do){const o=a[i];if(typeof o!="string"||!sn(o,{strict:!1}))throw new Error(`Aegis deployment address ${i} must be a valid EVM address.`);if(i!=="uniswapV4Quoter"&&o.toLowerCase()===ke)throw new Error(`Aegis deployment address ${i} must not be the zero address.`);}return{chainId:e,version:t,addresses:{...n.addresses}};}function _o(e,t,n){const r=typeof n=="string"?void 0:n,a=typeof n=="string"?n:r==null?void 0:r.graphApiKey,i=Lo(e,t,r==null?void 0:r.deployment);let o=i==null?void 0:i.subgraphUrl;if(!o){const l=St(t).deployments[e];if(!l)throw new Error(`Aegis ${t} is not deployed on chain ${bn(e)}.`);if(!l.subgraphUrl)throw new Error(`Subgraph URL is not configured for Aegis ${t} on chain ${bn(e)}. The contracts may be deployed but the subgraph has not yet been published.`);o=l.subgraphUrl;}return!a||!o.startsWith("https://gateway.thegraph.com/api/")?o:o.replace("https://gateway.thegraph.com/api/",`https://gateway.thegraph.com/api/${encodeURIComponent(a)}/`);}function Yu(e){return Object.keys(St(e).deployments).map(t=>Number(t));}function Qu(e){const t=Object.keys($r);return e===void 0?t:t.filter(n=>$r[n].deployments[e]!==void 0);}function va(e,t){return St(t).deployments[e]!==void 0;}function kr(e){if(e<0n)throw new Error("sqrt: negative value");if(e<2n)return e;let t=e,n=(t+1n)/2n;for(;n<t;)t=n,n=(t+e/t)/2n;return t;}var $t=(1n<<256n)-1n;function Xu(e,t){return e<0n||t<0n?!1:e===0n||t===0n?!0:t<=$t/e;}function ut(e,t){return e<=0n||t<=0n?0n:Xu(e,t)?kr(e*t):kr(e)*kr(t);}function Ve(e,t){if(e<0n||t<0n)throw new Error("addPreservingLowerBound: negative input");const n=e+t;return n>$t?e:n;}function Ii(e,t){return e<t?e:t;}function xi(e,t){if(t===0n)throw new Error("divCeil: division by zero");return e===0n?0n:(e+t-1n)/t;}var Ct=1n<<96n,ki=wt.MIN_TICK,Di=wt.MAX_TICK;function Xe(e){return f.BigInt(e.toString());}function ir(e){return BigInt(e.toString());}function pt(e){return ir(wt.getSqrtRatioAtTick(e));}function Wn(e,t,n,r){const[a,i]=e<=t?[e,t]:[t,e];return ir(co.getAmount0Delta(Xe(a),Xe(i),Xe(n),r));}function $n(e,t,n,r){const[a,i]=e<=t?[e,t]:[t,e];return ir(co.getAmount1Delta(Xe(a),Xe(i),Xe(n),r));}function Zu(e,t,n,r,a,i){return ir(ml(Xe(e),Xe(t),Xe(n),Xe(r),Xe(a)));}var Ju={"v0.4.0":!1,"v1.0.2":!0,"v1.0.3":!0};function wa(e,t){return ec(t,ba(Ju,e));}function ec(e,t){const{idle0:n,idle1:r,positions:a}=e;if(a.length===0)return ut(n,r);const i=[],o=/* @__PURE__ */new Map();let s=0;for(const u of a)if(u.kind===0){const d=tc(u.data);i.push(d),nc(d,o);}else rc(u.data,o),s+=1;const l=ac(o);return ic(n,r,i,l,s,t);}function tc(e){const t=pt(e.tickLower),n=pt(e.tickUpper),r=Wn(t,n,e.liquidity,!1),a=$n(t,n,e.liquidity,!1),i=xi(e.liquidity*Ct,n),o=xi(e.liquidity*t,Ct);return{tickLower:e.tickLower,tickUpper:e.tickUpper,sqrtLowerX96:t,sqrtUpperX96:n,liquidity:e.liquidity,amt0Below:r,amt1Above:a,neg0AtUpper:i,neg1AtLower:o};}function nc(e,t){const n=Hn(e.tickLower,t),r=Hn(e.tickUpper,t);n.sumLStart+=e.liquidity,r.sumLEnd+=e.liquidity,n.sumNeg0Start+=e.neg0AtUpper,r.sumNeg0End+=e.neg0AtUpper,n.sumNeg1Start+=e.neg1AtLower,r.sumNeg1End+=e.neg1AtLower,n.sumRangeAmt0AtLower+=e.amt0Below,r.sumRangeAmt1AtUpper+=e.amt1Above;}function rc(e,t){const n=Hn(e.tickLower,t),r=Hn(e.tickUpper,t),a=pt(e.tickLower),i=pt(e.tickUpper),o=Wn(a,i,e.liquidity,!1),s=$n(a,i,e.liquidity,!1);n.sumLoAmt0AtLower+=o,r.sumLoAmt1AtUpper+=s;}function Hn(e,t){const n=t.get(e);if(n)return n;const r={tick:e,sumLStart:0n,sumLEnd:0n,sumNeg0Start:0n,sumNeg0End:0n,sumNeg1Start:0n,sumNeg1End:0n,sumRangeAmt0AtLower:0n,sumRangeAmt1AtUpper:0n,sumLoAmt0AtLower:0n,sumLoAmt1AtUpper:0n};return t.set(e,r),r;}function ac(e){return Array.from(e.values()).sort((t,n)=>t.tick-n.tick).map(t=>({tick:t.tick,liquidityNet:t.sumLStart-t.sumLEnd,neg0Net:t.sumNeg0Start-t.sumNeg0End,neg1Net:t.sumNeg1Start-t.sumNeg1End,sumRangeAmt0AtLower:t.sumRangeAmt0AtLower,sumRangeAmt1AtUpper:t.sumRangeAmt1AtUpper,sumLoAmt0AtLower:t.sumLoAmt0AtLower,sumLoAmt1AtUpper:t.sumLoAmt1AtUpper}));}function ic(e,t,n,r,a,i){const o=r.length;if(o===0)return ut(e,t);const s=r.map(A=>pt(A.tick)),l=new Array(o),u=new Array(o);{let A=0n;for(let I=0;I<o;I++)A+=r[I].sumRangeAmt1AtUpper,l[I]=A;A=0n;for(let I=o;I>0;I--){const T=I-1;A+=r[T].sumRangeAmt0AtLower,u[T]=A;}}const d=a>0,c=new Array(o).fill(0n),p=new Array(o).fill(0n);if(d){let A=0n;for(let I=0;I<o;I++)A+=r[I].sumLoAmt1AtUpper,c[I]=A;A=0n;for(let I=o;I>0;I--){const T=I-1;A+=r[T].sumLoAmt0AtLower,p[T]=A;}}const y=new Array(o).fill(void 0);function b(A,I){return(i?A>=I:A>I)?{ok:!0,value:A-I}:{ok:!1,value:0n};}function m(A){let I=e,T=t;const L=s[A];for(const x of n)if(L<=x.sqrtLowerX96)I=Ve(I,x.amt0Below);else if(L>=x.sqrtUpperX96)T=Ve(T,x.amt1Above);else{const k=x.liquidity*Ct/L;if(k>=x.neg0AtUpper)I=Ve(I,k-x.neg0AtUpper);else{const D=b(I,x.neg0AtUpper-k);if(!D.ok)return{ok:!1,amt0:0n,amt1:0n};I=D.value;}const _=x.liquidity*L/Ct;if(_>=x.neg1AtLower)T=Ve(T,_-x.neg1AtLower);else{const D=b(T,x.neg1AtLower-_);if(!D.ok)return{ok:!1,amt0:0n,amt1:0n};T=D.value;}}return{ok:!0,amt0:I,amt1:T};}function h(A){const I=y[A];if(I!==void 0)return I;const T=m(A);if(!T.ok)return y[A]=0n,0n;let L=T.amt0,x=T.amt1;d&&(A+1<o&&(L=Ve(L,p[A+1])),A>0&&(x=Ve(x,c[A-1])));const k=r[A].sumLoAmt0AtLower,_=r[A].sumLoAmt1AtUpper,D=(k!==0n?1:0)|(_!==0n?2:0);let P;if(!d||D===0)return P=ut(L,x),y[A]=P,P;if(D===1)return P=ut(Ve(L,k),x),y[A]=P,P;if(D===2)return P=ut(L,Ve(x,_)),y[A]=P,P;P=ut(Ve(L,k),x);const W=ut(L,Ve(x,_));return W<P&&(P=W),y[A]=P,P;}let g=$t,v=0n,w=0n,E=0n;for(let A=0;A+1<o;A++){const I=r[A];if(v+=I.liquidityNet,v<0n)throw new Error("computeCollateralFloor: negative active liquidity (invalid tick aggregation)");const T=I.neg0Net;T>=0n?w+=T:T!==0n&&(w-=-T);const L=I.neg1Net;L>=0n?E+=L:L!==0n&&(E-=-L);const x=h(A),k=h(A+1);let _=x<k?x:k,D=e,P=t;A+1<o&&(D=Ve(D,u[A+1])),P=Ve(P,l[A]),d&&(A+1<o&&(D=Ve(D,p[A+1])),P=Ve(P,c[A]));const W=b(D,w),q=b(P,E);if(W.ok&&q.ok&&v>0n){const R=ut(W.value,q.value),C=Ve(R,v);_=Ii(_,C);}if(g=Ii(g,_),g===0n)break;}if(g===$t){let A=$t;for(let I=0;I<o;I++){const T=h(I);T<A&&(A=T);}g=A===$t?0n:A;}return g;}var bt=0n,Ue=0n,oc=0n,ze="0x0000000000000000000000000000000000000001",zt="0x0000000000000000000000000000000000000002",sc={// ── CL Position & Swap ────────────────────────────────────────────────
|
|
957
|
+
0:[{name:"tokenId",type:"uint256"},{name:"liquidity",type:"uint256"},{name:"amount0Max",type:"uint128"},{name:"amount1Max",type:"uint128"},{name:"hookData",type:"bytes"}],1:[{name:"tokenId",type:"uint256"},{name:"liquidity",type:"uint256"},{name:"amount0Min",type:"uint128"},{name:"amount1Min",type:"uint128"},{name:"hookData",type:"bytes"}],2:[{name:"poolKey",type:"tuple",components:[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}]},{name:"tickLower",type:"int24"},{name:"tickUpper",type:"int24"},{name:"liquidity",type:"uint256"},{name:"amount0Max",type:"uint128"},{name:"amount1Max",type:"uint128"},{name:"owner",type:"address"},{name:"hookData",type:"bytes"}],3:[{name:"tokenId",type:"uint256"},{name:"amount0Min",type:"uint128"},{name:"amount1Min",type:"uint128"},{name:"hookData",type:"bytes"}],4:[{name:"tokenId",type:"uint256"},{name:"amount0Max",type:"uint128"},{name:"amount1Max",type:"uint128"},{name:"hookData",type:"bytes"}],5:[{name:"poolKey",type:"tuple",components:[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}]},{name:"tickLower",type:"int24"},{name:"tickUpper",type:"int24"},{name:"amount0Max",type:"uint128"},{name:"amount1Max",type:"uint128"},{name:"owner",type:"address"},{name:"hookData",type:"bytes"}],6:[{name:"params",type:"tuple",components:[{name:"poolKey",type:"tuple",components:[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}]},{name:"zeroForOne",type:"bool"},{name:"amountIn",type:"uint128"},{name:"amountOutMinimum",type:"uint128"},{name:"hookData",type:"bytes"}]}],7:[{name:"params",type:"tuple",components:[{name:"currencyIn",type:"address"},{name:"path",type:"tuple[]",components:[{name:"intermediateCurrency",type:"address"},{name:"fee",type:"uint256"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"},{name:"hookData",type:"bytes"}]},{name:"amountIn",type:"uint128"},{name:"amountOutMinimum",type:"uint128"}]}],8:[{name:"params",type:"tuple",components:[{name:"poolKey",type:"tuple",components:[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}]},{name:"zeroForOne",type:"bool"},{name:"amountOut",type:"uint128"},{name:"amountInMaximum",type:"uint128"},{name:"hookData",type:"bytes"}]}],9:[{name:"params",type:"tuple",components:[{name:"currencyOut",type:"address"},{name:"path",type:"tuple[]",components:[{name:"intermediateCurrency",type:"address"},{name:"fee",type:"uint256"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"},{name:"hookData",type:"bytes"}]},{name:"amountOut",type:"uint128"},{name:"amountInMaximum",type:"uint128"}]}],// ── PM Delta Resolution ───────────────────────────────────────────────
|
|
958
|
+
11:[{name:"currency",type:"address"},{name:"amount",type:"uint256"},{name:"payerIsUser",type:"bool"}],12:[{name:"currency",type:"address"},{name:"maxAmount",type:"uint256"}],14:[{name:"currency",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],15:[{name:"currency",type:"address"},{name:"minAmount",type:"uint256"}],16:[{name:"currency",type:"address"},{name:"recipient",type:"address"},{name:"bips",type:"uint256"}],18:[{name:"currency",type:"address"}],20:[{name:"currency",type:"address"},{name:"recipient",type:"address"}],21:[{name:"amount",type:"uint256"}],22:[{name:"amount",type:"uint256"}],// ── Limit Orders ──────────────────────────────────────────────────────
|
|
959
|
+
// The deployed LimitOrderManager decodes PLACE_ORDER as
|
|
960
|
+
// `(PoolKey,int24,bool,uint128,address)`: `zeroForOne` precedes the uint128
|
|
961
|
+
// liquidity. See CONTRACT_BEHAVIOR.md.
|
|
962
|
+
48:[{name:"poolKey",type:"tuple",components:[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}]},{name:"tickLower",type:"int24"},{name:"zeroForOne",type:"bool"},{name:"liquidity",type:"uint128"},{name:"owner",type:"address"}],49:[{name:"tokenId",type:"uint256"},{name:"amount0Min",type:"uint128"},{name:"amount1Min",type:"uint128"},{name:"hookData",type:"bytes"}],50:[{name:"tokenId",type:"uint256"},{name:"amount0Min",type:"uint128"},{name:"amount1Min",type:"uint128"}],// ── AegisEngine ───────────────────────────────────────────────────────
|
|
963
|
+
128:[{name:"currency",type:"address"},{name:"amount",type:"uint256"},{name:"payerIsUser",type:"bool"}],129:[{name:"currency",type:"address"},{name:"recipient",type:"address"}],130:[{name:"currency",type:"address"}],131:[{name:"poolId",type:"bytes32"},{name:"owner",type:"address"}],132:[{name:"vaultId",type:"uint256"}],133:[{name:"vaultId",type:"uint256"},{name:"maxLtvPips",type:"uint256"}],134:[{name:"vaultId",type:"uint256"},{name:"kind",type:"uint8"},{name:"tokenId",type:"uint256"}],135:[{name:"vaultId",type:"uint256"},{name:"kind",type:"uint8"},{name:"tokenId",type:"uint256"},{name:"to",type:"address"}],136:[{name:"vaultId",type:"uint256"},{name:"amount0",type:"uint128"},{name:"amount1",type:"uint128"}],137:[{name:"vaultId",type:"uint256"}],144:[{name:"poolId",type:"bytes32"},{name:"liquidityDelta",type:"int128"},{name:"recipient",type:"address"},{name:"minShares",type:"uint256"},{name:"amount0Max",type:"uint128"},{name:"amount1Max",type:"uint128"}],145:[{name:"vaultId",type:"uint256"},{name:"principalDelta",type:"int128"},{name:"minLiquidityDelta",type:"int136"},{name:"minIdle0",type:"int128"},{name:"minIdle1",type:"int128"}],146:[{name:"vaultId",type:"uint256"},{name:"delta",type:"int256"}],150:[{name:"vaultId",type:"uint256"},{name:"kind",type:"uint8"},{name:"tokenId",type:"uint256"}],// ── PM / LOM Forwarders ───────────────────────────────────────────────
|
|
964
|
+
176:[{name:"currency",type:"address"},{name:"amount",type:"uint256"},{name:"payerIsUser",type:"bool"}],192:[{name:"currency",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],194:[{name:"currency",type:"address"},{name:"recipient",type:"address"},{name:"payerIsUser",type:"bool"}],184:[{name:"currency",type:"address"},{name:"amount",type:"uint256"},{name:"payerIsUser",type:"bool"}],196:[{name:"currency",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],198:[{name:"currency",type:"address"},{name:"recipient",type:"address"},{name:"payerIsUser",type:"bool"}]},lc=class{constructor(){oe(this,"_actions",[]);oe(this,"_params",[]);}/**
|
|
965
|
+
* Adds an action with its parameters to the batch.
|
|
966
|
+
*
|
|
967
|
+
* @param action - The action opcode
|
|
968
|
+
* @param parameters - The parameters to encode (must match AEGIS_ACTION_ABI)
|
|
969
|
+
* @returns this (for chaining)
|
|
970
|
+
*/addAction(e,t){const n=sc[e],r=eo(// Need to cast since encodeAbiParameters expects mutable array
|
|
971
|
+
n,t);return this._actions.push(e),this._params.push(r),this;}/**
|
|
972
|
+
* Number of actions currently in the planner.
|
|
973
|
+
*/get length(){return this._actions.length;}/**
|
|
974
|
+
* Finalizes the planner into an ExecutionBatch.
|
|
975
|
+
* Packs the action opcodes into a single hex string (one byte per action).
|
|
976
|
+
*
|
|
977
|
+
* @param opts - Options for the batch
|
|
978
|
+
* @returns The finalized execution batch
|
|
979
|
+
*/finalize(e){const t="0x"+this._actions.map(n=>n.toString(16).padStart(2,"0")).join("");return{requiresV4Unlock:e.requiresV4Unlock,actions:t,params:[...this._params]};}/**
|
|
980
|
+
* Clears all accumulated actions.
|
|
981
|
+
*
|
|
982
|
+
* @returns this (for chaining)
|
|
983
|
+
*/clear(){return this._actions=[],this._params=[],this;}},uc=(1n<<128n)-1n,ce=(1n<<127n)-1n,zr=-(1n<<127n);function Aa(e){const t=BigInt.asIntN(128,e>>128n),n=BigInt.asIntN(128,e&uc);return{amount0:t,amount1:n};}function Co(e,t){if(e>ce||e<zr||t>ce||t<zr)throw new Error(`encodeBalanceDelta: amount outside signed int128 (amount0=${e}, amount1=${t})`);const n=BigInt.asUintN(128,e)<<128n,r=BigInt.asUintN(128,t);return BigInt.asIntN(256,n|r);}function Mt(e,t){return Co(e,t);}function or(e,t){return Co(-e,-t);}function Ni(e,t){if(e<-ce||e>ce)throw new RangeError(`${t} must be between -int128 max (${-ce}) and int128 max (${ce}); got ${e}`);}var ft=class extends lc{// ── AE Settlement ───────────────────────────────────────────────────
|
|
984
|
+
addSettleAE(e,t=Ue,n=!0){return this.addAction(128,[e,t,n]);}addTakeAE(e,t){return this.addAction(129,[e,t]);}addCloseAE(e){return this.addAction(130,[e]);}// ── Vault Lifecycle ─────────────────────────────────────────────────
|
|
985
|
+
addCreateVault(e,t){return this.addAction(131,[e,t]);}addUnlockVault(e){return this.addAction(132,[e]);}addLockVault(e,t){return this.addAction(133,[e,t]);}addBurnVault(e){return this.addAction(137,[e]);}// ── Vault Operations ────────────────────────────────────────────────
|
|
986
|
+
addModifyDebt(e,t,n=0n,r=0n,a=0n){return Ni(t,"AegisPositionPlanner.addModifyDebt principalDelta"),this.addAction(145,[e,t,n,r,a]);}addModifyIdle(e,t){return this.addAction(146,[e,t]);}addAttachNft(e,t,n){return this.addAction(134,[e,t,n]);}addDetachNft(e,t,n,r){return this.addAction(135,[e,t,n,r]);}addDonateIdle(e,t,n){return this.addAction(136,[e,t,n]);}// ── Lending ─────────────────────────────────────────────────────────
|
|
987
|
+
addModifyLiquidity(e,t,n,r=0n,a=0n,i=0n){return Ni(t,"AegisPositionPlanner.addModifyLiquidity liquidityDelta"),this.addAction(144,[e,t,n,r,a,i]);}// ── Liquidation ─────────────────────────────────────────────────────
|
|
988
|
+
addPeelOrMicroLiquidate(e,t,n){return this.addAction(150,[e,t,n]);}// ── PM / LOM Forwarders ─────────────────────────────────────────────
|
|
989
|
+
addPmSettleFor(e,t=Ue,n=!0){return this.addAction(176,[e,t,n]);}addPmTake(e,t,n=Ue){return this.addAction(192,[e,t,n]);}addPmClose(e,t,n=!0){return this.addAction(194,[e,t,n]);}addLomSettleFor(e,t=Ue,n=!0){return this.addAction(184,[e,t,n]);}addLomTake(e,t,n=Ue){return this.addAction(196,[e,t,n]);}addLomClose(e,t,n=!0){return this.addAction(198,[e,t,n]);}// ── CL Actions ──────────────────────────────────────────────────────
|
|
990
|
+
addMintPosition(e,t,n,r,a,i,o,s="0x"){return this.addAction(2,[e,t,n,r,a,i,o,s]);}addMintPositionFromDeltas(e,t,n,r,a,i,o="0x"){return this.addAction(5,[e,t,n,r,a,i,o]);}addIncreaseLiquidity(e,t,n,r,a="0x"){return this.addAction(0,[e,t,n,r,a]);}addIncreaseLiquidityFromDeltas(e,t,n,r="0x"){return this.addAction(4,[e,t,n,r]);}addDecreaseLiquidity(e,t,n,r,a="0x"){return this.addAction(1,[e,t,n,r,a]);}addBurnPosition(e,t,n,r="0x"){return this.addAction(3,[e,t,n,r]);}addSweep(e,t){return this.addAction(20,[e,t]);}addSettle(e,t,n){return this.addAction(11,[e,t,n]);}addTake(e,t,n){return this.addAction(14,[e,t,n]);}addCloseCurrency(e){return this.addAction(18,[e]);}// ── Limit Orders ────────────────────────────────────────────────────
|
|
991
|
+
/**
|
|
992
|
+
* Places a limit order.
|
|
993
|
+
*
|
|
994
|
+
* The operand order matches the deployed LimitOrderManager decoder,
|
|
995
|
+
* `(PoolKey,int24,bool,uint128,address)` — `zeroForOne` precedes the uint128
|
|
996
|
+
* liquidity in the encoded payload. The public argument order remains the
|
|
997
|
+
* pre-0.31.0 order for source compatibility; only the on-chain tuple is
|
|
998
|
+
* reordered and narrowed to the deployed uint128 type.
|
|
999
|
+
*/addPlaceOrder(e,t,n,r,a){return this.addAction(48,[e,t,r,n,a]);}addCancelOrder(e,t,n,r="0x"){return this.addAction(49,[e,t,n,r]);}addWithdrawOrder(e,t,n){return this.addAction(50,[e,t,n]);}// ── Swap Actions ─────────────────────────────────────────────────────
|
|
1000
|
+
addSwapExactInSingle(e,t,n,r,a="0x"){return this.addAction(6,[{poolKey:e,zeroForOne:t,amountIn:n,amountOutMinimum:r,hookData:a}]);}addSwapExactOutSingle(e,t,n,r,a="0x"){return this.addAction(8,[{poolKey:e,zeroForOne:t,amountOut:n,amountInMaximum:r,hookData:a}]);}addSwapExactIn(e,t,n,r){return this.addAction(7,[{currencyIn:e,path:t,amountIn:n,amountOutMinimum:r}]);}addSwapExactOut(e,t,n,r){return this.addAction(9,[{currencyOut:e,path:t,amountOut:n,amountInMaximum:r}]);}},un=[{type:"constructor",inputs:[{name:"deps",type:"address",internalType:"contract IAegisDependencies"},{name:"_aegisEngine",type:"address",internalType:"contract IAegisEngine"},{name:"_limitOrderManager",type:"address",internalType:"contract ILimitOrderManager"},{name:"_vaultRegistry",type:"address",internalType:"contract IVaultRegistry"}],stateMutability:"nonpayable"},{type:"receive",stateMutability:"payable"},{type:"function",name:"AEGIS_ENGINE",inputs:[],outputs:[{name:"",type:"address",internalType:"contract IAegisEngine"}],stateMutability:"view"},{type:"function",name:"LIMIT_ORDER_MANAGER",inputs:[],outputs:[{name:"",type:"address",internalType:"contract ILimitOrderManager"}],stateMutability:"view"},{type:"function",name:"POSITION_MANAGER",inputs:[],outputs:[{name:"",type:"address",internalType:"contract IPositionManager"}],stateMutability:"view"},{type:"function",name:"VAULT_REGISTRY",inputs:[],outputs:[{name:"",type:"address",internalType:"contract IVaultRegistry"}],stateMutability:"view"},{type:"function",name:"WETH9",inputs:[],outputs:[{name:"",type:"address",internalType:"contract IWETH9"}],stateMutability:"view"},{type:"function",name:"aeStartCallback",inputs:[{name:"userData",type:"bytes",internalType:"bytes"}],outputs:[{name:"",type:"bytes",internalType:"bytes"}],stateMutability:"nonpayable"},{type:"function",name:"execute",inputs:[{name:"batches",type:"tuple[]",internalType:"struct IAegisRouterV1.ExecutionBatch[]",components:[{name:"requiresV4Unlock",type:"bool",internalType:"bool"},{name:"actions",type:"bytes",internalType:"bytes"},{name:"params",type:"bytes[]",internalType:"bytes[]"}]},{name:"deadline",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"msgSender",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"multicall",inputs:[{name:"data",type:"bytes[]",internalType:"bytes[]"}],outputs:[{name:"results",type:"bytes[]",internalType:"bytes[]"}],stateMutability:"payable"},{type:"function",name:"permit",inputs:[{name:"owner",type:"address",internalType:"address"},{name:"permitSingle",type:"tuple",internalType:"struct IAllowanceTransfer.PermitSingle",components:[{name:"details",type:"tuple",internalType:"struct IAllowanceTransfer.PermitDetails",components:[{name:"token",type:"address",internalType:"address"},{name:"amount",type:"uint160",internalType:"uint160"},{name:"expiration",type:"uint48",internalType:"uint48"},{name:"nonce",type:"uint48",internalType:"uint48"}]},{name:"spender",type:"address",internalType:"address"},{name:"sigDeadline",type:"uint256",internalType:"uint256"}]},{name:"signature",type:"bytes",internalType:"bytes"}],outputs:[{name:"err",type:"bytes",internalType:"bytes"}],stateMutability:"payable"},{type:"function",name:"permit2",inputs:[],outputs:[{name:"",type:"address",internalType:"contract IAllowanceTransfer"}],stateMutability:"view"},{type:"function",name:"permitBatch",inputs:[{name:"owner",type:"address",internalType:"address"},{name:"_permitBatch",type:"tuple",internalType:"struct IAllowanceTransfer.PermitBatch",components:[{name:"details",type:"tuple[]",internalType:"struct IAllowanceTransfer.PermitDetails[]",components:[{name:"token",type:"address",internalType:"address"},{name:"amount",type:"uint160",internalType:"uint160"},{name:"expiration",type:"uint48",internalType:"uint48"},{name:"nonce",type:"uint48",internalType:"uint48"}]},{name:"spender",type:"address",internalType:"address"},{name:"sigDeadline",type:"uint256",internalType:"uint256"}]},{name:"signature",type:"bytes",internalType:"bytes"}],outputs:[{name:"err",type:"bytes",internalType:"bytes"}],stateMutability:"payable"},{type:"function",name:"poolManager",inputs:[],outputs:[{name:"",type:"address",internalType:"contract IPoolManager"}],stateMutability:"view"},{type:"function",name:"unlockCallback",inputs:[{name:"data",type:"bytes",internalType:"bytes"}],outputs:[{name:"",type:"bytes",internalType:"bytes"}],stateMutability:"nonpayable"},{type:"error",name:"ContractLocked",inputs:[]},{type:"error",name:"DeadlinePassed",inputs:[{name:"deadline",type:"uint256",internalType:"uint256"}]},{type:"error",name:"DeltaNotNegative",inputs:[{name:"currency",type:"address",internalType:"Currency"}]},{type:"error",name:"DeltaNotPositive",inputs:[{name:"currency",type:"address",internalType:"Currency"}]},{type:"error",name:"ExcessiveAmount0Spent",inputs:[{name:"actualAmount",type:"uint128",internalType:"uint128"},{name:"maxAmount",type:"uint128",internalType:"uint128"}]},{type:"error",name:"ExcessiveAmount1Spent",inputs:[{name:"actualAmount",type:"uint128",internalType:"uint128"},{name:"maxAmount",type:"uint128",internalType:"uint128"}]},{type:"error",name:"InputLengthMismatch",inputs:[]},{type:"error",name:"InsufficientAmount0Received",inputs:[{name:"actualAmount",type:"int128",internalType:"int128"},{name:"minAmount",type:"uint128",internalType:"uint128"}]},{type:"error",name:"InsufficientAmount1Received",inputs:[{name:"actualAmount",type:"int128",internalType:"int128"},{name:"minAmount",type:"uint128",internalType:"uint128"}]},{type:"error",name:"InsufficientBalance",inputs:[]},{type:"error",name:"InsufficientIdleAmount0",inputs:[{name:"actualAmount",type:"int128",internalType:"int128"},{name:"minAmount",type:"int128",internalType:"int128"}]},{type:"error",name:"InsufficientIdleAmount1",inputs:[{name:"actualAmount",type:"int128",internalType:"int128"},{name:"minAmount",type:"int128",internalType:"int128"}]},{type:"error",name:"InsufficientLiquidityDelta",inputs:[{name:"actualDelta",type:"int136",internalType:"int136"},{name:"minDelta",type:"int136",internalType:"int136"}]},{type:"error",name:"InsufficientSharesMinted",inputs:[{name:"actualShares",type:"uint256",internalType:"uint256"},{name:"minShares",type:"uint256",internalType:"uint256"}]},{type:"error",name:"InvalidBips",inputs:[]},{type:"error",name:"InvalidEthSender",inputs:[]},{type:"error",name:"InvalidNftKind",inputs:[{name:"kind",type:"uint8",internalType:"uint8"}]},{type:"error",name:"LtvExceedsMaximum",inputs:[{name:"actualLtvPips",type:"uint256",internalType:"uint256"},{name:"maxLtvPips",type:"uint256",internalType:"uint256"}]},{type:"error",name:"NoCLNftCreatedInSession",inputs:[]},{type:"error",name:"NoLONftCreatedInSession",inputs:[]},{type:"error",name:"NoVaultCreatedInSession",inputs:[]},{type:"error",name:"NotAuthorizedForCLNft",inputs:[{name:"tokenId",type:"uint256",internalType:"uint256"}]},{type:"error",name:"NotAuthorizedForLONft",inputs:[{name:"tokenId",type:"uint256",internalType:"uint256"}]},{type:"error",name:"NotAuthorizedForVault",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"}]},{type:"error",name:"NotPoolManager",inputs:[]},{type:"error",name:"SafeCastOverflowedUintDowncast",inputs:[{name:"bits",type:"uint8",internalType:"uint8"},{name:"value",type:"uint256",internalType:"uint256"}]},{type:"error",name:"UnauthorizedCallback",inputs:[]},{type:"error",name:"UnauthorizedShareBurn",inputs:[{name:"owner",type:"address",internalType:"address"}]},{type:"error",name:"UnsupportedAction",inputs:[{name:"action",type:"uint256",internalType:"uint256"}]},{type:"error",name:"V4TooLittleReceived",inputs:[{name:"minAmountOutReceived",type:"uint256",internalType:"uint256"},{name:"amountReceived",type:"uint256",internalType:"uint256"}]},{type:"error",name:"V4TooMuchRequested",inputs:[{name:"maxAmountInRequested",type:"uint256",internalType:"uint256"},{name:"amountRequested",type:"uint256",internalType:"uint256"}]}],Ze=class cn{/** This class cannot be instantiated. */constructor(){}/**
|
|
1001
|
+
* Encodes an `execute()` call for the AegisRouterV1 contract.
|
|
1002
|
+
*
|
|
1003
|
+
* @param batches - One or more execution batches
|
|
1004
|
+
* @param deadline - Transaction deadline (unix timestamp)
|
|
1005
|
+
* @param value - Native token value to send (default 0)
|
|
1006
|
+
* @returns Encoded calldata and value
|
|
1007
|
+
*/static encodeExecute(t,n,r=0n){return{calldata:Ln({abi:un,functionName:"execute",args:[t,n]}),value:r};}/**
|
|
1008
|
+
* Encodes a `multicall()` call for the AegisRouterV1 contract.
|
|
1009
|
+
* Used to bundle permit2 approvals with execute in a single transaction.
|
|
1010
|
+
*
|
|
1011
|
+
* @param calldatas - Array of encoded function calls
|
|
1012
|
+
* @param value - Native token value to send (default 0)
|
|
1013
|
+
* @returns Encoded calldata and value
|
|
1014
|
+
*/static encodeMulticall(t,n=0n){return{calldata:Ln({abi:un,functionName:"multicall",args:[t]}),value:n};}/**
|
|
1015
|
+
* Encodes an `execute()` call, bundled behind a `multicall()` with the
|
|
1016
|
+
* Permit2 batch approval when one is supplied.
|
|
1017
|
+
*
|
|
1018
|
+
* @param batches - One or more execution batches
|
|
1019
|
+
* @param deadline - Transaction deadline (unix timestamp)
|
|
1020
|
+
* @param value - Native token value to send
|
|
1021
|
+
* @param permit - Optional signed Permit2 batch to forward before execute
|
|
1022
|
+
* @returns Encoded calldata and value
|
|
1023
|
+
*/static encodeExecuteWithOptionalPermit(t,n,r,a){if(a){const i=cn.encodePermitBatch(a.owner,a.permitBatch,a.signature),{calldata:o}=cn.encodeExecute(t,n);return cn.encodeMulticall([i,o],r);}return cn.encodeExecute(t,n,r);}/**
|
|
1024
|
+
* Encodes a `permit()` call for single-token Permit2 approval.
|
|
1025
|
+
*
|
|
1026
|
+
* @param owner - Token owner address
|
|
1027
|
+
* @param permitSingle - The permit details
|
|
1028
|
+
* @param signature - EIP-712 signature
|
|
1029
|
+
* @returns Encoded calldata
|
|
1030
|
+
*/static encodePermit(t,n,r){return Ln({abi:un,functionName:"permit",args:[t,n,r]});}/**
|
|
1031
|
+
* Encodes a `permitBatch()` call for multi-token Permit2 approval.
|
|
1032
|
+
*
|
|
1033
|
+
* @param owner - Token owner address
|
|
1034
|
+
* @param permitBatch - The batch permit details
|
|
1035
|
+
* @param signature - EIP-712 signature
|
|
1036
|
+
* @returns Encoded calldata
|
|
1037
|
+
*/static encodePermitBatch(t,n,r){return Ln({abi:un,functionName:"permitBatch",args:[t,n,r]});}},cc="Permit2";function dc(e,t){return{name:cc,chainId:e,verifyingContract:t};}var pc=[{name:"token",type:"address"},{name:"amount",type:"uint160"},{name:"expiration",type:"uint48"},{name:"nonce",type:"uint48"}],fc={PermitBatch:[{name:"details",type:"PermitDetails[]"},{name:"spender",type:"address"},{name:"sigDeadline",type:"uint256"}],PermitDetails:pc};function Mo(e,t){return{domain:dc(t.chainId,t.permit2Address),types:fc,primaryType:"PermitBatch",message:{details:e.details.map(n=>({token:n.token,amount:n.amount,expiration:n.expiration,nonce:n.nonce})),spender:e.spender,sigDeadline:e.sigDeadline}};}var mc=[{type:"function",name:"allowance",inputs:[{name:"owner",type:"address"},{name:"token",type:"address"},{name:"spender",type:"address"}],outputs:[{name:"amount",type:"uint160"},{name:"expiration",type:"uint48"},{name:"nonce",type:"uint48"}],stateMutability:"view"}];async function yc(e,t,n,r,a,i){const[o,s,l]=await e.readContract({address:t,abi:mc,functionName:"allowance",args:[n,r,a],blockNumber:i});return{amount:o,expiration:s,nonce:l};}var hc="0x000000000022D473030F116dDEE9F6B43aC78BA3";function Ro(e,t,n){return Vs(Mo(e,{chainId:t,permit2Address:n}));}function Ta(e){return{owner:e.owner,permitBatch:e.permitBatch,signature:e.signature};}async function So(e,t){const{chainId:n,permit2Address:r,permit:a,blockNumber:i}=t,o=Mo(a.permitBatch,{chainId:n,permit2Address:r}),[s,l]=await Promise.all([e.verifyTypedData({address:a.owner,domain:o.domain,types:o.types,primaryType:o.primaryType,message:o.message,signature:a.signature,blockNumber:i}),Promise.all(a.permitBatch.details.map(d=>yc(e,r,a.owner,d.token,a.permitBatch.spender,i)))]),u=a.permitBatch.details.map((d,c)=>({token:d.token,permitNonce:d.nonce,onChainNonce:l[c].nonce}));return{owner:a.owner,spender:a.permitBatch.spender,permit2:r,chainId:n,blockNumber:i,payloadDigest:Ro(a.permitBatch,n,r),signatureDigest:xt(a.signature),signatureValid:s,nonces:u,valid:s&&u.every(d=>d.permitNonce===d.onChainNonce)};}function bc(e){const{poolId:t,liquidityDelta:n,recipient:r,deadline:a,minShares:i=0n,amount0Max:o=0n,amount1Max:s=0n,currency0:l,currency1:u,value:d=0n,refundNative:c=!1,requiresV4Unlock:p=!0,permit:y}=e,b=new ft();b.addModifyLiquidity(t,n,r,i,o,s),b.addSettleAE(l),b.addSettleAE(u),c&&b.addSweep(ke,ze);const m=b.finalize({requiresV4Unlock:p});return Ze.encodeExecuteWithOptionalPermit([m],a,d,y);}function gc(e,t){const n=e.toLowerCase(),r=t.toLowerCase();return n<r?[e,t]:[t,e];}function Ea(e,t,n,r,a=50){if(!e||e.length===0)return;let i=0n,o=0n,s=!0,l=null,u=null;const d=BigInt(1e4-a);for(let p=0;p<e.length;p++){const y=e[p];if(!y||y.length===0)continue;const b=y[0],m=y[y.length-1];if(!(!b||!m)){if(l===null)l=b.tokenIn.address;else if(l.toLowerCase()!==b.tokenIn.address.toLowerCase())throw new Error(`route path ${p} tokenIn (${b.tokenIn.address}) does not match path 0 tokenIn (${l})`);if(u===null)u=m.tokenOut.address;else if(u.toLowerCase()!==m.tokenOut.address.toLowerCase())throw new Error(`route path ${p} tokenOut (${m.tokenOut.address}) does not match path 0 tokenOut (${u})`);if(b.amountIn===void 0)throw new Error(`route path ${p} missing amountIn on first hop`);i+=BigInt(b.amountIn),m.amountOut===void 0?s=!1:o+=BigInt(m.amountOut)*d/10000n;}}if(l===null)return;if(i!==t.input)throw new Error(`route total amountIn (${i}) does not match swap.input (${t.input}); recipe would leave drift`);const c=t.inputIsToken0?n:r??null;if(c!==null&&l.toLowerCase()!==c.toLowerCase())throw new Error(`route.tokenIn (${l}) does not equal expected pool currency (${c}) for swap.inputIsToken0=${t.inputIsToken0}`);if(r===void 0&&l.toLowerCase()===n.toLowerCase()!==t.inputIsToken0)throw new Error(`route.tokenIn (${l}) does not match swap.inputIsToken0 (${t.inputIsToken0})`);if(r!==void 0&&u!==null){const p=t.inputIsToken0?r:n;if(u.toLowerCase()!==p.toLowerCase())throw new Error(`route.tokenOut (${u}) is not the expected pool counterpart (${p})`);}if(s&&t.minOutput!==void 0&&o<t.minOutput)throw new Error(`route min amountOut after ${a} bps haircut (${o}) is below swap.minOutput (${t.minOutput})`);}function Ia(e,t,n=50,r){const a=/* @__PURE__ */new Set();for(const i of t){if(i.length===0)continue;for(const u of i)a.add(u.tokenIn.address),a.add(u.tokenOut.address);const o=i[0];if(!(o!=null&&o.amountIn))throw new Error("Route path missing amountIn on first hop");const s=BigInt(o.amountIn),l=vc(i,n);if(i.length===1){const u=o,[d,c]=gc(u.tokenIn.address,u.tokenOut.address),p=u.tokenIn.address.toLowerCase()===d.toLowerCase(),y={currency0:d,currency1:c,fee:u.fee,tickSpacing:u.tickSpacing,hooks:u.hooks};e.addSwapExactInSingle(y,p,s,l);}else{const u=i.map(d=>({intermediateCurrency:d.tokenOut.address,fee:d.fee,tickSpacing:d.tickSpacing,hooks:d.hooks,hookData:"0x"}));e.addSwapExactIn(o.tokenIn.address,u,s,l);}}for(const i of a)r!=null&&r.has(i.toLowerCase())||e.addCloseCurrency(i);}function vc(e,t){const n=e[e.length-1];if(!(n!=null&&n.amountOut))throw new Error("Route path missing amountOut on last hop");return BigInt(n.amountOut)*BigInt(1e4-t)/10000n;}function wc(e){const{poolId:t,poolKey:n,inputIsToken0:r,amountIn:a,swapAmountIn:i,minSwapAmountOut:o,liquidityDelta:s,recipient:l,minDeltaShares:u,amount0Max:d,amount1Max:c,deadline:p,route:y,slippageBps:b=50,value:m=0n,permit:h}=e;if(a<=0n)throw new Error(`buildDepositZapRecipe: amountIn must be positive; got ${a}`);if(i<=0n)throw new Error(`buildDepositZapRecipe: swapAmountIn must be positive; got ${i}`);if(i>=a)throw new Error(`buildDepositZapRecipe: swapAmountIn (${i}) must be less than amountIn (${a})`);if(s<=0n)throw new Error(`buildDepositZapRecipe: liquidityDelta must be positive; got ${s}`);if(u<=0n)throw new Error(`buildDepositZapRecipe: minDeltaShares must be positive; got ${u}`);const g=r?n.currency0:n.currency1,v=r?n.currency1:n.currency0;Ea(y,{input:i,inputIsToken0:r,minOutput:o},n.currency0,n.currency1,b);const w=new ft();if(w.addSettle(g,a,!0),y&&y.length>0){const T=/* @__PURE__ */new Set([g.toLowerCase(),v.toLowerCase()]);Ia(w,y,b,T);}else w.addSwapExactInSingle(n,r,i,o);w.addTake(g,zt,Ue),w.addTake(v,zt,Ue),w.addModifyLiquidity(t,s,l,u,d,c),w.addSettleAE(n.currency0,Ue,!1),w.addSettleAE(n.currency1,Ue,!1),w.addSweep(n.currency0,ze),w.addSweep(n.currency1,ze);const E=w.finalize({requiresV4Unlock:!0}),A=g.toLowerCase()===ke?a:0n,I=m>A?m:A;return Ze.encodeExecuteWithOptionalPermit([E],p,I,h);}function Dr(e){const{poolId:t,sharesDelta:n,owner:r,recipient:a,deadline:i,currency0:o,currency1:s,minAmount0:l=0n,minAmount1:u=0n,requiresV4Unlock:d=!0}=e;if(n<=0n)throw new RangeError(`buildRedeem: sharesDelta must be positive; got ${n}`);if(n>ce)throw new RangeError(`buildRedeem: sharesDelta must be <= int128 max (${ce}); got ${n}`);const c=new ft();c.addModifyLiquidity(t,-n,r??a,0n,l,u),c.addTakeAE(o,a),c.addTakeAE(s,a);const p=c.finalize({requiresV4Unlock:d});return Ze.encodeExecute([p],i);}var zn=ce,ct=-zr;function Oo(e){const{fn:t,principalLabel:n,principal:r,maxEngineTokenDebit0:a,maxEngineTokenDebit1:i}=e;if(r>zn)throw new Error(`${t}: ${n} must be ≤ int128 max (${zn}); got ${r}`);if(a<0n||a>ct||i<0n||i>ct)throw new Error(`${t}: Engine token-debit limits must be within [0, ${ct}]; got (${a}, ${i})`);}function Nr(e){const{vaultId:t,deadline:n,currency0:r,currency1:a,recipient:i,currentDebt:o,attachedNfts:s=[],value:l=0n,accrualPoke:u,fromWallet0:d=0n,fromWallet1:c=0n,maxEngineTokenDebit0:p=0n,maxEngineTokenDebit1:y=0n,minLiquidityDelta:b=0n,permit:m}=e;if(o<0n)throw new Error(`buildCloseVault: currentDebt must be a non-negative rL magnitude; got ${o}`);Oo({fn:"buildCloseVault",principalLabel:"currentDebt",principal:o,maxEngineTokenDebit0:p,maxEngineTokenDebit1:y});const h=[];if(s.length>0){const I=new ft();I.addUnlockVault(t);for(const T of s)I.addDetachNft(t,T.kind,T.tokenId,i);h.push(I.finalize({requiresV4Unlock:!1}));}const g=new ft();s.length===0&&g.addUnlockVault(t),(d>0n||c>0n)&&(g.addModifyIdle(t,Mt(d,c)),d>0n&&g.addCloseAE(r),c>0n&&g.addCloseAE(a)),u&&g.addModifyLiquidity(u.poolId,0n,u.recipient),o>0n&&g.addModifyDebt(t,-o,b,-p,-y),g.addModifyIdle(t,oc),g.addLockVault(t,0n),g.addBurnVault(t),g.addCloseAE(r),g.addCloseAE(a),g.addTakeAE(r,i),g.addTakeAE(a,i),h.push(g.finalize({requiresV4Unlock:!0}));const A=l+(r===ke?d:a===ke?c:0n);return Ze.encodeExecuteWithOptionalPermit(h,n,A,m);}function qo(e,t){const{vaultId:n,poolKey:r,input:a,minOutput:i,inputIsToken0:o,deposit0:s,deposit1:l,route:u,slippageBps:d,surplusRecipient:c}=t;if(a<=0n)throw new Error("Rebalance input must be positive");if((!u||u.length===0)&&i<=0n)throw new Error("Rebalance minimum output must be positive without a route");const p=o?r.currency0:r.currency1,y=o?r.currency1:r.currency0;e.addModifyIdle(n,or(o?a:0n,o?0n:a)),e.addTakeAE(p,zt),u&&u.length>0?Ia(e,u,d,/* @__PURE__ */new Set([p.toLowerCase(),y.toLowerCase()])):e.addSwapExactInSingle(r,o,a,i),e.addSettle(p,Ue,!1),e.addTake(y,zt,Ue),(s!==0n||l!==0n)&&(e.addModifyIdle(n,Mt(s,l)),e.addSettleAE(y,Ue,!1)),e.addSweep(y,c);}var Li=f.exponentiate(f.BigInt(2),f.BigInt(96));f.multiply(Li,Li);function Ac(e){return Number(e)/Number(Ct);}function Bo(e,t,n){const r=Ac(e),a=r*r,i=t-n;return a*Math.pow(10,i);}var Fo=31556736;function Tc(e,t,n){const r=n/Fo;return e/(1+t*r);}function sr(e){return e>=1?0:e<=0?1:Math.sqrt(1-e*e);}function Ec(e,t,n,r){return 2*e*t*n*(r/Fo);}function Ot(e,t,n){return Bo(e,t,n);}function mt(e,t,n){return Math.sqrt(Bo(e,t,n));}function Zt(e){return e===0n?0n:(1n<<192n)/e;}function gn(e,t,n,r,a){if(e<=0n)return 0;if(t<=0n||n<=0n)return 1e6;const i=Math.pow(10,(r+a)/2),o=Number(e)/i,s=Number(t)/10**r,l=Number(n)/10**a,u=Math.sqrt(s*l);if(!Number.isFinite(u)||u<=0)return 1e6;const d=o/u;if(!Number.isFinite(d))return 1e6;const c=Math.floor(d*1e6);return c<0?0:c>1e6?1e6:c;}var Gn=1e6;function at(e){return e/Gn;}function We(e,t){if(e===0n)return 0;const n=e<0n?-1:1,r=e<0n?-e:e,a=10n**BigInt(t),i=r/a,o=r%a;return n*(Number(i)+Number(o)/Number(a));}function nt(e,t){return!Number.isFinite(e)||e<=0?0n:BigInt(Math.floor(e*10**t));}function Ic(e,t){return!Number.isFinite(e)||e<=0?0n:BigInt(Math.ceil(e*10**t));}function Nt(e,t){return!Number.isFinite(e)||e<=0?0n:BigInt(Math.floor(e*t));}function it(e){const{market:t,vault:n,deposit:r}=e,{sqrtPriceX96:a,borrowIndexWad:i,decimals0:o,decimals1:s}=t,l=mt(a,o,s),u=Ot(a,o,s),d=Number(n.rL0)*Number(i)/1e18,c=10**((o+s)/2),p=d/c,y=We(n.x0,o),b=We(n.y0,s),m=We(r,o),h=We(e.yWtarget,s),g=y+m-p/l,v=b-p*l;return{sqrtP:l,p:u,xEff:g,yEff:v,gammaPreHuman:p,gammaScale:c,x0Human:y,y0Human:b,dHuman:m,yWHuman:h};}function jn(e){const t=at(e.tauPips);if(t<=0||t>=1)return _n("infeasible-existing-debt",e);const{sqrtP:n,xEff:r,yEff:a,gammaPreHuman:i,gammaScale:o,yWHuman:s}=it(e);if(e.yWtarget===0n){const{decimals0:T}=e.market,L=r+i/n;return{regime:"no-new-borrow",feasible:!0,gammaTotalL:Nt(i,o),gammaNewL:0n,xV:nt(Math.max(0,L),T),yV:e.vault.y0};}const l=s-a,u=1-t*t,d=t*t*(r*n-l/n),c=t*t*r*l,p=d*d-4*u*c;if(p<0||u<=0)return _n("infeasible-existing-debt",e);const y=Math.sqrt(p),b=(d-y)/(2*u),m=(d+y)/(2*u);let h,g;if(i>m||(i<b?(h="needs-borrow",g=b):(h="no-new-borrow",g=i),!Number.isFinite(g)||g<0))return _n("infeasible-existing-debt",e);const v=Math.max(0,g-i),w=r+g/n,E=a+g*n-s,{decimals0:A,decimals1:I}=e.market;return{regime:h,feasible:E>=0&&w>=0,gammaTotalL:Nt(g,o),gammaNewL:Nt(v,o),xV:nt(w,A),yV:nt(E,I)};}function Gr(e,t,n){const r={feasible:!1,gammaMinHuman:0,gammaMaxHuman:0,q:t,minOut:n},a=at(e.tauPips);if(a<=0||a>=1||t<=0n)return r;const{sqrtP:i,xEff:o,yEff:s,yWHuman:l}=it(e),u=We(t,e.market.decimals0),d=We(n,e.market.decimals1),c=o-u,p=s-l+d,y=1-a*a,b=-a*a*(c*i+p/i),m=-a*a*c*p;if(y<=0)return r;const h=b*b-4*y*m;if(h<0||!Number.isFinite(h))return r;const g=Math.sqrt(h),v=(-b-g)/(2*y),w=(-b+g)/(2*y),E=Math.max(0,v),A=w;return!Number.isFinite(E)||!Number.isFinite(A)||A<=0||E>A?r:{feasible:!0,gammaMinHuman:E,gammaMaxHuman:A,q:t,minOut:n};}var xc=1;function jr(e,t,n,r){const a=at(e.tauPips);if(a<=0||a>=1||!Number.isFinite(t)||t<0||n<0n)return Ft();const{sqrtP:i,xEff:o,yEff:s,gammaPreHuman:l,gammaScale:u,yWHuman:d}=it(e),c=We(n,e.market.decimals0),p=We(r,e.market.decimals1),y=o+t/i-c,b=s+t*i+p-d;if(!Number.isFinite(y)||!Number.isFinite(b)||y<0||b<0)return Ft();const m=(e.tauPips+xc)/Gn,h=y*b;if(h<=0)return Ft();const g=t/Math.sqrt(h);if(!Number.isFinite(g)||g>m)return Ft();const v=Math.max(0,t-l),{decimals0:w,decimals1:E}=e.market;return{feasible:!0,gammaTotalL:Nt(t,u),gammaNewL:Nt(v,u),qPreview:n,swapInputIsToken0:!0,// canonical
|
|
1038
|
+
xV:nt(y,w),yV:nt(b,E)};}function kc(e,t,n){const r=at(e.tauPips);if(r<=0||r>=1||t<=0n||n<=0n)return 0n;const{sqrtP:a,xEff:i,yEff:o,gammaPreHuman:s,yWHuman:l}=it(e);if(s<=0)return 0n;const u=We(t,e.market.decimals0),d=We(n,e.market.decimals1);if(u<=0)return 0n;const c=d/u;if(c<=0||!Number.isFinite(c))return 0n;const p=c*0.998,y=i+s/a,b=o+s*a-l,m=p,h=-(y*p-b),g=s*s/(r*r)-y*b;if(m<=0)return 0n;const v=h*h-4*m*g;if(v<0||!Number.isFinite(v))return 0n;const w=Math.sqrt(v),E=(-h-w)/(2*m);return!Number.isFinite(E)||E<=0?0n:Ic(E,e.market.decimals0);}function Vo(e,t){const n=at(e.tauPips);if(n<=0||n>=1||!Number.isFinite(t)||t<0)return 0;const{sqrtP:r,p:a,xEff:i,yEff:o}=it(e),s=i+t/r;return s<=0?0:t===0?Math.max(0,o+a*s):s-t/(n*r)<=0?Math.max(0,o+t*r-t*t/(n*n*s)):Math.max(0,o+t*r+a*s-2*t*r/n);}function Uo(e){return Wo(e).yMax;}function Wo(e){const t=at(e.tauPips);if(t<=0||t>=1)return{yMax:0n,gammaNewL:0n};const n=sr(t);if(n<=0||n>=1)return{yMax:0n,gammaNewL:0n};const{sqrtP:r,xEff:a,gammaPreHuman:i,gammaScale:o}=it(e),s=a>0?a*r*(1-n)/n:0,l=Math.max(s,i);if(l<=0)return{yMax:0n,gammaNewL:0n};const u=nt(Vo(e,l),e.market.decimals1),d=Math.max(0,l-i),c=Nt(d,o);return{yMax:u,gammaNewL:c};}function $o(e){const{gammaPreHuman:t}=it(e);return nt(Vo(e,t),e.market.decimals1);}function Dc(e){const t=Uo(e),n=$o(e);return t>n?t:n;}function Nc(e){return!Number.isFinite(e)||e<0?0:e>=Gn?1:e/Gn;}function Ho(e,t,n){const r=at(e.tauPips);if(r<=0||r>=1||!Number.isFinite(t)||t<0)return 0;const{sqrtP:a,p:i,xEff:o,yEff:s}=it(e),l=Nc(n),u=i*(1-l),d=a*Math.sqrt(Math.max(0,1-l)),c=o+t/a;return c<=0?0:t===0&&u>0?Math.max(0,s+u*c):(d>0?c-t/(r*d):Number.NEGATIVE_INFINITY)<=0?Math.max(0,s+t*a-t*t/(r*r*c)):Math.max(0,s+t*a+u*c-2*t*d/r);}function Lc(e,t){return Pc(e,t).yMax;}function Pc(e,t){const n=at(e.tauPips);if(n<=0||n>=1)return{yMax:0n,gammaNewL:0n};const r=sr(n);if(r<=0||r>=1)return{yMax:0n,gammaNewL:0n};const{sqrtP:a,xEff:i,gammaPreHuman:o,gammaScale:s}=it(e),l=i>0?i*a*(1-r)/r:0,u=Math.max(l,o);if(u<=0)return{yMax:0n,gammaNewL:0n};const d=nt(Ho(e,u,t),e.market.decimals1),c=Math.max(0,u-o),p=Nt(c,s);return{yMax:d,gammaNewL:p};}function _c(e,t){const{gammaPreHuman:n}=it(e);return nt(Ho(e,n,t),e.market.decimals1);}function Cc(e){const t=at(e.tauPips);if(t<=0||t>=1)return!1;const n=sr(t);if(n<=0||n>=1)return!1;const{market:r,vault:a}=e,i=mt(r.sqrtPriceX96,r.decimals0,r.decimals1),o=Number(a.rL0)*Number(r.borrowIndexWad)/1e18,s=Math.pow(10,(r.decimals0+r.decimals1)/2),l=o/s;return(We(a.x0,r.decimals0)-l/i)*i*(1-n)/n>=l;}function zo(e){const t=at(e.tauPips);if(t<=0||t>=1)return null;const n=sr(t);if(n<=0||n>=1)return null;const{market:r,vault:a}=e,i=mt(r.sqrtPriceX96,r.decimals0,r.decimals1),o=Ot(r.sqrtPriceX96,r.decimals0,r.decimals1),s=Number(a.rL0)*Number(r.borrowIndexWad)/1e18/Math.pow(10,(r.decimals0+r.decimals1)/2),l=We(a.x0,r.decimals0),u=We(a.y0,r.decimals1),d=We(e.yWtarget,r.decimals1),c=u-s*i;if(d<=u){const y=u-d;if(y>=0){const b=t*Math.sqrt(Math.max(0,l*y));if(s<=b)return 0n;}}if(!Cc(e))return null;const p=(d-c)*(1+n)/(o*(1-n))-l+s/i;return Number.isFinite(p)?nt(Math.max(0,p),r.decimals0):null;}var Pi=xo*ie;function Mc(e){const t=1000000000n,n=(e+t-1n)/t;return n>Pi?n:Pi;}function Jt(e,t){return t===0n?0n:(Mc(e)+t-1n)/t;}function _n(e,t){return{regime:e,feasible:!1,gammaTotalL:0n,gammaNewL:0n,xV:t.vault.x0+t.deposit,yV:t.vault.y0};}function Ft(){return{feasible:!1,gammaTotalL:0n,gammaNewL:0n,qPreview:0n,swapInputIsToken0:!0,xV:0n,yV:0n};}function Go(e,t){if(t===0n)throw new Error("divCeil: divide by zero");return(e+t-1n)/t;}function xa(e,t){if(e<=0n)return 0n;if(t<=0n)throw new Error("lToRlRoundUp: borrowIndexWad must be positive");return Go(e*ie,t);}function Ke(e,t){if(e<=0n)return 0n;if(t<=0n)throw new Error("rlToL: borrowIndexWad must be positive");return Go(e*t,ie);}function Rc(e){const{market:t,vault:n,deposit:r,withdraw:a,borrowGammaNewL:i,swap:o,maxLtvPips:s,deadline:l,owner:u,permit:d}=e,c=new ft(),{poolKey:p,borrowIndexWad:y}=t,b=xa(i,y);if(b>0n){const A=((n==null?void 0:n.rL0)??0n)+b,I=Jt(t.equityLWad,y);if(A<I)throw new Error(`buildBorrowRecipe: post-borrow rL (${A}) is below the engine's min-debt floor (${I}); lockVault would revert ERR_VAULT_DEBT_BELOW_MINIMUM. Use a larger γ_new or top up the vault before borrowing.`);}if(b===0n&&o.enabled&&o.input>0n){const A=o.inputIsToken0?r.amount0:r.amount1,I=o.inputIsToken0?(n==null?void 0:n.x0)??0n:(n==null?void 0:n.y0)??0n;if(A+I<o.input)throw new Error(`buildBorrowRecipe: zero-debt swap recipe requires the swap input (${o.input}) to be funded by fresh deposit + pre-existing vault idle on the input side; got deposit=${A}, idle=${I}. Add deposit, fund vault idle, or borrow new debt.`);}n===null?(c.addCreateVault(t.poolId,u),c.addUnlockVault(bt)):c.addUnlockVault(n.vaultId);const m=n===null?bt:n.vaultId;(r.amount0>0n||r.amount1>0n)&&(c.addModifyIdle(m,Mt(r.amount0,r.amount1)),r.amount0>0n&&c.addCloseAE(p.currency0),r.amount1>0n&&c.addCloseAE(p.currency1)),b>0n&&c.addModifyDebt(m,b),o.enabled&&o.input>0n&&(Ea(o.route,o,p.currency0,p.currency1,o.slippageBps??50),qo(c,{vaultId:m,poolKey:p,input:o.input,minOutput:o.minOutput,inputIsToken0:o.inputIsToken0,deposit0:o.inputIsToken0?0n:o.minOutput,deposit1:o.inputIsToken0?o.minOutput:0n,route:o.route,slippageBps:o.slippageBps??50,surplusRecipient:(n==null?void 0:n.owner)??u})),(a.amount0>0n||a.amount1>0n)&&(c.addModifyIdle(m,or(a.amount0,a.amount1)),a.amount0>0n&&c.addTakeAE(p.currency0,ze),a.amount1>0n&&c.addTakeAE(p.currency1,ze)),c.addLockVault(m,BigInt(s)),c.addCloseCurrency(p.currency0),c.addCloseCurrency(p.currency1);const h=p.currency0===ke,g=p.currency1===ke,v=o.enabled&&o.input>0n&&(o.inputIsToken0?g:h);(h||g)&&!v&&c.addSweep(h?p.currency0:p.currency1,ze);const w=c.finalize({requiresV4Unlock:!0}),E=h?r.amount0:g?r.amount1:0n;return Ze.encodeExecuteWithOptionalPermit([w],l,E,d);}function _i(e){const{market:t,vault:n,principalDeltaRl:r,source:a,maxLtvPips:i,maxEngineTokenDebit0:o=0n,maxEngineTokenDebit1:s=0n,minLiquidityDelta:l=0n,deadline:u,permit:d}=e,c=new ft(),{poolKey:p}=t;if(r<0n)throw new Error(`buildRepayRecipe: principalDeltaRl must be ≥ 0; got ${r}`);if(r>n.rL0)throw new Error(`buildRepayRecipe: principalDeltaRl (${r}) exceeds vault.rL0 (${n.rL0}); engine would revert via SafeCast underflow on _safeAdd`);Oo({fn:"buildRepayRecipe",principalLabel:"principalDeltaRl",principal:r,maxEngineTokenDebit0:o,maxEngineTokenDebit1:s}),c.addUnlockVault(n.vaultId),(a.fromWallet0>0n||a.fromWallet1>0n)&&(c.addModifyIdle(n.vaultId,Mt(a.fromWallet0,a.fromWallet1)),a.fromWallet0>0n&&c.addCloseAE(p.currency0),a.fromWallet1>0n&&c.addCloseAE(p.currency1)),a.source==="idle-swap"&&a.swapInput>0n&&(Ea(a.swapRoute,{input:a.swapInput,inputIsToken0:a.swapInputIsToken0,minOutput:a.swapOutputMin},p.currency0,p.currency1,a.swapSlippageBps??50),qo(c,{vaultId:n.vaultId,poolKey:p,input:a.swapInput,minOutput:a.swapOutputMin,inputIsToken0:a.swapInputIsToken0,deposit0:a.swapInputIsToken0?0n:a.swapOutputMin,deposit1:a.swapInputIsToken0?a.swapOutputMin:0n,route:a.swapRoute,slippageBps:a.swapSlippageBps??50,// Vault idle belongs to the owner, even when an operator submits repayment.
|
|
1039
|
+
surplusRecipient:n.owner})),c.addModifyLiquidity(t.poolId,0n,n.owner),r>0n&&c.addModifyDebt(n.vaultId,-r,l,-o,-s),c.addLockVault(n.vaultId,BigInt(i));const y=p.currency0===ke,b=p.currency1===ke,m=a.source==="idle-swap"&&a.swapInput>0n&&(a.swapInputIsToken0?b:y);(y||b)&&!m&&c.addSweep(y?p.currency0:p.currency1,ze);const h=c.finalize({requiresV4Unlock:!0}),g=y?a.fromWallet0:b?a.fromWallet1:0n;return Ze.encodeExecuteWithOptionalPermit([h],u,g,d);}function Sc(e){const{market:t,vault:n,deposit:r,withdraw:a,maxLtvPips:i,deadline:o}=e,s=new ft(),{poolKey:l}=t;s.addUnlockVault(n.vaultId),(r.amount0>0n||r.amount1>0n)&&(s.addModifyIdle(n.vaultId,Mt(r.amount0,r.amount1)),r.amount0>0n&&s.addCloseAE(l.currency0),r.amount1>0n&&s.addCloseAE(l.currency1)),(a.amount0>0n||a.amount1>0n)&&(s.addModifyIdle(n.vaultId,or(a.amount0,a.amount1)),a.amount0>0n&&s.addTakeAE(l.currency0,ze),a.amount1>0n&&s.addTakeAE(l.currency1,ze)),s.addLockVault(n.vaultId,BigInt(i)),s.addCloseCurrency(l.currency0),s.addCloseCurrency(l.currency1);const u=l.currency0===ke,d=l.currency1===ke;(u||d)&&s.addSweep(u?l.currency0:l.currency1,ze);const c=s.finalize({requiresV4Unlock:!0}),p=u?r.amount0:d?r.amount1:0n;return Ze.encodeExecute([c],o,p);}var Le=[{type:"constructor",inputs:[{name:"deps",type:"address",internalType:"contract IAegisDependencies"},{name:"_aegisEngine",type:"address",internalType:"contract IAegisEngine"},{name:"_limitOrderManager",type:"address",internalType:"contract ILimitOrderManager"}],stateMutability:"nonpayable"},{type:"function",name:"AEGIS_ENGINE",inputs:[],outputs:[{name:"",type:"address",internalType:"contract IAegisEngine"}],stateMutability:"view"},{type:"function",name:"LIMIT_ORDER_MANAGER",inputs:[],outputs:[{name:"",type:"address",internalType:"contract ILimitOrderManager"}],stateMutability:"view"},{type:"function",name:"POSITION_MANAGER",inputs:[],outputs:[{name:"",type:"address",internalType:"contract IPositionManager"}],stateMutability:"view"},{type:"function",name:"decodeBalanceDelta",inputs:[{name:"delta",type:"int256",internalType:"int256"}],outputs:[{name:"amount0",type:"int128",internalType:"int128"},{name:"amount1",type:"int128",internalType:"int128"}],stateMutability:"pure"},{type:"function",name:"getDefaultRateOracle",inputs:[],outputs:[{name:"rateOracle",type:"address",internalType:"address"},{name:"fullUtilRate",type:"uint64",internalType:"uint64"}],stateMutability:"view"},{type:"function",name:"getMarketBorrowIndex",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"borrowIndexWad",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getMarketBorrowedLWad",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"borrowedLWad",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getMarketBorrowedLWadLatest",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"borrowedLWadLatest",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getMarketEquity",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"equityLWad",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getMarketKey",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"key",type:"tuple",internalType:"struct PoolKey",components:[{name:"currency0",type:"address",internalType:"Currency"},{name:"currency1",type:"address",internalType:"Currency"},{name:"fee",type:"uint24",internalType:"uint24"},{name:"tickSpacing",type:"int24",internalType:"int24"},{name:"hooks",type:"address",internalType:"contract IHooks"}]}],stateMutability:"view"},{type:"function",name:"getMarketLastAccrue",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"lastAccrue",type:"uint40",internalType:"uint40"}],stateMutability:"view"},{type:"function",name:"getMarketLtvThresholds",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"maxLtvPips",type:"uint24",internalType:"uint24"},{name:"hardLtvPips",type:"uint24",internalType:"uint24"}],stateMutability:"view"},{type:"function",name:"getMarketProtocolFee",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"protocolFeePips",type:"uint24",internalType:"uint24"}],stateMutability:"view"},{type:"function",name:"getMarketRateOracle",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"rateOracle",type:"address",internalType:"address"},{name:"fullUtilRate",type:"uint64",internalType:"uint64"}],stateMutability:"view"},{type:"function",name:"getMarketResidues",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"residues",type:"int256",internalType:"BalanceDelta"}],stateMutability:"view"},{type:"function",name:"getMarketSharePriceWad",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"sharePriceWad",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getMarketSharePriceWadLatest",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"sharePriceWadLatest",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getMarketState",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"state",type:"tuple",internalType:"struct Market.State",components:[{name:"initialized",type:"bool",internalType:"bool"},{name:"totalRlBorrowed",type:"uint128",internalType:"uint128"},{name:"lastAccrue",type:"uint40",internalType:"uint40"},{name:"protocolFeePips",type:"uint24",internalType:"uint24"},{name:"maxLtvPips",type:"uint24",internalType:"uint24"},{name:"hardLtvPips",type:"uint24",internalType:"uint24"},{name:"borrowIndexWad",type:"uint256",internalType:"uint256"},{name:"equityLWad",type:"uint256",internalType:"uint256"},{name:"rateOracle",type:"address",internalType:"contract IVariableInterestRate"},{name:"fullUtilizationRate",type:"uint64",internalType:"uint64"},{name:"key",type:"tuple",internalType:"struct PoolKey",components:[{name:"currency0",type:"address",internalType:"Currency"},{name:"currency1",type:"address",internalType:"Currency"},{name:"fee",type:"uint24",internalType:"uint24"},{name:"tickSpacing",type:"int24",internalType:"int24"},{name:"hooks",type:"address",internalType:"contract IHooks"}]},{name:"residues",type:"int256",internalType:"BalanceDelta"}]}],stateMutability:"view"},{type:"function",name:"getMarketTotalDebt",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"totalRlBorrowed",type:"uint128",internalType:"uint128"}],stateMutability:"view"},{type:"function",name:"getMarketUtilizationPips",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"utilPips",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getMarketUtilizationPipsLatest",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"utilPipsLatest",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getOwner",inputs:[],outputs:[{name:"owner",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"getTotalSupply",inputs:[{name:"tokenId",type:"uint256",internalType:"uint256"}],outputs:[{name:"totalSupply",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getVaultCollateralFloor",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"}],outputs:[{name:"cMinL",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getVaultDebt",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"}],outputs:[{name:"rL",type:"uint128",internalType:"uint128"}],stateMutability:"view"},{type:"function",name:"getVaultIdleAmounts",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"}],outputs:[{name:"idle0",type:"uint128",internalType:"uint128"},{name:"idle1",type:"uint128",internalType:"uint128"}],stateMutability:"view"},{type:"function",name:"getVaultIdleBalances",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"}],outputs:[{name:"idleBalances",type:"int256",internalType:"BalanceDelta"}],stateMutability:"view"},{type:"function",name:"getVaultLtvPips",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"}],outputs:[{name:"ltvPips",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getVaultLtvPipsLatest",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"}],outputs:[{name:"ltvPipsLatest",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getVaultPoolId",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"}],outputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],stateMutability:"view"},{type:"function",name:"getVaultPosition",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"},{name:"index",type:"uint256",internalType:"uint256"}],outputs:[{name:"ref",type:"tuple",internalType:"struct NftRef",components:[{name:"kind",type:"uint8",internalType:"enum NftKind"},{name:"tokenId",type:"uint248",internalType:"uint248"}]}],stateMutability:"view"},{type:"function",name:"getVaultPositions",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"}],outputs:[{name:"positions",type:"tuple[]",internalType:"struct NftRef[]",components:[{name:"kind",type:"uint8",internalType:"enum NftKind"},{name:"tokenId",type:"uint248",internalType:"uint248"}]}],stateMutability:"view"},{type:"function",name:"getVaultPositionsLength",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"}],outputs:[{name:"length",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getVaultState",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"}],outputs:[{name:"state",type:"tuple",internalType:"struct Vault.State",components:[{name:"poolId",type:"bytes32",internalType:"PoolId"},{name:"idleBalances",type:"int256",internalType:"BalanceDelta"},{name:"rL",type:"uint128",internalType:"uint128"},{name:"positions",type:"tuple[]",internalType:"struct NftRef[]",components:[{name:"kind",type:"uint8",internalType:"enum NftKind"},{name:"tokenId",type:"uint248",internalType:"uint248"}]}]}],stateMutability:"view"},{type:"function",name:"getVaultStateWithPositions",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"}],outputs:[{name:"state",type:"tuple",internalType:"struct Vault.State",components:[{name:"poolId",type:"bytes32",internalType:"PoolId"},{name:"idleBalances",type:"int256",internalType:"BalanceDelta"},{name:"rL",type:"uint128",internalType:"uint128"},{name:"positions",type:"tuple[]",internalType:"struct NftRef[]",components:[{name:"kind",type:"uint8",internalType:"enum NftKind"},{name:"tokenId",type:"uint248",internalType:"uint248"}]}]}],stateMutability:"view"},{type:"function",name:"isHookAuthorized",inputs:[{name:"hook",type:"address",internalType:"address"}],outputs:[{name:"authorized",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isMarketInitialized",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"initialized",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"previewMarketAccrual",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"borrowIndexWadLatest",type:"uint256",internalType:"uint256"},{name:"equityLWadLatest",type:"uint256",internalType:"uint256"},{name:"fullUtilRateLatest",type:"uint64",internalType:"uint64"}],stateMutability:"view"}];async function jo(e,t,n,r){const a=await e.readContract({address:t,abi:Le,functionName:"getMarketState",args:[n],blockNumber:r});return Yo(a);}async function ka(e,t,n,r){const[a,i]=await Promise.all([e.readContract({address:t,abi:Le,functionName:"getMarketState",args:[n],blockNumber:r}),e.readContract({address:t,abi:Le,functionName:"previewMarketAccrual",args:[n],blockNumber:r})]);return{market:Yo(a),latestBorrowIndexWad:i[0],latestEquityLWad:i[1],latestFullUtilRate:i[2]};}async function Ko(e,t,n,r){return e.readContract({address:t,abi:Le,functionName:"getMarketSharePriceWadLatest",args:[n],blockNumber:r});}async function Oc(e,t,n){const[r,a]=await e.readContract({address:t,abi:Le,functionName:"getMarketLtvThresholds",args:[n]});return{maxLtvPips:r,hardLtvPips:a};}function Yo(e){const t={initialized:e.initialized,totalRlBorrowed:e.totalRlBorrowed,lastAccrue:e.lastAccrue,protocolFeePips:e.protocolFeePips,maxLtvPips:e.maxLtvPips,hardLtvPips:e.hardLtvPips,borrowIndexWad:e.borrowIndexWad,equityLWad:e.equityLWad,rateOracle:e.rateOracle,fullUtilizationRate:e.fullUtilizationRate,key:{currency0:e.key.currency0,currency1:e.key.currency1,fee:e.key.fee,tickSpacing:e.key.tickSpacing,hooks:e.key.hooks},residues:Aa(e.residues)};return Wu.fromRaw(t);}async function qc(e,t,n,r){return e.readContract({address:t,abi:Le,functionName:"getVaultCollateralFloor",args:[n],blockNumber:r});}async function Bc(e,t,n,r){const[a,i]=await e.readContract({address:t,abi:Le,functionName:"getVaultIdleAmounts",args:[n],blockNumber:r});return{idle0:a,idle1:i};}async function Fc(e,t,n,r){return e.readContract({address:t,abi:Le,functionName:"getVaultPoolId",args:[n],blockNumber:r});}async function Da(e,t,n,r){return(await e.readContract({address:t,abi:Le,functionName:"getVaultPositions",args:[n],blockNumber:r})).map(i=>({kind:i.kind,tokenId:i.tokenId}));}async function Qo(e,t,n,r){return e.readContract({address:t,abi:Ht,functionName:"ownerOf",args:[n],blockNumber:r});}var Ci=[{type:"function",name:"epochInfos",stateMutability:"view",inputs:[{name:"epoch",type:"uint232"}],outputs:[{name:"filled",type:"bool"},{name:"token0Total",type:"uint256"},{name:"token1Total",type:"uint256"},{name:"liquidityTotal",type:"uint128"}]},{type:"function",name:"orderFeeGrowthCursors",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"feeGrowth0LastX128",type:"uint256"},{name:"feeGrowth1LastX128",type:"uint256"}]},{type:"function",name:"epochPayouts",stateMutability:"view",inputs:[{name:"epoch",type:"uint232"}],outputs:[{name:"principal0PerLiquidityX128",type:"uint256"},{name:"principal1PerLiquidityX128",type:"uint256"},{name:"feeGrowth0EndX128",type:"uint256"},{name:"feeGrowth1EndX128",type:"uint256"}]},{type:"function",name:"orders",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"poolId",type:"bytes32"},{name:"epoch",type:"uint232"},{name:"tickLower",type:"int24"},{name:"zeroForOne",type:"bool"},{name:"liquidity",type:"uint128"}]},{type:"function",name:"poolKeys",stateMutability:"view",inputs:[{name:"poolId",type:"bytes32"}],outputs:[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}]}],Mi=[{type:"function",name:"getPoolAndPositionInfo",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"poolKey",type:"tuple",components:[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}]},{name:"info",type:"uint256"}]},{type:"function",name:"getPositionLiquidity",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"liquidity",type:"uint128"}]}];async function Gt(e,t){const n=t===void 0?await e.getBlock():await e.getBlock({blockNumber:t});if(n.hash===null)throw new Error("fetchReadFrame: pending block has no canonical hash");return{blockNumber:n.number,blockHash:n.hash,blockTimestamp:n.timestamp,observedAt:Date.now()};}var kn=class extends Error{constructor(t){super(`${t.fn}: read frame ${t.frameBlockNumber} changed from ${t.expectedBlockHash} to ${t.observedBlockHash}; re-quote required`);oe(this,"name","ReadFrameNotCanonicalError");/** Frame height whose canonical hash changed. */oe(this,"frameBlockNumber");/** Hash the frame was assembled at. */oe(this,"expectedBlockHash");/** Hash the same height resolves to now. */oe(this,"observedBlockHash");this.frameBlockNumber=t.frameBlockNumber,this.expectedBlockHash=t.expectedBlockHash,this.observedBlockHash=t.observedBlockHash;}};async function jt(e,t,n){const r=await e.getBlock({blockNumber:t.blockNumber});if(r.hash!==t.blockHash)throw new kn({fn:n,frameBlockNumber:t.blockNumber,expectedBlockHash:t.blockHash,observedBlockHash:r.hash});}function Vc(e,t,n){const r=n??60n;if(r<0n)throw new Error(`computeExpiresAt: quoteTtlSeconds must be >= 0, got ${r}`);const a=t.blockTimestamp+r;return e<a?e:a;}function Kr(e,t){return(e==null?void 0:e.blockTimestamp)??t??BigInt(Math.floor(Date.now()/1e3));}function ee(e,t){if(e!=null&&e.aborted)throw new Error(`${t}: aborted`);}async function Xo(e,t){if(ee(t.signal,"fetchVaultCollateralSnapshot"),t.maxPositions!==void 0&&(!Number.isSafeInteger(t.maxPositions)||t.maxPositions<0))throw new RangeError("fetchVaultCollateralSnapshot: maxPositions must be a non-negative safe integer");if(t.metadataConcurrency!==void 0&&(!Number.isSafeInteger(t.metadataConcurrency)||t.metadataConcurrency<1))throw new RangeError("fetchVaultCollateralSnapshot: metadataConcurrency must be a positive safe integer");const{addresses:n}=je(t.chainId,t.version,t.deployment),r=t.frame.blockNumber,[a,i,o,s,l,u]=await Promise.all([Da(e,n.aegisStateView,t.vaultId,r),Bc(e,n.aegisStateView,t.vaultId,r),qc(e,n.aegisStateView,t.vaultId,r),Fc(e,n.aegisStateView,t.vaultId,r),e.readContract({address:n.aegisStateView,abi:Le,functionName:"POSITION_MANAGER",blockNumber:r}),e.readContract({address:n.aegisStateView,abi:Le,functionName:"LIMIT_ORDER_MANAGER",blockNumber:r})]),d={vaultId:t.vaultId,version:t.version,blockNumber:r,blockHash:t.frame.blockHash,refs:a},c=(g,v)=>({...d,status:"unavailable",reason:g,detail:v});if(ee(t.signal,"fetchVaultCollateralSnapshot"),await jt(e,t.frame,"fetchVaultCollateralSnapshot"),ee(t.signal,"fetchVaultCollateralSnapshot"),s.toLowerCase()!==t.expectedPoolId.toLowerCase())return c("vault-pool-mismatch",`vault ${t.vaultId} belongs to ${s}, expected ${t.expectedPoolId}`);if(l.toLowerCase()!==n.positionManager.toLowerCase()||u.toLowerCase()!==n.limitOrderManager.toLowerCase())return c("manager-identity-mismatch",`StateView managers (${l}, ${u}) do not match the deployment registry (${n.positionManager}, ${n.limitOrderManager})`);if(t.maxPositions!==void 0&&a.length>t.maxPositions)return c("attached-position-limit-exceeded",`vault has ${a.length} positions, maximum ${t.maxPositions}`);ee(t.signal,"fetchVaultCollateralSnapshot");const p=/* @__PURE__ */new Set();for(const g of a){const v=`${g.kind}:${g.tokenId}`;if(p.has(v))return c("duplicate-position-ref",`duplicate attached position ${v}`);if(p.add(v),g.kind!==0&&g.kind!==1)return c("unsupported-position-kind",`attached position ${g.tokenId} has unsupported kind ${g.kind}`);}const y=new Array(a.length);let b=0;await Promise.all(Array.from({length:Math.min(a.length,t.metadataConcurrency??a.length)},async()=>{for(;;){const g=b++,v=a[g];if(!v)return;ee(t.signal,"fetchVaultCollateralSnapshot"),y[g]=v.kind===0?await Wc(e,n.positionManager,v.tokenId,r):await $c(e,n.limitOrderManager,v.tokenId,r,t.signal);}})),ee(t.signal,"fetchVaultCollateralSnapshot"),await jt(e,t.frame,"fetchVaultCollateralSnapshot"),ee(t.signal,"fetchVaultCollateralSnapshot");for(const g of y){for(const w of g.poolIds)if(w.toLowerCase()!==s.toLowerCase())return c("position-pool-mismatch",`position ${g.info.data.tokenId} belongs to ${w}, expected ${s}`);const v=Uc(g.info);if(v!==null)return c("invalid-position-metadata",v);}const m=y.map(({info:g})=>g),h=wa(t.version,{idle0:i.idle0,idle1:i.idle1,positions:m});return h!==o?c("contract-parity-mismatch",`SDK floor ${h} does not equal contract floor ${o}`):{...d,status:"verified-at-frame",basis:"sdk-contract-parity",poolId:s,idle0:i.idle0,idle1:i.idle1,positions:m,sdkFloorL:h,contractFloorL:o};}function Uc(e){const{tokenId:t,tickLower:n,tickUpper:r}=e.data;return n<ki||r>Di||n>=r?`position ${t} has invalid tick range [${n}, ${r}]; expected ${ki} <= lower < upper <= ${Di}`:null;}function Ri(e){const t=Number(e&0xffffffn);return t>=8388608?t-16777216:t;}async function Wc(e,t,n,r){const[[a,i],o]=await Promise.all([e.readContract({address:t,abi:Mi,functionName:"getPoolAndPositionInfo",args:[n],blockNumber:r}),e.readContract({address:t,abi:Mi,functionName:"getPositionLiquidity",args:[n],blockNumber:r})]);return{poolIds:[ar(a)],info:{kind:0,data:{tokenId:n,tickLower:Ri(i>>8n),tickUpper:Ri(i>>32n),liquidity:o}}};}async function $c(e,t,n,r,a){const[i,,o,,s]=await e.readContract({address:t,abi:Ci,functionName:"orders",args:[n],blockNumber:r});ee(a,"fetchVaultCollateralSnapshot");const[l,u,d,c,p]=await e.readContract({address:t,abi:Ci,functionName:"poolKeys",args:[i],blockNumber:r});return{// The stored id, plus the id of the `poolKeys` record `tickSpacing` came from.
|
|
1040
|
+
poolIds:[i,ar({currency0:l,currency1:u,fee:d,tickSpacing:c,hooks:p})],info:{kind:1,data:{tokenId:n,tickLower:o,tickUpper:o+c,liquidity:s}}};}var Cn=31688730000n;function Hc(e,t,n){const r=t.borrowIndexWad,a=t.equityLWad,i=t.lastAccrueTimestamp??n;if(n<=i)return{borrowIndexWadLatest:r,equityLWadLatest:a,fullUtilRateLatest:t.fullUtilRate};const o=n-i;let s=0n;a>0n&&(s=t.totalRlBorrowed*r*_e/a);const{ratePerSecondWad:l,newFullUtilRateWad:u}=e.getNewRate(o,s,t.fullUtilRate);let d=l,c=u;d>Cn&&(d=Cn),c>Cn&&(c=Cn);const p=r*(d*o)/ie,y=r+p,b=a+p*t.totalRlBorrowed;return{borrowIndexWadLatest:y,equityLWadLatest:b,fullUtilRateLatest:c};}var Si=ie,zc={vertexUtilization:800000n,vertex2Utilization:900000n,vertexRatePercent:500000000000000000n,// 0.5e18
|
|
1041
|
+
vertex2RatePercent:750000000000000000n,// 0.75e18
|
|
1042
|
+
minTargetUtil:750000n,maxTargetUtil:850000n,zeroUtilRate:0n,minFullUtilRate:1585489599n,maxFullUtilRate:31709791983n,rateHalfLife:43200n};function Gc(e,t,n){if(n===0n)throw new Error("mulDivFloor: division by zero");return e*t/n;}function jc(e,t,n,r){let a=r;if(n<e.minTargetUtil){const i=(e.minTargetUtil-n)*ie/e.minTargetUtil,o=e.rateHalfLife*ie*ie+i*i*t;a=r*(e.rateHalfLife*ie*ie)/o;}else if(n>e.maxTargetUtil){const i=(n-e.maxTargetUtil)*ie/(_e-e.maxTargetUtil),o=e.rateHalfLife*ie*ie+i*i*t;a=r*o/(e.rateHalfLife*ie*ie);}return a>e.maxFullUtilRate?e.maxFullUtilRate:a<e.minFullUtilRate?e.minFullUtilRate:a;}function Kc(e,t,n,r){const a=Gc(n,_e,In),i=jc(e,t,a,r),o=(i-e.zeroUtilRate)*e.vertexRatePercent/Si+e.zeroUtilRate,s=(i-e.zeroUtilRate)*e.vertex2RatePercent/Si+e.zeroUtilRate;let l;return a<e.vertexUtilization?l=e.zeroUtilRate+a*(o-e.zeroUtilRate)/e.vertexUtilization:a<e.vertex2Utilization?l=o+(a-e.vertexUtilization)*(s-o)/(e.vertex2Utilization-e.vertexUtilization):l=s+(a-e.vertex2Utilization)*(i-s)/(_e-e.vertex2Utilization),{ratePerSecondWad:l,newFullUtilRateWad:i};}var Dn=class Yr{constructor(t){oe(this,"config");Yr._validate(t),this.config=Object.freeze({...t});}/** Create an oracle with the default deployed config. */static default(){return new Yr(zc);}getNewRate(t,n,r){return Kc(this.config,t,n,r);}previewAccrual(t,n){return Hc(this,t,n);}/**
|
|
1043
|
+
* Validates config invariants matching the on-chain Solidity constructor.
|
|
1044
|
+
* Fails fast with clear error messages.
|
|
1045
|
+
*/static _validate(t){Be(t.maxTargetUtil>t.minTargetUtil,"VariableInterestRateV1: maxTargetUtil must be > minTargetUtil"),Be(t.maxFullUtilRate>t.minFullUtilRate,"VariableInterestRateV1: maxFullUtilRate must be > minFullUtilRate"),Be(t.zeroUtilRate<=t.minFullUtilRate,"VariableInterestRateV1: zeroUtilRate must be <= minFullUtilRate"),Be(t.vertexUtilization>0n,"VariableInterestRateV1: vertexUtilization must be > 0"),Be(t.vertexUtilization<_e,"VariableInterestRateV1: vertexUtilization must be < PIPS_DENOMINATOR"),Be(t.vertex2Utilization>t.vertexUtilization,"VariableInterestRateV1: vertex2Utilization must be > vertexUtilization"),Be(t.vertex2Utilization<_e,"VariableInterestRateV1: vertex2Utilization must be < PIPS_DENOMINATOR"),Be(t.vertexRatePercent<=ie,"VariableInterestRateV1: vertexRatePercent must be <= WAD"),Be(t.vertex2RatePercent>=t.vertexRatePercent,"VariableInterestRateV1: vertex2RatePercent must be >= vertexRatePercent"),Be(t.vertex2RatePercent<=ie,"VariableInterestRateV1: vertex2RatePercent must be <= WAD"),Be(t.rateHalfLife>0n,"VariableInterestRateV1: rateHalfLife must be > 0"),Be(t.maxTargetUtil<=_e,"VariableInterestRateV1: maxTargetUtil must be <= PIPS_DENOMINATOR"),Be(t.maxFullUtilRate<=ie,"VariableInterestRateV1: maxFullUtilRate must be <= WAD");}},Yc=class{constructor(e,t){oe(this,"chainId");oe(this,"version");oe(this,"entries",/* @__PURE__ */new Map());this.chainId=e,this.version=t;}/** Register an oracle for a given contract address. */register(e,t){this.entries.set(e.toLowerCase(),t);}/** Look up the registry entry for an address. Returns undefined if unknown. */get(e){return this.entries.get(e.toLowerCase());}/** Resolve an InterestRateOracle instance for an address. Throws if unknown. */resolve(e){const t=this.get(e);if(!t)throw new Error(`OracleRegistry: unknown oracle address ${e} on chain ${this.chainId} (${this.version})`);return t.factory();}/** Check if an address is registered. */has(e){return this.entries.has(e.toLowerCase());}};function Zo(e,t,n){const r=new Yc(e,t),{addresses:a}=je(e,t,n);return r.register(a.variableInterestRate,{type:"VariableInterestRateV1",factory:()=>Dn.default()}),r;}function Jo(e){const t=e.deployment?je(e.chainId,e.version,e.deployment):void 0;if(e.rateModel)return{status:"ok",oracle:e.rateModel};if(!t&&!va(e.chainId,e.version))return{status:"unsupported",reason:"chain-version-unregistered"};const n=je(e.chainId,e.version,t).addresses.variableInterestRate;if(e.rateOracle.toLowerCase()!==n.toLowerCase())return{status:"unsupported",reason:"oracle-not-canonical"};const r=Zo(e.chainId,e.version,t);return r.has(e.rateOracle)?{status:"ok",oracle:r.resolve(e.rateOracle)}:{status:"unsupported",reason:"oracle-not-registered"};}function Kn(e){return e instanceof oa&&e.walk(t=>t instanceof Ji)!==null;}function qn(e){if(Kn(e))return null;throw e;}var es=[{type:"function",name:"getPositionInfo",stateMutability:"view",inputs:[{name:"poolId",type:"bytes32"},{name:"owner",type:"address"},{name:"tickLower",type:"int24"},{name:"tickUpper",type:"int24"},{name:"salt",type:"bytes32"}],outputs:[{name:"liquidity",type:"uint128"},{name:"feeGrowthInside0LastX128",type:"uint256"},{name:"feeGrowthInside1LastX128",type:"uint256"}]},{type:"function",name:"getFeeGrowthInside",stateMutability:"view",inputs:[{name:"poolId",type:"bytes32"},{name:"tickLower",type:"int24"},{name:"tickUpper",type:"int24"}],outputs:[{name:"feeGrowthInside0X128",type:"uint256"},{name:"feeGrowthInside1X128",type:"uint256"}]},{type:"function",name:"getSlot0",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"sqrtPriceX96",type:"uint160",internalType:"uint160"},{name:"tick",type:"int24",internalType:"int24"},{name:"protocolFee",type:"uint24",internalType:"uint24"},{name:"lpFee",type:"uint24",internalType:"uint24"}],stateMutability:"view"},{type:"function",name:"getLiquidity",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"}],outputs:[{name:"liquidity",type:"uint128",internalType:"uint128"}],stateMutability:"view"}];async function Na(e,t,n,r){const[a,i,o,s]=await e.readContract({address:t,abi:es,functionName:"getSlot0",args:[n],blockNumber:r});return{sqrtPriceX96:a,tick:i,protocolFee:o,lpFee:s};}async function La(e,t,n,r){return e.readContract({address:t,abi:es,functionName:"getLiquidity",args:[n],blockNumber:r});}async function ts(e,t,n,r){const[a,i]=await Promise.all([Na(e,t,n,r),La(e,t,n,r)]);return{...a,liquidity:i};}var Lr=1000000n;async function ns(e,t){const{aegisStateView:n,v4StateView:r,poolId:a,blockNumber:i}=t;if(!t.rateModel&&!t.variableInterestRateV1Address)throw new Error("fetchBorrowMarketContext: must provide either `variableInterestRateV1Address` (canonical VariableInterestRateV1 deployment for this chain) or `rateModel` (explicit oracle override). Refuse to guess.");const[o,s,l]=await Promise.all([ka(e,n,a,i),Na(e,r,a,i),La(e,r,a,i)]),{market:u,latestBorrowIndexWad:d,latestEquityLWad:c,latestFullUtilRate:p}=o;if(!u.initialized)throw new Error(`fetchBorrowMarketContext: market not initialized for poolId ${a}`);if(!t.rateModel){const I=t.variableInterestRateV1Address.toLowerCase();if(u.rateOracle.toLowerCase()!==I)throw new Error(`fetchBorrowMarketContext: market.rateOracle (${u.rateOracle}) is not the canonical VariableInterestRateV1 deployment for this chain (${t.variableInterestRateV1Address}). Pass an explicit \`rateModel\` override.`);}const y=t.rateModel??Dn.default(),b=u.poolKey.currency0===ke,m=u.poolKey.currency1===ke,[h,g]=await Promise.all([b?Promise.resolve(18):e.readContract({address:u.poolKey.currency0,abi:qr,functionName:"decimals",blockNumber:i}),m?Promise.resolve(18):e.readContract({address:u.poolKey.currency1,abi:qr,functionName:"decimals",blockNumber:i})]),v=u.totalRlBorrowed*d,w=c>0n?v*Lr/c:0n,E=w>Lr?Lr:w,{ratePerSecondWad:A}=y.getNewRate(0n,E,p);return{context:{poolId:a,poolKey:u.poolKey,sqrtPriceX96:s.sqrtPriceX96,tickCurrent:s.tick,tickSpacing:u.poolKey.tickSpacing,inRangeLiquidity:l,borrowIndexWad:d,equityLWad:c,borrowedLWad:v,maxLtvPips:u.maxLtvPips,hardLtvPips:u.hardLtvPips,currentRatePerSecWad:A,decimals0:h,decimals1:g},rateOracle:u.rateOracle,latestFullUtilRate:p};}async function rs(e,t){var s;if(t.frame!==void 0&&t.blockNumber!==void 0&&t.frame.blockNumber!==t.blockNumber)throw new Error(`fetchBorrowVaultContext: frame block ${t.frame.blockNumber} does not match blockNumber ${t.blockNumber}`);const n=((s=t.frame)==null?void 0:s.blockNumber)??t.blockNumber,[r,a]=await Promise.all([e.readContract({address:t.aegisStateView,abi:Le,functionName:"getVaultState",args:[t.vaultId],blockNumber:n}),Da(e,t.aegisStateView,t.vaultId,n)]);if(t.expectedPoolId!==void 0&&r.poolId!==t.expectedPoolId)throw new Error(`fetchBorrowVaultContext: vault ${t.vaultId} belongs to poolId ${r.poolId}, not the expected ${t.expectedPoolId}`);t.frame!==void 0&&(await jt(e,t.frame,"fetchBorrowVaultContext"));const{amount0:i,amount1:o}=Aa(r.idleBalances);return{vaultId:t.vaultId,poolId:r.poolId,owner:t.owner,x0:i,y0:o,rL0:r.rL,...(t.frame!==void 0?{attachedPositionEvidence:{vaultId:t.vaultId,blockNumber:t.frame.blockNumber,blockHash:t.frame.blockHash,refs:a}}:{})};}async function Qc(e,t){const{chainId:n,version:r,poolId:a}=t;if(!t.deployment&&!va(n,r))return{status:"unsupported-oracle",reason:"chain-version-unregistered",rateOracle:null,frame:await Gt(e,t.blockNumber)};const i=je(n,r,t.deployment),{addresses:o}=i,s=await Gt(e,t.blockNumber),l=t.rateModel??Dn.default(),[u,d,c,p,y]=await Promise.all([ns(e,{aegisStateView:o.aegisStateView,v4StateView:o.stateView,poolId:a,rateModel:l,blockNumber:s.blockNumber}),t.owner!==void 0?e.readContract({address:o.vaultRegistry,abi:Ht,functionName:"isApprovedForAll",args:[t.owner,o.aegisRouterV1],blockNumber:s.blockNumber}):Promise.resolve(null),t.owner!==void 0&&t.vaultId!==void 0?e.readContract({address:o.vaultRegistry,abi:Ht,functionName:"getApproved",args:[t.vaultId],blockNumber:s.blockNumber}).catch(qn):Promise.resolve(null),t.owner!==void 0&&t.vaultId!==void 0?Qo(e,o.vaultRegistry,t.vaultId,s.blockNumber).catch(qn):Promise.resolve(null),t.owner!==void 0&&t.vaultId!==void 0?e.readContract({address:o.aegisStateView,abi:Le,functionName:"getVaultPoolId",args:[t.vaultId],blockNumber:s.blockNumber}).catch(qn):Promise.resolve(null)]);xn(i,u.context.poolKey.hooks);const b=Jo({deployment:i,chainId:n,version:r,rateOracle:u.rateOracle,rateModel:t.rateModel});if(b.status==="unsupported")return{status:"unsupported-oracle",reason:b.reason,rateOracle:u.rateOracle,frame:s};const m=t.owner===void 0||d===null?null:{owner:t.owner,vaultId:t.vaultId??null,chainId:n,permit2:o.permit2,ownerOnChain:p,vaultPoolId:y,routerApproved:d||c!==null&&c.toLowerCase()===o.aegisRouterV1.toLowerCase(),router:o.aegisRouterV1,vaultRegistry:o.vaultRegistry,blockNumber:s.blockNumber};return{status:"ok",context:{deployment:i,chainId:n,version:r,poolId:a,market:u.context,aprProjection:{...(t.deployment?{deployment:i}:{}),chainId:n,version:r,rateOracleAddress:u.rateOracle,fullUtilRate:u.latestFullUtilRate,// An explicit override must drive the post-borrow projection too —
|
|
1046
|
+
// otherwise estimatePostBorrowRate reconstructs the DEFAULT oracle
|
|
1047
|
+
// and silently projects a custom market with canonical math.
|
|
1048
|
+
...(t.rateModel?{rateModel:t.rateModel}:{})},authorization:m,rateOracle:u.rateOracle,latestFullUtilRate:u.latestFullUtilRate,frame:s}};}async function Pa(e,t,n,r){const a=BigInt(n);return e.readContract({address:t,abi:Le,functionName:"getTotalSupply",args:[a],blockNumber:r});}async function Xc(e,t){const{chainId:n,version:r,poolId:a}=t,i=je(n,r,t.deployment),{addresses:o}=i,s=await Gt(e,t.blockNumber),l=s.blockNumber,[u,d,c,p,y]=await Promise.all([jo(e,o.aegisStateView,a,l),Na(e,o.stateView,a,l),La(e,o.stateView,a,l),Pa(e,o.aegisStateView,a,l),Ko(e,o.aegisStateView,a,l)]);xn(i,u.poolKey.hooks);const b={poolId:a,poolKey:u.poolKey,sqrtPriceX96:d.sqrtPriceX96,tickCurrent:d.tick,inRangeLiquidity:c,lpFeePips:d.lpFee},m={poolId:a,borrowIndexWad:u.borrowIndexWad,equityLWad:u.equityLWad,totalRlBorrowed:u.totalRlBorrowed,rateOracle:u.rateOracle,fullUtilRate:u.fullUtilizationRate,maxLtvPips:BigInt(u.maxLtvPips),hardLtvPips:BigInt(u.hardLtvPips),lastAccrueTimestamp:BigInt(u.lastAccrue)},h=Zc(t,m,p,s);return{deployment:i,chainId:n,version:r,poolId:a,market:b,snapshot:m,totalShares:p,sharePriceWad:y,apy:h,frame:s};}function Zc(e,t,n,r){const a=Jo({chainId:e.chainId,version:e.version,rateOracle:t.rateOracle,rateModel:e.rateModel,deployment:e.deployment});return a.status==="unsupported"?{available:!1,reason:a.reason}:{available:!0,projection:{market:t,totalShares:n,oracle:a.oracle,nowTimestamp:r.blockTimestamp}};}async function Jc(e,t,n,r){return e.readContract({address:t,abi:qr,functionName:"balanceOf",args:[n],blockNumber:r});}var as=[{type:"function",name:"balanceOf",inputs:[{name:"owner",type:"address"},{name:"id",type:"uint256"}],outputs:[{name:"",type:"uint256"}],stateMutability:"view"}];async function ed(e,t,n,r,a){const i=BigInt(r);return e.readContract({address:t,abi:as,functionName:"balanceOf",args:[n,i],blockNumber:a});}async function td(e,t){const n=t.vaultIds??[],r=t.sharePositions??[],a=je(t.chainId,t.version,t.deployment),{addresses:i}=a,o=await Gt(e,t.blockNumber);ee(t.signal,"fetchPositionsBatch");const s={blockNumber:o.blockNumber,chunkSize:t.chunkSize??50,concurrency:t.concurrency??4,signal:t.signal},l=[];for(const T of n)l.push({address:i.vaultRegistry,abi:Ht,functionName:"ownerOf",args:[T]}),l.push({address:i.aegisStateView,abi:Le,functionName:"getVaultState",args:[T]});for(const T of r)l.push({address:i.aegisEngine,abi:as,functionName:"balanceOf",args:[T.account,BigInt(T.poolId)]});const u=await Oi(e,l,s);ee(t.signal,"fetchPositionsBatch");const d=n.map((T,L)=>{const x=u[2*L],k=u[2*L+1];if(k.status==="failure")return{vaultId:T,failure:{reason:"read-error",detail:k.detail}};if(x.status==="failure")return{vaultId:T,failure:{reason:x.contractLevel?"vault-burned":"read-error",detail:x.detail}};const _=x.result;if(t.expectedOwner&&_.toLowerCase()!==t.expectedOwner.toLowerCase())return{vaultId:T,failure:{reason:"owner-mismatch",detail:`live owner is ${_}`}};const D=k.result,P=Aa(D.idleBalances);return{vaultId:T,owner:_,poolId:D.poolId,idle0:P.amount0,idle1:P.amount1,rL:D.rL};}),c=r.map((T,L)=>{const x=u[2*n.length+L];return x.status==="failure"?{position:T,failure:{detail:x.detail}}:{position:T,shareBalance:x.result};}),p=d.filter(T=>T.failure===void 0),y=/* @__PURE__ */new Map();for(const T of[...p.map(L=>L.poolId),...r.map(L=>L.poolId)]){const L=T.toLowerCase();y.has(L)||y.set(L,T);}const b=[...y.values()],m=4,h=b.flatMap(T=>[{address:i.aegisStateView,abi:Le,functionName:"previewMarketAccrual",args:[T]},{address:i.aegisStateView,abi:Le,functionName:"getMarketLtvThresholds",args:[T]},{address:i.aegisStateView,abi:Le,functionName:"getTotalSupply",args:[BigInt(T)]},{address:i.aegisStateView,abi:Le,functionName:"getMarketSharePriceWadLatest",args:[T]}]),g=p.filter(T=>T.rL>0n);for(const T of g)h.push({address:i.aegisStateView,abi:Le,functionName:"getVaultLtvPipsLatest",args:[T.vaultId]});const v=await Oi(e,h,s);l.length>0&&(await jt(e,o,"fetchPositionsBatch"));const w=/* @__PURE__ */new Map();b.forEach((T,L)=>{const[x,k,_,D]=v.slice(L*m,(L+1)*m);if(x.status==="failure"||k.status==="failure"||_.status==="failure"||D.status==="failure"){w.set(T.toLowerCase(),null);return;}const[P,W]=x.result;if(P<=0n){w.set(T.toLowerCase(),null);return;}const[q,R]=k.result;w.set(T.toLowerCase(),{borrowIndexWadLatest:P,equityLWadLatest:W,maxLtvPips:q,hardLtvPips:R,totalShares:_.result,sharePriceWad:D.result});});const E=/* @__PURE__ */new Map();g.forEach((T,L)=>{E.set(T.vaultId,v[b.length*m+L]);});const A=d.map(T=>{if(T.failure)return{status:"failed",vaultId:T.vaultId,reason:T.failure.reason,...(T.failure.detail!==void 0?{detail:T.failure.detail}:{})};const L=w.get(T.poolId.toLowerCase());if(!L)return{status:"failed",vaultId:T.vaultId,reason:"read-error",detail:`market read failed for pool ${T.poolId}`};let x=null;if(T.rL>0n){const k=E.get(T.vaultId);if(k.status==="failure")return{status:"failed",vaultId:T.vaultId,reason:"read-error",detail:k.detail};x=k.result;}return{status:"ok",vault:{vaultId:T.vaultId,poolId:T.poolId,owner:T.owner,rL:T.rL,debtLLatest:Ke(T.rL,L.borrowIndexWadLatest),idle0:T.idle0,idle1:T.idle1,ltvPipsLatest:x,maxLtvPips:L.maxLtvPips,hardLtvPips:L.hardLtvPips}};}),I=c.map(({position:T,failure:L,shareBalance:x})=>{if(L)return{status:"failed",account:T.account,poolId:T.poolId,reason:"read-error",...(L.detail!==void 0?{detail:L.detail}:{})};const k=w.get(T.poolId.toLowerCase());return k?{status:"ok",account:T.account,poolId:T.poolId,shareBalance:x,totalShares:k.totalShares,sharePriceWad:k.sharePriceWad,equityLWad:k.equityLWadLatest}:{status:"failed",account:T.account,poolId:T.poolId,reason:"read-error",detail:`market read failed for pool ${T.poolId}`};});return{deployment:a,frame:o,vaults:A,shares:I};}async function Oi(e,t,n){var u,d,c;if(t.length===0)return[];const r=Math.max(1,n.chunkSize),a=[];for(let p=0;p<t.length;p+=r)a.push(t.slice(p,p+r));const i=((c=(d=(u=e.chain)==null?void 0:u.contracts)==null?void 0:d.multicall3)==null?void 0:c.address)!==void 0,o=new Array(a.length);let s=0;const l=Math.max(1,Math.min(n.concurrency,a.length));return await Promise.all(Array.from({length:l},async()=>{for(;;){const p=s++;if(p>=a.length)return;ee(n.signal,"fetchPositionsBatch"),o[p]=await nd(e,a[p],n.blockNumber,i);}})),o.flat();}async function nd(e,t,n,r){if(r)try{return(await e.multicall({contracts:t.map(i=>({address:i.address,abi:i.abi,functionName:i.functionName,args:i.args})),allowFailure:!0,blockNumber:n})).map(i=>i.status==="success"?{status:"success",result:i.result}:{status:"failure",detail:Pr(i.error),contractLevel:Kn(i.error)});}catch(a){return t.map(()=>({status:"failure",detail:Pr(a),contractLevel:!1}));}return Promise.all(t.map(a=>e.readContract({address:a.address,abi:a.abi,functionName:a.functionName,args:a.args,blockNumber:n}).then(i=>({status:"success",result:i})).catch(i=>({status:"failure",detail:Pr(i),contractLevel:Kn(i)}))));}function Pr(e){return e instanceof Error?e.message.split(`
|
|
1049
|
+
`)[0]:String(e);}var rd=-887272,ad=887272;function qi(e,t){const n=e%t;return n===0?e:e-n;}function is(e){return{tickLower:qi(rd,e),tickUpper:qi(ad,e)};}function lr(e){const{idle0:t,idle1:n,poolKey:r,poolState:a}=e;if(t<=0n&&n<=0n||a.sqrtPriceX96<=0n)return null;try{const{tickLower:i,tickUpper:o}=is(r.tickSpacing),s=pt(i),l=pt(o);return Zu(a.sqrtPriceX96,s,l,t,n,!0);}catch{return null;}}function id(e,t,n){if(n===0n)throw new Error("Division by zero");return(e*t+n-1n)/n;}function yt(e,t,n,r=!1){if(e<=0n||n.sqrtPriceX96<=0n)return null;try{const{tickLower:a,tickUpper:i}=is(t.tickSpacing),o=pt(a),s=pt(i),l=n.sqrtPriceX96;return l<=o?{amount0:Wn(o,s,e,r),amount1:0n}:l>=s?{amount0:0n,amount1:$n(o,s,e,r)}:{amount0:Wn(l,s,e,r),amount1:$n(o,l,e,r)};}catch{return null;}}function od(e,t,n,r){if(e<=0n||t===0n||r.sqrtPriceX96===0n)return null;const a=id(e,t,ie);if(a===0n)return null;const i=yt(a,n,r,!1);return i?{amount0:i.amount0,amount1:i.amount1,liquidityL:a}:null;}var $e=[{type:"constructor",inputs:[{name:"deps",type:"address",internalType:"contract IAegisDependencies"},{name:"vaultNft",type:"address",internalType:"contract IVaultRegistry"},{name:"limitOrderManager",type:"address",internalType:"contract ILimitOrderManager"},{name:"oracleManager",type:"address",internalType:"contract IOracleManager"},{name:"defaultRateOracle",type:"address",internalType:"contract IVariableInterestRate"},{name:"defaultFullUtilizationRate",type:"uint64",internalType:"uint64"}],stateMutability:"nonpayable"},{type:"receive",stateMutability:"payable"},{type:"function",name:"aeStart",inputs:[{name:"data",type:"bytes",internalType:"bytes"}],outputs:[{name:"result",type:"bytes",internalType:"bytes"}],stateMutability:"nonpayable"},{type:"function",name:"allowance",inputs:[{name:"owner",type:"address",internalType:"address"},{name:"spender",type:"address",internalType:"address"},{name:"id",type:"uint256",internalType:"uint256"}],outputs:[{name:"amount",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"approve",inputs:[{name:"spender",type:"address",internalType:"address"},{name:"id",type:"uint256",internalType:"uint256"},{name:"amount",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"nonpayable"},{type:"function",name:"attachUserNft",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"},{name:"ref",type:"tuple",internalType:"struct NftRef",components:[{name:"kind",type:"uint8",internalType:"enum NftKind"},{name:"tokenId",type:"uint248",internalType:"uint248"}]}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"authorizeHook",inputs:[{name:"hook",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"balanceOf",inputs:[{name:"owner",type:"address",internalType:"address"},{name:"id",type:"uint256",internalType:"uint256"}],outputs:[{name:"balance",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"burnVault",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"createVault",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"},{name:"owner",type:"address",internalType:"address"}],outputs:[{name:"vaultId",type:"uint256",internalType:"uint256"}],stateMutability:"nonpayable"},{type:"function",name:"detachUserNft",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"},{name:"ref",type:"tuple",internalType:"struct NftRef",components:[{name:"kind",type:"uint8",internalType:"enum NftKind"},{name:"tokenId",type:"uint248",internalType:"uint248"}]},{name:"to",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"donateIdle",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"},{name:"amount0",type:"uint128",internalType:"uint128"},{name:"amount1",type:"uint128",internalType:"uint128"}],outputs:[{name:"balancesAfter",type:"int256",internalType:"BalanceDelta"}],stateMutability:"nonpayable"},{type:"function",name:"extsload",inputs:[{name:"slot",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"extsload",inputs:[{name:"startSlot",type:"bytes32",internalType:"bytes32"},{name:"nSlots",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bytes32[]",internalType:"bytes32[]"}],stateMutability:"view"},{type:"function",name:"extsload",inputs:[{name:"slots",type:"bytes32[]",internalType:"bytes32[]"}],outputs:[{name:"",type:"bytes32[]",internalType:"bytes32[]"}],stateMutability:"view"},{type:"function",name:"exttload",inputs:[{name:"slots",type:"bytes32[]",internalType:"bytes32[]"}],outputs:[{name:"",type:"bytes32[]",internalType:"bytes32[]"}],stateMutability:"view"},{type:"function",name:"exttload",inputs:[{name:"slot",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"flushPositiveDelta",inputs:[{name:"currency",type:"address",internalType:"Currency"},{name:"to",type:"address",internalType:"address"}],outputs:[{name:"amountFlushed",type:"uint256",internalType:"uint256"}],stateMutability:"nonpayable"},{type:"function",name:"initialize",inputs:[{name:"key",type:"tuple",internalType:"struct PoolKey",components:[{name:"currency0",type:"address",internalType:"Currency"},{name:"currency1",type:"address",internalType:"Currency"},{name:"fee",type:"uint24",internalType:"uint24"},{name:"tickSpacing",type:"int24",internalType:"int24"},{name:"hooks",type:"address",internalType:"contract IHooks"}]}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"isOperator",inputs:[{name:"owner",type:"address",internalType:"address"},{name:"operator",type:"address",internalType:"address"}],outputs:[{name:"isOperator",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"lockVault",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"}],outputs:[{name:"ltvPips",type:"uint256",internalType:"uint256"}],stateMutability:"nonpayable"},{type:"function",name:"modifyDebt",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"},{name:"principalDelta",type:"int128",internalType:"int128"}],outputs:[{name:"liquidityDelta",type:"int136",internalType:"int136"},{name:"vaultIdleDelta",type:"int256",internalType:"BalanceDelta"}],stateMutability:"nonpayable"},{type:"function",name:"modifyIdle",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"},{name:"delta",type:"int256",internalType:"BalanceDelta"}],outputs:[{name:"balancesAfter",type:"int256",internalType:"BalanceDelta"}],stateMutability:"nonpayable"},{type:"function",name:"modifyLiquidity",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"},{name:"liquidityOrSharesDelta",type:"int128",internalType:"int128"},{name:"recipientOrOwner",type:"address",internalType:"address"}],outputs:[{name:"deltaShares",type:"uint256",internalType:"uint256"},{name:"modifyFullRangeDelta",type:"int256",internalType:"BalanceDelta"}],stateMutability:"nonpayable"},{type:"function",name:"onERC721Received",inputs:[{name:"",type:"address",internalType:"address"},{name:"from",type:"address",internalType:"address"},{name:"tokenId",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}],outputs:[{name:"",type:"bytes4",internalType:"bytes4"}],stateMutability:"nonpayable"},{type:"function",name:"peelOrMicroLiquidate",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"},{name:"maybeNft",type:"tuple",internalType:"struct NftRef",components:[{name:"kind",type:"uint8",internalType:"enum NftKind"},{name:"tokenId",type:"uint248",internalType:"uint248"}]}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setDefaultRateOracle",inputs:[{name:"oracle",type:"address",internalType:"address"},{name:"fullUtilRate",type:"uint64",internalType:"uint64"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setMarketLtvThresholds",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"},{name:"newMaxLtvPips",type:"uint24",internalType:"uint24"},{name:"newHardLtvPips",type:"uint24",internalType:"uint24"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setMarketProtocolFee",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"},{name:"newProtocolFeePips",type:"uint24",internalType:"uint24"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setOperator",inputs:[{name:"operator",type:"address",internalType:"address"},{name:"approved",type:"bool",internalType:"bool"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"nonpayable"},{type:"function",name:"setPoolRateOracle",inputs:[{name:"poolId",type:"bytes32",internalType:"PoolId"},{name:"oracle",type:"address",internalType:"address"},{name:"fullUtilRate",type:"uint64",internalType:"uint64"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"supportsInterface",inputs:[{name:"interfaceId",type:"bytes4",internalType:"bytes4"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"transfer",inputs:[{name:"receiver",type:"address",internalType:"address"},{name:"id",type:"uint256",internalType:"uint256"},{name:"amount",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"nonpayable"},{type:"function",name:"transferFrom",inputs:[{name:"sender",type:"address",internalType:"address"},{name:"receiver",type:"address",internalType:"address"},{name:"id",type:"uint256",internalType:"uint256"},{name:"amount",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"nonpayable"},{type:"function",name:"transferOwnership",inputs:[{name:"newOwner",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"unlockVault",inputs:[{name:"vaultId",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"event",name:"Approval",inputs:[{name:"owner",type:"address",indexed:!0,internalType:"address"},{name:"spender",type:"address",indexed:!0,internalType:"address"},{name:"id",type:"uint256",indexed:!0,internalType:"uint256"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"DebtModified",inputs:[{name:"vaultId",type:"uint256",indexed:!0,internalType:"uint256"},{name:"principalDeltaRequested",type:"int128",indexed:!1,internalType:"int128"},{name:"principalDeltaActual",type:"int136",indexed:!1,internalType:"int136"},{name:"borrowIndexWad",type:"uint256",indexed:!1,internalType:"uint256"},{name:"deltaIdle",type:"int256",indexed:!1,internalType:"BalanceDelta"}],anonymous:!1},{type:"event",name:"DefaultRateOracleSet",inputs:[{name:"oracle",type:"address",indexed:!0,internalType:"address"},{name:"fullUtilRate",type:"uint64",indexed:!1,internalType:"uint64"}],anonymous:!1},{type:"event",name:"HookAuthorized",inputs:[{name:"hook",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"IdleDonated",inputs:[{name:"vaultId",type:"uint256",indexed:!0,internalType:"uint256"},{name:"amounts",type:"int256",indexed:!1,internalType:"BalanceDelta"}],anonymous:!1},{type:"event",name:"IdleModified",inputs:[{name:"vaultId",type:"uint256",indexed:!0,internalType:"uint256"},{name:"delta",type:"int256",indexed:!1,internalType:"BalanceDelta"}],anonymous:!1},{type:"event",name:"InterestAccrued",inputs:[{name:"poolId",type:"bytes32",indexed:!0,internalType:"PoolId"},{name:"ratePerSecondWad",type:"uint256",indexed:!1,internalType:"uint256"},{name:"interestAccruedWad",type:"uint256",indexed:!1,internalType:"uint256"},{name:"borrowIndexWadAfter",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"LiquidityModified",inputs:[{name:"poolId",type:"bytes32",indexed:!0,internalType:"PoolId"},{name:"account",type:"address",indexed:!0,internalType:"address"},{name:"liquidityOrSharesDelta",type:"int128",indexed:!1,internalType:"int128"},{name:"deltaShares",type:"uint256",indexed:!1,internalType:"uint256"},{name:"liquidityDelta",type:"int128",indexed:!1,internalType:"int128"},{name:"deltaAmounts",type:"int256",indexed:!1,internalType:"BalanceDelta"}],anonymous:!1},{type:"event",name:"MarketInitialized",inputs:[{name:"poolId",type:"bytes32",indexed:!0,internalType:"PoolId"},{name:"currency0",type:"address",indexed:!0,internalType:"Currency"},{name:"currency1",type:"address",indexed:!0,internalType:"Currency"},{name:"fee",type:"uint24",indexed:!1,internalType:"uint24"},{name:"tickSpacing",type:"int24",indexed:!1,internalType:"int24"},{name:"hooks",type:"address",indexed:!1,internalType:"contract IHooks"}],anonymous:!1},{type:"event",name:"MarketLtvThresholdsSet",inputs:[{name:"poolId",type:"bytes32",indexed:!0,internalType:"PoolId"},{name:"maxLtvPips",type:"uint24",indexed:!1,internalType:"uint24"},{name:"hardLtvPips",type:"uint24",indexed:!1,internalType:"uint24"}],anonymous:!1},{type:"event",name:"MarketProtocolFeeSet",inputs:[{name:"poolId",type:"bytes32",indexed:!0,internalType:"PoolId"},{name:"protocolFeePips",type:"uint24",indexed:!1,internalType:"uint24"}],anonymous:!1},{type:"event",name:"NftAttached",inputs:[{name:"vaultId",type:"uint256",indexed:!0,internalType:"uint256"},{name:"tokenId",type:"uint256",indexed:!0,internalType:"uint256"},{name:"kind",type:"uint8",indexed:!1,internalType:"enum NftKind"},{name:"from",type:"address",indexed:!1,internalType:"address"},{name:"liquidity",type:"uint128",indexed:!1,internalType:"uint128"}],anonymous:!1},{type:"event",name:"NftDetached",inputs:[{name:"vaultId",type:"uint256",indexed:!0,internalType:"uint256"},{name:"tokenId",type:"uint256",indexed:!0,internalType:"uint256"},{name:"kind",type:"uint8",indexed:!1,internalType:"enum NftKind"},{name:"to",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"NftPeeled",inputs:[{name:"vaultId",type:"uint256",indexed:!0,internalType:"uint256"},{name:"caller",type:"address",indexed:!0,internalType:"address"},{name:"nft",type:"tuple",indexed:!1,internalType:"struct NftRef",components:[{name:"kind",type:"uint8",internalType:"enum NftKind"},{name:"tokenId",type:"uint248",internalType:"uint248"}]},{name:"xRealized",type:"uint256",indexed:!1,internalType:"uint256"},{name:"yRealized",type:"uint256",indexed:!1,internalType:"uint256"},{name:"idleDelta",type:"int256",indexed:!1,internalType:"BalanceDelta"},{name:"initialLtvPips",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"OperatorSet",inputs:[{name:"owner",type:"address",indexed:!0,internalType:"address"},{name:"operator",type:"address",indexed:!0,internalType:"address"},{name:"approved",type:"bool",indexed:!1,internalType:"bool"}],anonymous:!1},{type:"event",name:"OwnershipTransferred",inputs:[{name:"user",type:"address",indexed:!0,internalType:"address"},{name:"newOwner",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"PoolRateOracleSet",inputs:[{name:"poolId",type:"bytes32",indexed:!0,internalType:"PoolId"},{name:"oracle",type:"address",indexed:!0,internalType:"address"},{name:"fullUtilRate",type:"uint64",indexed:!1,internalType:"uint64"}],anonymous:!1},{type:"event",name:"ProtocolFeeMinted",inputs:[{name:"poolId",type:"bytes32",indexed:!0,internalType:"PoolId"},{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"sharesMinted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"protocolFeeAmount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"TradingFeesReinvested",inputs:[{name:"poolId",type:"bytes32",indexed:!0,internalType:"PoolId"},{name:"feesCollected",type:"int256",indexed:!1,internalType:"BalanceDelta"},{name:"liquidityMinted",type:"uint128",indexed:!1,internalType:"uint128"},{name:"equityLWadAfter",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"Transfer",inputs:[{name:"caller",type:"address",indexed:!1,internalType:"address"},{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"id",type:"uint256",indexed:!0,internalType:"uint256"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"VaultBurned",inputs:[{name:"vaultId",type:"uint256",indexed:!0,internalType:"uint256"},{name:"owner",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"VaultCreated",inputs:[{name:"vaultId",type:"uint256",indexed:!0,internalType:"uint256"},{name:"poolId",type:"bytes32",indexed:!0,internalType:"PoolId"},{name:"owner",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"VaultLocked",inputs:[{name:"vaultId",type:"uint256",indexed:!0,internalType:"uint256"},{name:"ltvPips",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"VaultMicroLiquidated",inputs:[{name:"vaultId",type:"uint256",indexed:!0,internalType:"uint256"},{name:"caller",type:"address",indexed:!0,internalType:"address"},{name:"zeroForOne",type:"bool",indexed:!1,internalType:"bool"},{name:"swapDelta",type:"int256",indexed:!1,internalType:"BalanceDelta"},{name:"debtRepaidRl",type:"uint136",indexed:!1,internalType:"uint136"},{name:"idleDelta",type:"int256",indexed:!1,internalType:"BalanceDelta"},{name:"keeperFee",type:"int256",indexed:!1,internalType:"BalanceDelta"},{name:"initialLtvPips",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"error",name:"AegisEngineError",inputs:[{name:"code",type:"uint8",internalType:"uint8"}]},{type:"error",name:"ContractLocked",inputs:[]},{type:"error",name:"DelegateCallNotAllowed",inputs:[]},{type:"error",name:"HookNotAuthorized",inputs:[]},{type:"error",name:"OwnableUnauthorizedAccount",inputs:[]},{type:"error",name:"SafeCastOverflowedIntDowncast",inputs:[{name:"bits",type:"uint8",internalType:"uint8"},{name:"value",type:"int256",internalType:"int256"}]},{type:"error",name:"SafeCastOverflowedIntToUint",inputs:[{name:"value",type:"int256",internalType:"int256"}]},{type:"error",name:"SafeCastOverflowedUintDowncast",inputs:[{name:"bits",type:"uint8",internalType:"uint8"},{name:"value",type:"uint256",internalType:"uint256"}]}],os=[{inputs:[{internalType:"contract IPoolManager",name:"_poolManager",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{internalType:"PoolId",name:"poolId",type:"bytes32"}],name:"NotEnoughLiquidity",type:"error"},{inputs:[],name:"NotPoolManager",type:"error"},{inputs:[],name:"NotSelf",type:"error"},{inputs:[{internalType:"uint256",name:"amount",type:"uint256"}],name:"QuoteSwap",type:"error"},{inputs:[],name:"UnexpectedCallSuccess",type:"error"},{inputs:[{internalType:"bytes",name:"revertData",type:"bytes"}],name:"UnexpectedRevertBytes",type:"error"},{inputs:[{components:[{internalType:"Currency",name:"exactCurrency",type:"address"},{components:[{internalType:"Currency",name:"intermediateCurrency",type:"address"},{internalType:"uint24",name:"fee",type:"uint24"},{internalType:"int24",name:"tickSpacing",type:"int24"},{internalType:"contract IHooks",name:"hooks",type:"address"},{internalType:"bytes",name:"hookData",type:"bytes"}],internalType:"struct PathKey[]",name:"path",type:"tuple[]"},{internalType:"uint128",name:"exactAmount",type:"uint128"}],internalType:"struct IV4Quoter.QuoteExactParams",name:"params",type:"tuple"}],name:"_quoteExactInput",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{components:[{internalType:"Currency",name:"currency0",type:"address"},{internalType:"Currency",name:"currency1",type:"address"},{internalType:"uint24",name:"fee",type:"uint24"},{internalType:"int24",name:"tickSpacing",type:"int24"},{internalType:"contract IHooks",name:"hooks",type:"address"}],internalType:"struct PoolKey",name:"poolKey",type:"tuple"},{internalType:"bool",name:"zeroForOne",type:"bool"},{internalType:"uint128",name:"exactAmount",type:"uint128"},{internalType:"bytes",name:"hookData",type:"bytes"}],internalType:"struct IV4Quoter.QuoteExactSingleParams",name:"params",type:"tuple"}],name:"_quoteExactInputSingle",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"Currency",name:"exactCurrency",type:"address"},{components:[{internalType:"Currency",name:"intermediateCurrency",type:"address"},{internalType:"uint24",name:"fee",type:"uint24"},{internalType:"int24",name:"tickSpacing",type:"int24"},{internalType:"contract IHooks",name:"hooks",type:"address"},{internalType:"bytes",name:"hookData",type:"bytes"}],internalType:"struct PathKey[]",name:"path",type:"tuple[]"},{internalType:"uint128",name:"exactAmount",type:"uint128"}],internalType:"struct IV4Quoter.QuoteExactParams",name:"params",type:"tuple"}],name:"_quoteExactOutput",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{components:[{internalType:"Currency",name:"currency0",type:"address"},{internalType:"Currency",name:"currency1",type:"address"},{internalType:"uint24",name:"fee",type:"uint24"},{internalType:"int24",name:"tickSpacing",type:"int24"},{internalType:"contract IHooks",name:"hooks",type:"address"}],internalType:"struct PoolKey",name:"poolKey",type:"tuple"},{internalType:"bool",name:"zeroForOne",type:"bool"},{internalType:"uint128",name:"exactAmount",type:"uint128"},{internalType:"bytes",name:"hookData",type:"bytes"}],internalType:"struct IV4Quoter.QuoteExactSingleParams",name:"params",type:"tuple"}],name:"_quoteExactOutputSingle",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"poolManager",outputs:[{internalType:"contract IPoolManager",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{components:[{internalType:"Currency",name:"exactCurrency",type:"address"},{components:[{internalType:"Currency",name:"intermediateCurrency",type:"address"},{internalType:"uint24",name:"fee",type:"uint24"},{internalType:"int24",name:"tickSpacing",type:"int24"},{internalType:"contract IHooks",name:"hooks",type:"address"},{internalType:"bytes",name:"hookData",type:"bytes"}],internalType:"struct PathKey[]",name:"path",type:"tuple[]"},{internalType:"uint128",name:"exactAmount",type:"uint128"}],internalType:"struct IV4Quoter.QuoteExactParams",name:"params",type:"tuple"}],name:"quoteExactInput",outputs:[{internalType:"uint256",name:"amountOut",type:"uint256"},{internalType:"uint256",name:"gasEstimate",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{components:[{internalType:"Currency",name:"currency0",type:"address"},{internalType:"Currency",name:"currency1",type:"address"},{internalType:"uint24",name:"fee",type:"uint24"},{internalType:"int24",name:"tickSpacing",type:"int24"},{internalType:"contract IHooks",name:"hooks",type:"address"}],internalType:"struct PoolKey",name:"poolKey",type:"tuple"},{internalType:"bool",name:"zeroForOne",type:"bool"},{internalType:"uint128",name:"exactAmount",type:"uint128"},{internalType:"bytes",name:"hookData",type:"bytes"}],internalType:"struct IV4Quoter.QuoteExactSingleParams",name:"params",type:"tuple"}],name:"quoteExactInputSingle",outputs:[{internalType:"uint256",name:"amountOut",type:"uint256"},{internalType:"uint256",name:"gasEstimate",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"Currency",name:"exactCurrency",type:"address"},{components:[{internalType:"Currency",name:"intermediateCurrency",type:"address"},{internalType:"uint24",name:"fee",type:"uint24"},{internalType:"int24",name:"tickSpacing",type:"int24"},{internalType:"contract IHooks",name:"hooks",type:"address"},{internalType:"bytes",name:"hookData",type:"bytes"}],internalType:"struct PathKey[]",name:"path",type:"tuple[]"},{internalType:"uint128",name:"exactAmount",type:"uint128"}],internalType:"struct IV4Quoter.QuoteExactParams",name:"params",type:"tuple"}],name:"quoteExactOutput",outputs:[{internalType:"uint256",name:"amountIn",type:"uint256"},{internalType:"uint256",name:"gasEstimate",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{components:[{internalType:"Currency",name:"currency0",type:"address"},{internalType:"Currency",name:"currency1",type:"address"},{internalType:"uint24",name:"fee",type:"uint24"},{internalType:"int24",name:"tickSpacing",type:"int24"},{internalType:"contract IHooks",name:"hooks",type:"address"}],internalType:"struct PoolKey",name:"poolKey",type:"tuple"},{internalType:"bool",name:"zeroForOne",type:"bool"},{internalType:"uint128",name:"exactAmount",type:"uint128"},{internalType:"bytes",name:"hookData",type:"bytes"}],internalType:"struct IV4Quoter.QuoteExactSingleParams",name:"params",type:"tuple"}],name:"quoteExactOutputSingle",outputs:[{internalType:"uint256",name:"amountIn",type:"uint256"},{internalType:"uint256",name:"gasEstimate",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes",name:"data",type:"bytes"}],name:"unlockCallback",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"nonpayable",type:"function"}];function sd(e,t,n){var o;let r,a;if(typeof e=="string")r=e,a=t;else{if(typeof t!="string")throw new Error("createSubgraphClient: version is required when passing a chainId");r=_o(e,t,n!=null&&n.deployment?{deployment:n.deployment}:void 0),a=n;}const i=(o=a==null?void 0:a.graphApiKey)==null?void 0:o.trim();return i&&r.startsWith("https://gateway.thegraph.com/api/")&&(r=r.replace("https://gateway.thegraph.com/api/",`https://gateway.thegraph.com/api/${encodeURIComponent(i)}/`)),new Vu(r);}var Oe=class extends String{constructor(t,n){super(t);oe(this,"__apiType");oe(this,"value");oe(this,"__meta__");this.value=t,this.__meta__=n;}toString(){return this.value;}},ld=new Oe(`
|
|
1050
|
+
query VaultDebtActions($vaultId: String!, $first: Int, $skip: Int) {
|
|
1051
|
+
debtModifiedActions(
|
|
1052
|
+
where: {vault: $vaultId}
|
|
1053
|
+
first: $first
|
|
1054
|
+
skip: $skip
|
|
1055
|
+
orderBy: timestamp
|
|
1056
|
+
orderDirection: desc
|
|
1057
|
+
) {
|
|
1058
|
+
id
|
|
1059
|
+
timestamp
|
|
1060
|
+
logIndex
|
|
1061
|
+
principalDeltaActual
|
|
1062
|
+
principalDeltaRequested
|
|
1063
|
+
borrowIndexWad
|
|
1064
|
+
deltaIdle0
|
|
1065
|
+
deltaIdle1
|
|
1066
|
+
transaction {
|
|
1067
|
+
id
|
|
1068
|
+
blockNumber
|
|
1069
|
+
gasPrice
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
`),ud=new Oe(`
|
|
1074
|
+
query VaultIdleActions($vaultId: String!, $first: Int, $skip: Int) {
|
|
1075
|
+
idleModifiedActions(
|
|
1076
|
+
where: {vault: $vaultId}
|
|
1077
|
+
first: $first
|
|
1078
|
+
skip: $skip
|
|
1079
|
+
orderBy: timestamp
|
|
1080
|
+
orderDirection: desc
|
|
1081
|
+
) {
|
|
1082
|
+
id
|
|
1083
|
+
timestamp
|
|
1084
|
+
logIndex
|
|
1085
|
+
deltaAmount0
|
|
1086
|
+
deltaAmount1
|
|
1087
|
+
transaction {
|
|
1088
|
+
id
|
|
1089
|
+
blockNumber
|
|
1090
|
+
gasPrice
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
`),cd=new Oe(`
|
|
1095
|
+
query RecentLiquidations($first: Int, $skip: Int) {
|
|
1096
|
+
vaultMicroLiquidatedActions(
|
|
1097
|
+
first: $first
|
|
1098
|
+
skip: $skip
|
|
1099
|
+
orderBy: timestamp
|
|
1100
|
+
orderDirection: desc
|
|
1101
|
+
) {
|
|
1102
|
+
id
|
|
1103
|
+
timestamp
|
|
1104
|
+
logIndex
|
|
1105
|
+
caller
|
|
1106
|
+
debtRepaidRl
|
|
1107
|
+
idleDelta0
|
|
1108
|
+
idleDelta1
|
|
1109
|
+
swapDelta0
|
|
1110
|
+
swapDelta1
|
|
1111
|
+
keeperFee0
|
|
1112
|
+
keeperFee1
|
|
1113
|
+
initialLtvPips
|
|
1114
|
+
zeroForOne
|
|
1115
|
+
vault {
|
|
1116
|
+
id
|
|
1117
|
+
owner
|
|
1118
|
+
pool {
|
|
1119
|
+
id
|
|
1120
|
+
currency0
|
|
1121
|
+
currency1
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
transaction {
|
|
1125
|
+
id
|
|
1126
|
+
blockNumber
|
|
1127
|
+
gasPrice
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
`),dd=new Oe(`
|
|
1132
|
+
query MarketLiquidityActions($poolId: String!, $first: Int, $skip: Int) {
|
|
1133
|
+
liquidityModifiedActions(
|
|
1134
|
+
where: {pool: $poolId}
|
|
1135
|
+
first: $first
|
|
1136
|
+
skip: $skip
|
|
1137
|
+
orderBy: timestamp
|
|
1138
|
+
orderDirection: desc
|
|
1139
|
+
) {
|
|
1140
|
+
id
|
|
1141
|
+
timestamp
|
|
1142
|
+
logIndex
|
|
1143
|
+
account
|
|
1144
|
+
liquidityDelta
|
|
1145
|
+
liquidityOrSharesDelta
|
|
1146
|
+
deltaShares
|
|
1147
|
+
deltaAmount0
|
|
1148
|
+
deltaAmount1
|
|
1149
|
+
transaction {
|
|
1150
|
+
id
|
|
1151
|
+
blockNumber
|
|
1152
|
+
gasPrice
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
`),pd=new Oe(`
|
|
1157
|
+
query MarketInterestActions($poolId: String!, $first: Int, $skip: Int) {
|
|
1158
|
+
interestAccruedActions(
|
|
1159
|
+
where: {pool: $poolId}
|
|
1160
|
+
first: $first
|
|
1161
|
+
skip: $skip
|
|
1162
|
+
orderBy: timestamp
|
|
1163
|
+
orderDirection: desc
|
|
1164
|
+
) {
|
|
1165
|
+
id
|
|
1166
|
+
timestamp
|
|
1167
|
+
logIndex
|
|
1168
|
+
ratePerSecondWad
|
|
1169
|
+
interestAccruedWad
|
|
1170
|
+
borrowIndexWadAfter
|
|
1171
|
+
transaction {
|
|
1172
|
+
id
|
|
1173
|
+
blockNumber
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
`),fd=new Oe(`
|
|
1178
|
+
query VaultNftActions($vaultId: String!, $first: Int, $skip: Int) {
|
|
1179
|
+
nftAttachedActions(
|
|
1180
|
+
where: {vault: $vaultId}
|
|
1181
|
+
first: $first
|
|
1182
|
+
skip: $skip
|
|
1183
|
+
orderBy: timestamp
|
|
1184
|
+
orderDirection: desc
|
|
1185
|
+
) {
|
|
1186
|
+
id
|
|
1187
|
+
timestamp
|
|
1188
|
+
logIndex
|
|
1189
|
+
kind
|
|
1190
|
+
tokenId
|
|
1191
|
+
liquidity
|
|
1192
|
+
from
|
|
1193
|
+
transaction {
|
|
1194
|
+
id
|
|
1195
|
+
blockNumber
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
`),md=new Oe(`
|
|
1200
|
+
query MarketDayDataById($id: ID!) {
|
|
1201
|
+
marketDayData(id: $id) {
|
|
1202
|
+
id
|
|
1203
|
+
date
|
|
1204
|
+
dayStartTimestamp
|
|
1205
|
+
depositCount
|
|
1206
|
+
withdrawCount
|
|
1207
|
+
debtIncreaseCount
|
|
1208
|
+
debtDecreaseCount
|
|
1209
|
+
microLiquidationCount
|
|
1210
|
+
nftAttachCount
|
|
1211
|
+
nftDetachCount
|
|
1212
|
+
nftPeelCount
|
|
1213
|
+
idleModifiedCount
|
|
1214
|
+
tradingFeeReinvestCount
|
|
1215
|
+
actionCount
|
|
1216
|
+
pool {
|
|
1217
|
+
id
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
`),yd=new Oe(`
|
|
1222
|
+
query RecentMarketDayData($poolId: String!, $first: Int, $skip: Int) {
|
|
1223
|
+
marketDayDatas(
|
|
1224
|
+
where: {pool: $poolId}
|
|
1225
|
+
first: $first
|
|
1226
|
+
skip: $skip
|
|
1227
|
+
orderBy: date
|
|
1228
|
+
orderDirection: desc
|
|
1229
|
+
) {
|
|
1230
|
+
id
|
|
1231
|
+
date
|
|
1232
|
+
dayStartTimestamp
|
|
1233
|
+
depositCount
|
|
1234
|
+
withdrawCount
|
|
1235
|
+
debtIncreaseCount
|
|
1236
|
+
debtDecreaseCount
|
|
1237
|
+
microLiquidationCount
|
|
1238
|
+
nftAttachCount
|
|
1239
|
+
nftDetachCount
|
|
1240
|
+
nftPeelCount
|
|
1241
|
+
idleModifiedCount
|
|
1242
|
+
tradingFeeReinvestCount
|
|
1243
|
+
actionCount
|
|
1244
|
+
pool {
|
|
1245
|
+
id
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
`),hd=new Oe(`
|
|
1250
|
+
query MarketShareBalancesByAccount($account: Bytes!, $first: Int, $skip: Int) {
|
|
1251
|
+
marketShareBalances(
|
|
1252
|
+
where: {account: $account, balance_gt: "0"}
|
|
1253
|
+
first: $first
|
|
1254
|
+
skip: $skip
|
|
1255
|
+
orderBy: balance
|
|
1256
|
+
orderDirection: desc
|
|
1257
|
+
) {
|
|
1258
|
+
id
|
|
1259
|
+
account
|
|
1260
|
+
balance
|
|
1261
|
+
pool {
|
|
1262
|
+
id
|
|
1263
|
+
currency0
|
|
1264
|
+
currency1
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
`),bd=new Oe(`
|
|
1269
|
+
query MarketShareBalancesByPool($poolId: String!, $minBalance: BigInt!, $first: Int, $skip: Int, $orderBy: MarketShareBalance_orderBy!, $orderDirection: OrderDirection!) {
|
|
1270
|
+
marketShareBalances(
|
|
1271
|
+
where: {pool: $poolId, balance_gte: $minBalance}
|
|
1272
|
+
first: $first
|
|
1273
|
+
skip: $skip
|
|
1274
|
+
orderBy: $orderBy
|
|
1275
|
+
orderDirection: $orderDirection
|
|
1276
|
+
) {
|
|
1277
|
+
id
|
|
1278
|
+
account
|
|
1279
|
+
balance
|
|
1280
|
+
pool {
|
|
1281
|
+
id
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
`),gd=new Oe(`
|
|
1286
|
+
query MarketShareTransfersByPool($poolId: String!, $first: Int, $skip: Int, $orderBy: MarketShareTransfer_orderBy!, $orderDirection: OrderDirection!) {
|
|
1287
|
+
marketShareTransfers(
|
|
1288
|
+
where: {pool: $poolId}
|
|
1289
|
+
first: $first
|
|
1290
|
+
skip: $skip
|
|
1291
|
+
orderBy: $orderBy
|
|
1292
|
+
orderDirection: $orderDirection
|
|
1293
|
+
) {
|
|
1294
|
+
id
|
|
1295
|
+
timestamp
|
|
1296
|
+
logIndex
|
|
1297
|
+
caller
|
|
1298
|
+
from
|
|
1299
|
+
to
|
|
1300
|
+
amount
|
|
1301
|
+
isMint
|
|
1302
|
+
isBurn
|
|
1303
|
+
pool {
|
|
1304
|
+
id
|
|
1305
|
+
}
|
|
1306
|
+
transaction {
|
|
1307
|
+
id
|
|
1308
|
+
blockNumber
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
`),vd=new Oe(`
|
|
1313
|
+
query AllMarkets($first: Int, $skip: Int) {
|
|
1314
|
+
markets(
|
|
1315
|
+
first: $first
|
|
1316
|
+
skip: $skip
|
|
1317
|
+
orderBy: createdAtTimestamp
|
|
1318
|
+
orderDirection: desc
|
|
1319
|
+
) {
|
|
1320
|
+
id
|
|
1321
|
+
currency0
|
|
1322
|
+
currency1
|
|
1323
|
+
fee
|
|
1324
|
+
tickSpacing
|
|
1325
|
+
hooks
|
|
1326
|
+
equityLWad
|
|
1327
|
+
borrowIndexWad
|
|
1328
|
+
shareTotalSupply
|
|
1329
|
+
totalRlBorrowed
|
|
1330
|
+
maxLtvPips
|
|
1331
|
+
hardLtvPips
|
|
1332
|
+
rateOracle
|
|
1333
|
+
fullUtilRate
|
|
1334
|
+
residues0
|
|
1335
|
+
residues1
|
|
1336
|
+
vaultCount
|
|
1337
|
+
activeVaultCount
|
|
1338
|
+
activeDebtVaultCount
|
|
1339
|
+
activeLendAccountCount
|
|
1340
|
+
createdAtTimestamp
|
|
1341
|
+
createdAtBlockNumber
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
`),wd=new Oe(`
|
|
1345
|
+
query MarketById($id: ID!) {
|
|
1346
|
+
market(id: $id) {
|
|
1347
|
+
id
|
|
1348
|
+
currency0
|
|
1349
|
+
currency1
|
|
1350
|
+
fee
|
|
1351
|
+
tickSpacing
|
|
1352
|
+
hooks
|
|
1353
|
+
equityLWad
|
|
1354
|
+
borrowIndexWad
|
|
1355
|
+
shareTotalSupply
|
|
1356
|
+
totalRlBorrowed
|
|
1357
|
+
maxLtvPips
|
|
1358
|
+
hardLtvPips
|
|
1359
|
+
rateOracle
|
|
1360
|
+
fullUtilRate
|
|
1361
|
+
residues0
|
|
1362
|
+
residues1
|
|
1363
|
+
vaultCount
|
|
1364
|
+
activeVaultCount
|
|
1365
|
+
activeDebtVaultCount
|
|
1366
|
+
activeLendAccountCount
|
|
1367
|
+
createdAtTimestamp
|
|
1368
|
+
createdAtBlockNumber
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
`),Ad=new Oe(`
|
|
1372
|
+
query VaultsByOwner($owner: Bytes!, $first: Int, $skip: Int) {
|
|
1373
|
+
vaults(
|
|
1374
|
+
where: {owner: $owner, burnedAtTimestamp: null}
|
|
1375
|
+
first: $first
|
|
1376
|
+
skip: $skip
|
|
1377
|
+
orderBy: createdAtTimestamp
|
|
1378
|
+
orderDirection: desc
|
|
1379
|
+
) {
|
|
1380
|
+
id
|
|
1381
|
+
owner
|
|
1382
|
+
idle0
|
|
1383
|
+
idle1
|
|
1384
|
+
principalRl
|
|
1385
|
+
borrowIndexWadAtLastDebt
|
|
1386
|
+
nftCount
|
|
1387
|
+
lastLockedAt
|
|
1388
|
+
lastLtvPips
|
|
1389
|
+
createdAtTimestamp
|
|
1390
|
+
createdAtBlockNumber
|
|
1391
|
+
burnedAtTimestamp
|
|
1392
|
+
burnedAtBlockNumber
|
|
1393
|
+
pool {
|
|
1394
|
+
id
|
|
1395
|
+
currency0
|
|
1396
|
+
currency1
|
|
1397
|
+
fee
|
|
1398
|
+
tickSpacing
|
|
1399
|
+
hooks
|
|
1400
|
+
borrowIndexWad
|
|
1401
|
+
}
|
|
1402
|
+
nfts {
|
|
1403
|
+
id
|
|
1404
|
+
kind
|
|
1405
|
+
tokenId
|
|
1406
|
+
liquidityAtLastAttach
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
`),Td=new Oe(`
|
|
1411
|
+
query VaultById($id: ID!) {
|
|
1412
|
+
vault(id: $id) {
|
|
1413
|
+
id
|
|
1414
|
+
owner
|
|
1415
|
+
idle0
|
|
1416
|
+
idle1
|
|
1417
|
+
principalRl
|
|
1418
|
+
borrowIndexWadAtLastDebt
|
|
1419
|
+
nftCount
|
|
1420
|
+
lastLockedAt
|
|
1421
|
+
lastLtvPips
|
|
1422
|
+
createdAtTimestamp
|
|
1423
|
+
createdAtBlockNumber
|
|
1424
|
+
burnedAtTimestamp
|
|
1425
|
+
burnedAtBlockNumber
|
|
1426
|
+
pool {
|
|
1427
|
+
id
|
|
1428
|
+
currency0
|
|
1429
|
+
currency1
|
|
1430
|
+
fee
|
|
1431
|
+
tickSpacing
|
|
1432
|
+
hooks
|
|
1433
|
+
borrowIndexWad
|
|
1434
|
+
equityLWad
|
|
1435
|
+
maxLtvPips
|
|
1436
|
+
hardLtvPips
|
|
1437
|
+
}
|
|
1438
|
+
nfts {
|
|
1439
|
+
id
|
|
1440
|
+
kind
|
|
1441
|
+
tokenId
|
|
1442
|
+
liquidityAtLastAttach
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
`),Ed=new Oe(`
|
|
1447
|
+
query VaultsAtRisk($minLtvPips: BigInt!, $first: Int, $skip: Int) {
|
|
1448
|
+
vaults(
|
|
1449
|
+
where: {lastLtvPips_gte: $minLtvPips, principalRl_gt: "0", burnedAtTimestamp: null}
|
|
1450
|
+
first: $first
|
|
1451
|
+
skip: $skip
|
|
1452
|
+
orderBy: lastLtvPips
|
|
1453
|
+
orderDirection: desc
|
|
1454
|
+
) {
|
|
1455
|
+
id
|
|
1456
|
+
owner
|
|
1457
|
+
idle0
|
|
1458
|
+
idle1
|
|
1459
|
+
principalRl
|
|
1460
|
+
borrowIndexWadAtLastDebt
|
|
1461
|
+
nftCount
|
|
1462
|
+
lastLockedAt
|
|
1463
|
+
lastLtvPips
|
|
1464
|
+
burnedAtTimestamp
|
|
1465
|
+
burnedAtBlockNumber
|
|
1466
|
+
pool {
|
|
1467
|
+
id
|
|
1468
|
+
currency0
|
|
1469
|
+
currency1
|
|
1470
|
+
borrowIndexWad
|
|
1471
|
+
maxLtvPips
|
|
1472
|
+
hardLtvPips
|
|
1473
|
+
}
|
|
1474
|
+
nfts {
|
|
1475
|
+
id
|
|
1476
|
+
kind
|
|
1477
|
+
tokenId
|
|
1478
|
+
liquidityAtLastAttach
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
`),Id=new Oe(`
|
|
1483
|
+
query VaultsByPool($poolId: String!, $first: Int, $skip: Int) {
|
|
1484
|
+
vaults(
|
|
1485
|
+
where: {pool: $poolId, burnedAtTimestamp: null}
|
|
1486
|
+
first: $first
|
|
1487
|
+
skip: $skip
|
|
1488
|
+
orderBy: createdAtTimestamp
|
|
1489
|
+
orderDirection: desc
|
|
1490
|
+
) {
|
|
1491
|
+
id
|
|
1492
|
+
owner
|
|
1493
|
+
idle0
|
|
1494
|
+
idle1
|
|
1495
|
+
principalRl
|
|
1496
|
+
borrowIndexWadAtLastDebt
|
|
1497
|
+
nftCount
|
|
1498
|
+
lastLockedAt
|
|
1499
|
+
lastLtvPips
|
|
1500
|
+
createdAtTimestamp
|
|
1501
|
+
burnedAtTimestamp
|
|
1502
|
+
burnedAtBlockNumber
|
|
1503
|
+
nfts {
|
|
1504
|
+
id
|
|
1505
|
+
kind
|
|
1506
|
+
tokenId
|
|
1507
|
+
liquidityAtLastAttach
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
`),xd={"\n query VaultDebtActions($vaultId: String!, $first: Int, $skip: Int) {\n debtModifiedActions(\n where: { vault: $vaultId }\n first: $first\n skip: $skip\n orderBy: timestamp\n orderDirection: desc\n ) {\n id\n timestamp\n logIndex\n principalDeltaActual\n principalDeltaRequested\n borrowIndexWad\n deltaIdle0\n deltaIdle1\n transaction {\n id\n blockNumber\n gasPrice\n }\n }\n }\n":ld,"\n query VaultIdleActions($vaultId: String!, $first: Int, $skip: Int) {\n idleModifiedActions(\n where: { vault: $vaultId }\n first: $first\n skip: $skip\n orderBy: timestamp\n orderDirection: desc\n ) {\n id\n timestamp\n logIndex\n deltaAmount0\n deltaAmount1\n transaction {\n id\n blockNumber\n gasPrice\n }\n }\n }\n":ud,"\n query RecentLiquidations($first: Int, $skip: Int) {\n vaultMicroLiquidatedActions(\n first: $first\n skip: $skip\n orderBy: timestamp\n orderDirection: desc\n ) {\n id\n timestamp\n logIndex\n caller\n debtRepaidRl\n idleDelta0\n idleDelta1\n swapDelta0\n swapDelta1\n keeperFee0\n keeperFee1\n initialLtvPips\n zeroForOne\n vault {\n id\n owner\n pool {\n id\n currency0\n currency1\n }\n }\n transaction {\n id\n blockNumber\n gasPrice\n }\n }\n }\n":cd,"\n query MarketLiquidityActions($poolId: String!, $first: Int, $skip: Int) {\n liquidityModifiedActions(\n where: { pool: $poolId }\n first: $first\n skip: $skip\n orderBy: timestamp\n orderDirection: desc\n ) {\n id\n timestamp\n logIndex\n account\n liquidityDelta\n liquidityOrSharesDelta\n deltaShares\n deltaAmount0\n deltaAmount1\n transaction {\n id\n blockNumber\n gasPrice\n }\n }\n }\n":dd,"\n query MarketInterestActions($poolId: String!, $first: Int, $skip: Int) {\n interestAccruedActions(\n where: { pool: $poolId }\n first: $first\n skip: $skip\n orderBy: timestamp\n orderDirection: desc\n ) {\n id\n timestamp\n logIndex\n ratePerSecondWad\n interestAccruedWad\n borrowIndexWadAfter\n transaction {\n id\n blockNumber\n }\n }\n }\n":pd,"\n query VaultNftActions($vaultId: String!, $first: Int, $skip: Int) {\n nftAttachedActions(\n where: { vault: $vaultId }\n first: $first\n skip: $skip\n orderBy: timestamp\n orderDirection: desc\n ) {\n id\n timestamp\n logIndex\n kind\n tokenId\n liquidity\n from\n transaction {\n id\n blockNumber\n }\n }\n }\n":fd,"\n query MarketDayDataById($id: ID!) {\n marketDayData(id: $id) {\n id\n date\n dayStartTimestamp\n depositCount\n withdrawCount\n debtIncreaseCount\n debtDecreaseCount\n microLiquidationCount\n nftAttachCount\n nftDetachCount\n nftPeelCount\n idleModifiedCount\n tradingFeeReinvestCount\n actionCount\n pool {\n id\n }\n }\n }\n":md,"\n query RecentMarketDayData($poolId: String!, $first: Int, $skip: Int) {\n marketDayDatas(\n where: { pool: $poolId }\n first: $first\n skip: $skip\n orderBy: date\n orderDirection: desc\n ) {\n id\n date\n dayStartTimestamp\n depositCount\n withdrawCount\n debtIncreaseCount\n debtDecreaseCount\n microLiquidationCount\n nftAttachCount\n nftDetachCount\n nftPeelCount\n idleModifiedCount\n tradingFeeReinvestCount\n actionCount\n pool {\n id\n }\n }\n }\n":yd,'\n query MarketShareBalancesByAccount($account: Bytes!, $first: Int, $skip: Int) {\n marketShareBalances(\n where: { account: $account, balance_gt: "0" }\n first: $first\n skip: $skip\n orderBy: balance\n orderDirection: desc\n ) {\n id\n account\n balance\n pool {\n id\n currency0\n currency1\n }\n }\n }\n':hd,"\n query MarketShareBalancesByPool(\n $poolId: String!\n $minBalance: BigInt!\n $first: Int\n $skip: Int\n $orderBy: MarketShareBalance_orderBy!\n $orderDirection: OrderDirection!\n ) {\n marketShareBalances(\n where: { pool: $poolId, balance_gte: $minBalance }\n first: $first\n skip: $skip\n orderBy: $orderBy\n orderDirection: $orderDirection\n ) {\n id\n account\n balance\n pool {\n id\n }\n }\n }\n":bd,"\n query MarketShareTransfersByPool(\n $poolId: String!\n $first: Int\n $skip: Int\n $orderBy: MarketShareTransfer_orderBy!\n $orderDirection: OrderDirection!\n ) {\n marketShareTransfers(\n where: { pool: $poolId }\n first: $first\n skip: $skip\n orderBy: $orderBy\n orderDirection: $orderDirection\n ) {\n id\n timestamp\n logIndex\n caller\n from\n to\n amount\n isMint\n isBurn\n pool {\n id\n }\n transaction {\n id\n blockNumber\n }\n }\n }\n":gd,"\n query AllMarkets($first: Int, $skip: Int) {\n markets(first: $first, skip: $skip, orderBy: createdAtTimestamp, orderDirection: desc) {\n id\n currency0\n currency1\n fee\n tickSpacing\n hooks\n equityLWad\n borrowIndexWad\n shareTotalSupply\n totalRlBorrowed\n maxLtvPips\n hardLtvPips\n rateOracle\n fullUtilRate\n residues0\n residues1\n vaultCount\n activeVaultCount\n activeDebtVaultCount\n activeLendAccountCount\n createdAtTimestamp\n createdAtBlockNumber\n }\n }\n":vd,"\n query MarketById($id: ID!) {\n market(id: $id) {\n id\n currency0\n currency1\n fee\n tickSpacing\n hooks\n equityLWad\n borrowIndexWad\n shareTotalSupply\n totalRlBorrowed\n maxLtvPips\n hardLtvPips\n rateOracle\n fullUtilRate\n residues0\n residues1\n vaultCount\n activeVaultCount\n activeDebtVaultCount\n activeLendAccountCount\n createdAtTimestamp\n createdAtBlockNumber\n }\n }\n":wd,"\n query VaultsByOwner($owner: Bytes!, $first: Int, $skip: Int) {\n vaults(\n where: { owner: $owner, burnedAtTimestamp: null }\n first: $first\n skip: $skip\n orderBy: createdAtTimestamp\n orderDirection: desc\n ) {\n id\n owner\n idle0\n idle1\n principalRl\n borrowIndexWadAtLastDebt\n nftCount\n lastLockedAt\n lastLtvPips\n createdAtTimestamp\n createdAtBlockNumber\n burnedAtTimestamp\n burnedAtBlockNumber\n pool {\n id\n currency0\n currency1\n fee\n tickSpacing\n hooks\n borrowIndexWad\n }\n nfts {\n id\n kind\n tokenId\n liquidityAtLastAttach\n }\n }\n }\n":Ad,"\n query VaultById($id: ID!) {\n vault(id: $id) {\n id\n owner\n idle0\n idle1\n principalRl\n borrowIndexWadAtLastDebt\n nftCount\n lastLockedAt\n lastLtvPips\n createdAtTimestamp\n createdAtBlockNumber\n burnedAtTimestamp\n burnedAtBlockNumber\n pool {\n id\n currency0\n currency1\n fee\n tickSpacing\n hooks\n borrowIndexWad\n equityLWad\n maxLtvPips\n hardLtvPips\n }\n nfts {\n id\n kind\n tokenId\n liquidityAtLastAttach\n }\n }\n }\n":Td,'\n query VaultsAtRisk($minLtvPips: BigInt!, $first: Int, $skip: Int) {\n vaults(\n where: { lastLtvPips_gte: $minLtvPips, principalRl_gt: "0", burnedAtTimestamp: null }\n first: $first\n skip: $skip\n orderBy: lastLtvPips\n orderDirection: desc\n ) {\n id\n owner\n idle0\n idle1\n principalRl\n borrowIndexWadAtLastDebt\n nftCount\n lastLockedAt\n lastLtvPips\n burnedAtTimestamp\n burnedAtBlockNumber\n pool {\n id\n currency0\n currency1\n borrowIndexWad\n maxLtvPips\n hardLtvPips\n }\n nfts {\n id\n kind\n tokenId\n liquidityAtLastAttach\n }\n }\n }\n':Ed,"\n query VaultsByPool($poolId: String!, $first: Int, $skip: Int) {\n vaults(\n where: { pool: $poolId, burnedAtTimestamp: null }\n first: $first\n skip: $skip\n orderBy: createdAtTimestamp\n orderDirection: desc\n ) {\n id\n owner\n idle0\n idle1\n principalRl\n borrowIndexWadAtLastDebt\n nftCount\n lastLockedAt\n lastLtvPips\n createdAtTimestamp\n burnedAtTimestamp\n burnedAtBlockNumber\n nfts {\n id\n kind\n tokenId\n liquidityAtLastAttach\n }\n }\n }\n":Id};function ss(e){return xd[e]??{};}var kd=ss(`
|
|
1512
|
+
query VaultDebtActions($vaultId: String!, $first: Int, $skip: Int) {
|
|
1513
|
+
debtModifiedActions(
|
|
1514
|
+
where: { vault: $vaultId }
|
|
1515
|
+
first: $first
|
|
1516
|
+
skip: $skip
|
|
1517
|
+
orderBy: timestamp
|
|
1518
|
+
orderDirection: desc
|
|
1519
|
+
) {
|
|
1520
|
+
id
|
|
1521
|
+
timestamp
|
|
1522
|
+
logIndex
|
|
1523
|
+
principalDeltaActual
|
|
1524
|
+
principalDeltaRequested
|
|
1525
|
+
borrowIndexWad
|
|
1526
|
+
deltaIdle0
|
|
1527
|
+
deltaIdle1
|
|
1528
|
+
transaction {
|
|
1529
|
+
id
|
|
1530
|
+
blockNumber
|
|
1531
|
+
gasPrice
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
`),Dd=ss(`
|
|
1536
|
+
query VaultIdleActions($vaultId: String!, $first: Int, $skip: Int) {
|
|
1537
|
+
idleModifiedActions(
|
|
1538
|
+
where: { vault: $vaultId }
|
|
1539
|
+
first: $first
|
|
1540
|
+
skip: $skip
|
|
1541
|
+
orderBy: timestamp
|
|
1542
|
+
orderDirection: desc
|
|
1543
|
+
) {
|
|
1544
|
+
id
|
|
1545
|
+
timestamp
|
|
1546
|
+
logIndex
|
|
1547
|
+
deltaAmount0
|
|
1548
|
+
deltaAmount1
|
|
1549
|
+
transaction {
|
|
1550
|
+
id
|
|
1551
|
+
blockNumber
|
|
1552
|
+
gasPrice
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
`);async function Nd(e,t,n){return e.request(kd,{vaultId:t,first:(n==null?void 0:n.first)??100,skip:(n==null?void 0:n.skip)??0});}async function Ld(e,t,n){return e.request(Dd,{vaultId:t,first:(n==null?void 0:n.first)??100,skip:(n==null?void 0:n.skip)??0});}function Bi(e,t,n,r){return e>0?e*t+n-2*r*Math.sqrt(e):NaN;}function ls(e,t,n,r){const a=e+t,i=e,o=n*a-t,s=Math.max(0,Math.min(i,o));return r>0?s/r:0;}function Pd(e,t,n,r,a){if(!(e>0)||!(n>0)||!(a>0))return NaN;const i=Math.sqrt(e);return e*t/n-2*r*i/(n*(Math.sqrt(a)+1));}function _d(e,t,n,r){return!(e>0)||!(r>0)?NaN:(e*t-n*Math.sqrt(e))/r;}function Cd(e,t,n){return!(e>0)||!(n>0)?NaN:e*t/n;}function us(e,t,n){if(!(e>0)||!(t>0))return 0;if(n<=0)return e<t?1/0:0;const r=t/e-1;return r>0?r/n*365:0;}function Md(e,t,n,r,a,i){if(!Number.isFinite(e)||!Number.isFinite(t)||!(n>0)||!(r>0)||!(a>0&&a<1)||!(i>0))return null;const o=Math.sqrt(i),s=i,u=i*(1-a)/a,d=n*r,c=e+d/o,p=t+d*o,y=(p-u*c)/(s+u);if(!Number.isFinite(y))return null;const b=c+y,m=p-s*y;if(!(b>0&&m>0))return null;const h=Math.sqrt(b*m);if(!(h>0))return null;const g=d/h;return{gamma:d,xb:c,yb:p,q:y,x:b,y:m,collateral:h,ltv:g};}var Rd=31556736;function Fi(e,t,n){const r=e/100,a=us(t,n,r);return a===1/0?"INF":a;}function cs(e){const{equityLWad:t,borrowedLWad:n,deltaLWad:r,fullUtilRate:a,rateOracleAddress:i,chainId:o,version:s,currentAprPct:l,entryLtv:u,thetaL:d}=e,c=t>0n?n*_e/t:0n,p=t>0n?(n+r)*_e/t:0n,y=Fi(l,u,d),b=E=>({preBorrowUtilPips:c,postBorrowUtilPips:p,preBorrowAprPct:l,postBorrowAprPct:l,preBorrowDaysToLiq:y,postBorrowDaysToLiq:y,oracleSupported:!1,unsupportedReason:E,postBorrowRatePerSecWad:null}),m=e.deployment?je(o,s,e.deployment):void 0;let h;if(e.rateModel)h=e.rateModel;else{const E=o;if(!Object.values(ha).includes(E)||!m&&!va(E,s))return b("chain-version-unregistered");const A=Zo(E,s,m);if(!A.has(i))return b("oracle-not-registered");h=A.resolve(i);}const{ratePerSecondWad:g}=h.getNewRate(0n,p,a),v=Number(g)*Rd/1e18*100,w=Fi(v,u,d);return{preBorrowUtilPips:c,postBorrowUtilPips:p,preBorrowAprPct:l,postBorrowAprPct:v,preBorrowDaysToLiq:y,postBorrowDaysToLiq:w,oracleSupported:!0,unsupportedReason:null,postBorrowRatePerSecWad:g};}Dn.default();var Sd={VaultCreated:Je(et({abi:$e,name:"VaultCreated"})),VaultBurned:Je(et({abi:$e,name:"VaultBurned"})),VaultLocked:Je(et({abi:$e,name:"VaultLocked"})),IdleModified:Je(et({abi:$e,name:"IdleModified"})),IdleDonated:Je(et({abi:$e,name:"IdleDonated"})),DebtModified:Je(et({abi:$e,name:"DebtModified"})),NftAttached:Je(et({abi:$e,name:"NftAttached"})),NftDetached:Je(et({abi:$e,name:"NftDetached"})),NftPeeled:Je(et({abi:$e,name:"NftPeeled"})),VaultMicroLiquidated:Je(et({abi:$e,name:"VaultMicroLiquidated"}))};new Set(Object.values(Sd).map(e=>e.toLowerCase()));async function Od(e,t,n){if(t==="0x0000000000000000000000000000000000000000")throw new Error("quoteExactInputSingle: Uniswap V4 Quoter address is unset for this chain. Pass an explicit override or update NetworkAddresses in src/utils/chains.ts.");const{result:r}=await e.simulateContract({address:t,abi:os,functionName:"quoteExactInputSingle",...(n.blockNumber!==void 0?{blockNumber:n.blockNumber}:{}),args:[{poolKey:n.poolKey,zeroForOne:n.zeroForOne,exactAmount:n.exactAmount,hookData:n.hookData??"0x"}]}),[a,i]=r;return{amountOut:a,gasEstimate:i};}function ds(e,t){if(e===0n)return t>0n?_e:0n;const n=e*ie;return t*_e/n;}var qd=2e-3,Bd=1440*365;function ps(e){const{entryPrice:t,targetPrice:n,direction:r,depositAsset:a,depositAmount:i,horizonMinutes:o,betaTime:s,market:l}=e,{aprPct:u,thetaL:d,M:c,utilizationCap:p,SIdle:y,BM:b}=l,m=Math.sqrt(t),h=t,g=t,v=a==="token0"?i:0,w=a==="token1"?i:0,E=g*v+w;if(!(E>0))return{ok:!1,error:"Effective deposit value (e·X₀ + Y₀) must be > 0. Check deposit and prices."};const A=n/t,I=u>0?u/100:0,T=o>0?o/Bd:0;let L=d;if(I>0&&T>0&&(L=d/(1+I*T)),!(L>0))return{ok:!1,error:"Time-derived LTV τ_time is non-positive. Check APR and horizon."};const x=Math.min(d,L),k=s*x,_=Math.max(1e-6,d-qd),D=Math.min(k,_);if(!(D>0&&D<d))return{ok:!1,error:"Target LTV τ_degen must be in (0, θ_L). Try shorter time or lower β."};const P=ls(y,b,p,c);if(!(P>0))return{ok:!1,error:"No borrow capacity under current utilisation caps (δ_max ≤ 0). Increase S or reduce B_M."};const W=g/m+m,q=[];let R=null,C=null,F=0,j=0;for(let re=1;re<100;re++){const te=re/100;if(!(te>0&&te<1))continue;const ne=h*(1-te)/te;if(!(ne>0)||!Number.isFinite(ne))continue;const ge=Math.sqrt(ne),de=g+ne-D*ge*W;if(!(de>0)||!Number.isFinite(de))continue;const me=D*ge*E/(c*de);if(!(me>0)||!Number.isFinite(me))continue;const ye=Md(v,w,me,c,te,t);if(!ye)continue;const{gamma:Ae,xb:pe,yb:he,q:be,x:fe,y:Y,collateral:ae,ltv:V}=ye;if(!(V>0&&V<d&&V<=D))continue;const Q=Bi(t,fe,Y,Ae);if(!(Q>0)||!Number.isFinite(Q))continue;const le=Bi(n,fe,Y,Ae),H=Pd(t,fe,Q,Ae,A);if(!Number.isFinite(H))continue;if(r==="long"){if(!(H>0))continue;}else if(!(H<0))continue;const Z=le-Q,z=Math.min(Q,le),O=z/Q;if(F++,(!C||Z>C.pnlTarget||Z===C.pnlTarget&&O>C.worstEquityRatio)&&(C={alpha:te,pnlTarget:Z,worstEquityRatio:O}),me>P)continue;j++;const Te=r==="long"?H:-H,De=_d(t,fe,Ae,Q),ue=Cd(t,fe,Q),J=me>=P-1e-9,se={direction:r,depositAsset:a,depositAmount:i,X0:v,Y0:w,P0:t,P_target:n,m:A,T_years:T,rEff:I,tauTimeRaw:L,tauDegen:D,tauOpen:V,thetaL:d,deltaCap:P,M_used:c,U_cap_used:p,alpha:te,r:ne,delta:me,gamma:Ae,x_b:pe,y_b:he,q:be,x:fe,y:Y,coll:ae,LTV:V,E0:Q,E_target:le,L_avg:H,L_display:Te,L0:De,L_infty:ue,pnlTarget:Z,worstEquity:z,worstEquityRatio:O,cappedByDelta:J};q.push(se),(!R||Z>R.pnlTarget||Z===R.pnlTarget&&O>R.worstEquityRatio)&&(R=se);}let K=1/0;if(C){const re=C.alpha,te=h*(1-re)/re,ne=Math.sqrt(te),ge=g+te-D*ne*W;if(ge>0&&Number.isFinite(ge)){const de=P*c*ge/(D*ne);Number.isFinite(de)&&de>0&&(K=a==="token0"?de/t:de);}}const $=R!==null&&C!==null&&C.alpha!==R.alpha,S={maxEfficientDeposit:K,isCapConstrained:$,unconstrainedAlpha:(C==null?void 0:C.alpha)??0,candidatesTotal:F,candidatesSurviving:j};return R?{ok:!0,position:R,candidates:q,diagnostics:S}:{ok:!1,error:"No feasible tap trading configuration for this combo of deposit, target price, time horizon and system caps. Try a smaller move, shorter time, or larger deposit."};}function Fd(e,t){const n=e.Ppool,{direction:r,depositAsset:a,depositAmount:i,targetPrice:o,horizonMinutes:s}=t;if(!(n>0))return{ok:!1,error:"Entry price P₀ must be > 0."};if(!(o>0))return{ok:!1,error:"Target price P_T must be > 0."};if(!(e.M>0))return{ok:!1,error:"Interest multiplier M must be > 0."};if(!(e.Ucap>0&&e.Ucap<=1))return{ok:!1,error:"Utilisation cap Ū must be in (0,1]."};if(!(e.thetaL>0&&e.thetaL<1.5))return{ok:!1,error:"Liquidation LTV θ_L looks invalid."};if(!(i>0))return{ok:!1,error:"Deposit amount must be > 0. (Tap Trading mode assumes a fresh vault.)"};if(!(e.betaTime>0&&e.betaTime<=1.1))return{ok:!1,error:"Time-risk factor β must be in (0,1.1]."};const l=o/n;if(r==="long"&&!(l>1))return{ok:!1,error:"For longs, target price must be above entry price."};if(r==="short"&&!(l<1))return{ok:!1,error:"For shorts, target price must be below entry price."};const u=ps({entryPrice:n,targetPrice:o,direction:r,depositAsset:a,depositAmount:i,horizonMinutes:s,betaTime:e.betaTime,market:{aprPct:e.aprPct,thetaL:e.thetaL,M:e.M,utilizationCap:e.Ucap,SIdle:e.SIdle,BM:e.BM}});if(!u.ok)return{ok:!1,error:u.error};const d=c=>({...c,S_before:e.SIdle,B_M_before:e.BM});return{ok:!0,position:d(u.position),candidates:u.candidates.map(d),diagnostics:u.diagnostics};}function Vd(e,t){const n=e.Ppool;if(!(n>0)||!(t.targetPrice>0)||!(e.M>0)||!(e.Ucap>0&&e.Ucap<=1)||!(e.thetaL>0&&e.thetaL<1.5)||!(e.betaTime>0&&e.betaTime<=1.1))return null;const r=t.targetPrice/n;if(t.direction==="long"&&!(r>1)||t.direction==="short"&&!(r<1))return null;const a=ps({entryPrice:n,targetPrice:t.targetPrice,direction:t.direction,depositAsset:t.depositAsset,depositAmount:1e-10,horizonMinutes:t.horizonMinutes,betaTime:e.betaTime,market:{aprPct:e.aprPct,thetaL:e.thetaL,M:e.M,utilizationCap:e.Ucap,SIdle:e.SIdle,BM:e.BM}});if(!a.ok)return null;const i=a.diagnostics.maxEfficientDeposit;return Number.isFinite(i)&&i>0?i:null;}var Ud=2n**96n,Wd=Number(Ud);function fs(e){if(e.sqrtPriceX96<=0n)throw new Error("displayPrice: market.sqrtPriceX96 must be > 0n");if(!Number.isInteger(e.decimals0)||!Number.isInteger(e.decimals1)||e.decimals0<0||e.decimals1<0||e.decimals0>30||e.decimals1>30)throw new Error("displayPrice: decimals0/decimals1 must be integers in [0, 30]");}function _a(e,t,n){const r=Number(e)/Wd;return r*r*Math.pow(10,t-n);}function $d(e,t,n){return Math.sqrt(_a(e,t,n));}var Hd={xV:0n,yV:0n,gammaTotalL:0n};function Vi(e,t){if(e.xV<0n||e.yV<0n||e.gammaTotalL<0n)throw new Error(`computeBammVsBlPayoff: ${t} bigint fields must be >= 0n`);}function zd(e){const{market:t,postAction:n,preAction:r,blAction:a,options:i}=e,o=(i==null?void 0:i.alphaMin)??0,s=(i==null?void 0:i.alphaMax)??4,l=(i==null?void 0:i.steps)??80;if(!Number.isFinite(o)||o<0)throw new Error("computeBammVsBlPayoff: alphaMin must be a finite, non-negative number");if(!Number.isFinite(s)||s<=o)throw new Error("computeBammVsBlPayoff: alphaMax must be finite and > alphaMin");if(!Number.isInteger(l)||l<1||l>1e3)throw new Error("computeBammVsBlPayoff: steps must be an integer in [1, 1000]");Vi(n,"postAction");const u=r??Hd;if(r&&Vi(r,"preAction"),a&&(a.depositT0<0n||a.depositT1<0n||a.loanT0<0n||a.loanT1<0n))throw new Error("computeBammVsBlPayoff: blAction bigint fields must be >= 0n");fs(t);const{decimals0:d,decimals1:c}=t,p=_a(t.sqrtPriceX96,d,c);if(!Number.isFinite(p)||p<=0)throw new Error("computeBammVsBlPayoff: entry price derived from sqrtPriceX96 is non-finite or non-positive");const y=Math.pow(10,d),b=Math.pow(10,c),m=Math.pow(10,(d+c)/2),h=Number(n.xV)/y,g=Number(n.yV)/b,v=Number(n.gammaTotalL)/m,w=Number(n.xV-u.xV)/y,E=Number(n.yV-u.yV)/b,A=Number(n.gammaTotalL-u.gammaTotalL)/m;let I=0,T=0;a&&(I=Number(a.depositT0-a.loanT0)/y,T=Number(a.depositT1-a.loanT1)/b);let L;h>0&&g>0?L=v/Math.sqrt(h*g):L=v>0?1:0,Number.isFinite(L)||(L=1);const x=Math.max(0,Math.min(1e6,Math.floor(L*1e6))),k=[];for(let q=0;q<=l;q++){const R=o+(s-o)*q/l,C=p*R,F=Math.sqrt(Math.max(0,C)),j=w*C+E-2*A*F,K=a?I*C+T:null;k.push({alpha:R,priceHuman:C,bammEquity:j,blEquity:K,canonicalLtvPipsBamm:x});}const _={entrySqrtPriceX96:t.sqrtPriceX96,entryPriceHuman:p,points:k};if(w>0&&A>0){const q=A/w,R=q*q;_.minEquityBammAlpha=R/p,_.minEquityBammValue=E-A*A/w;}const D=[];if(w!==0){const q=A*A-w*E;if(q>=0){const R=Math.sqrt(q),C=(A-R)/w,F=(A+R)/w;C>0&&D.push(C*C/p),F>0&&F!==C&&D.push(F*F/p);}}else if(A!==0){const q=E/(2*A);q>0&&D.push(q*q/p);}D.sort((q,R)=>q-R);const P=D.length===2?D[0]:void 0,W=D.length>=1?D[D.length-1]:void 0;if(P!==void 0&&(_.zeroEquityBammAlphaLower=P),W!==void 0&&(_.zeroEquityBammAlphaUpper=W),a&&I!==0){const q=-T/I;q>0&&(_.zeroEquityBlAlpha=q/p);}return _;}function Gd(e){const{requestedRl:t,projectedIdle:n,borrowIndexWad:r,poolKey:a,poolState:i}=e;if(t<=0n||r<=0n)return{appliedRl:0n,cappedByBridge:!1,bridgeGapL:0n};const o=Ke(t,r);if(n.x<=0n||n.y<=0n)return{appliedRl:0n,cappedByBridge:!0,bridgeGapL:o};const s=lr({idle0:n.x,idle1:n.y,poolKey:a,poolState:i});return s===null||s<=0n?{appliedRl:0n,cappedByBridge:!0,bridgeGapL:o}:s>=o?{appliedRl:t,cappedByBridge:!1,bridgeGapL:0n}:{appliedRl:s*ie/r,cappedByBridge:!0,bridgeGapL:o-s};}function Yn(e){return{sqrtPriceX96:e.sqrtPriceX96,tick:e.tickCurrent,protocolFee:0,lpFee:0,liquidity:e.inRangeLiquidity};}function ur(e,t){const n=e.x0+t.fromWallet0-(t.swapInputIsToken0?t.swapInput:0n)+(t.swapInputIsToken0?0n:t.swapOutputMin),r=e.y0+t.fromWallet1-(t.swapInputIsToken0?0n:t.swapInput)+(t.swapInputIsToken0?t.swapOutputMin:0n);return{x:n<0n?0n:n,y:r<0n?0n:r};}function ms(e,t,n,r){const a=ur(t,n),i=r>0n?yt(r,e.poolKey,Yn(e),!0):{amount0:0n,amount1:0n};return i===null?null:{idle0:a.x>i.amount0?a.x-i.amount0:0n,idle1:a.y>i.amount1?a.y-i.amount1:0n};}function ys(e,t,n,r,a){if(a===null)return ms(e,t,n,r);const i=ur(t,n);return{idle0:i.x>a.amount0?i.x-a.amount0:0n,idle1:i.y>a.amount1?i.y-a.amount1:0n};}function jd(e){const{idle0:t,idle1:n,rLAfter:r,borrowIndexWad:a,maxLtvPips:i}=e;if(r<=0n)return!0;const o=ut(t<0n?0n:t,n<0n?0n:n),s=r*a*_e,l=o*ie*BigInt(i);return s<=l;}var Kd=1e6;function Nn(e){return e/Kd;}function Yd(e){return!Number.isFinite(e)||e<=0?0:e>=1e4?1:e/1e4;}function Mn(e,t){if(e===0n)return 0;const n=e<0n?-1:1,r=e<0n?-e:e,a=10n**BigInt(t),i=r/a,o=r%a;return n*(Number(i)+Number(o)/Number(a));}function Qd(e,t){return!Number.isFinite(e)||e<=0?0n:BigInt(Math.ceil(e*10**t));}function Xd(e,t){return!Number.isFinite(e)||e<=0?0n:BigInt(Math.floor(e*10**t));}function Zd(e,t){return!Number.isFinite(e)||e<=0?0n:BigInt(Math.ceil(e*t));}function Ca(e,t,n,r,a){const{sqrtPriceX96:i,borrowIndexWad:o,decimals0:s,decimals1:l}=e,u=mt(i,s,l),d=Ot(i,s,l),c=Yd(a),p=d*(1-c),y=Number(t.rL0)*Number(o)/1e18,b=10**((s+l)/2),m=y/b,h=Mn(t.x0,s),g=Mn(t.y0,l),v=Mn(n,s),w=Mn(r,l),E=h+v-m/u,A=g-m*u;return{sqrtP:u,p:d,pEff:p,xEff:E,yEff:A,gammaPreHuman:m,gammaScale:b,yWHuman:w,x0Human:h,y0Human:g,dHuman:v};}function hs(e,t,n,r){const{sqrtP:a,pEff:i,xEff:o,yEff:s,yWHuman:l,gammaPreHuman:u}=e,d=o+t/a,c=s+t*a-l,p=r==="preserve-collateral"?Math.max(0,(t-u)/a):d;let y;if(i<=0?y=c>=0?0:Number.POSITIVE_INFINITY:y=Math.max(0,-c/i),i<=0||n<=0||n>=1)return{discriminantNonNegative:!1,qLtvMinus:0,qLtvPlus:0,qLo:y,qHi:p,A:d,B:c};const b=i,m=-(d*i-c),h=t*t/(n*n)-d*c,g=m*m-4*b*h;if(!Number.isFinite(g)||g<0)return{discriminantNonNegative:!1,qLtvMinus:0,qLtvPlus:0,qLo:y,qHi:p,A:d,B:c};const v=Math.sqrt(g),w=(-m-v)/(2*b),E=(-m+v)/(2*b);return{discriminantNonNegative:!0,qLtvMinus:w,qLtvPlus:E,qLo:y,qHi:p,A:d,B:c};}function Kt(e,t,n){const r=Nn(e.tauPips);if(r<=0||r>=1||!Number.isFinite(t)||t<0)return Number.NEGATIVE_INFINITY;const a=Ca(e.market,e.vault,e.deposit,n,e.quoteHaircutBps),i=hs(a,t,r,e.collateralPolicy);if(!i.discriminantNonNegative)return Number.NEGATIVE_INFINITY;const o=1/10**e.market.decimals0,s=Math.max(i.qLtvMinus,i.qLo,o);return Math.min(i.qLtvPlus,i.qHi)-s;}function Jd(e,t,n){const r=Nn(e.tauPips),a=Ca(e.market,e.vault,e.deposit,n,e.quoteHaircutBps),i=hs(a,t,r,e.collateralPolicy),o=e.market.decimals0,s=1/10**o;if(!i.discriminantNonNegative)return{q:0n,qUpperWei:0n,lowerFloat:Number.POSITIVE_INFINITY,upperFloat:Number.NEGATIVE_INFINITY,integerFeasible:!1};const l=Math.max(i.qLtvMinus,i.qLo,s),u=Math.min(i.qLtvPlus,i.qHi),d=Qd(l,o),c=Xd(u,o),p=d>=1n?d:1n;return{q:p,qUpperWei:c,lowerFloat:l,upperFloat:u,integerFeasible:p>=1n&&p<=c};}var ep=8,Ui=5,bs=1.1,tp=1e-10,np=50,_r=8;function Qr(e,t){const n=Nn(e.tauPips);if(n<=0||n>=1||t<=0n)return Wi("price-unviable","heuristic");const r=Ca(e.market,e.vault,e.deposit,t,e.quoteHaircutBps),{gammaPreHuman:a,gammaScale:i}=r,o=ap(e,r),s=a+o,l=Number.isFinite(e.utilMaxGammaNewHuman)?a+e.utilMaxGammaNewHuman:Number.POSITIVE_INFINITY,u=[];let d=!1,c=!1,p=s,y=s,b=Kt(e,s,t);for(u.push({gammaHuman:s,gap:b,refinedFromPrevious:!1}),s>l?y=l:b>0&&(c=!0,p=a,y=s);!c&&y<l;){const g=Math.min(y*bs,l);if(g<=y)break;const v=Kt(e,g,t);if(ip(b,v)){d=!0;const E=op(e,y,g,t,u);if(E.feasibleFound){p=E.bracketLo,y=E.bracketHi,c=!0;break;}b=E.lastGap,y=E.lastGammaHuman;continue;}if(u.push({gammaHuman:g,gap:v,refinedFromPrevious:!1}),v>0){p=y,y=g,c=!0;break;}y=g,b=v;}if(c){const{gammaResult:g,bisectionSteps:v}=sp(e,p,y,t),w=lp(e,g,y,t);if(w.feasible){const E=Math.max(0,w.gammaHuman-a);return{feasible:!0,gammaNewHuman:E,gammaNewL:Zd(E,i),gammaTotalHuman:w.gammaHuman,q:w.q,sweepSamples:u,bisectionSteps:v,validationRetries:w.retries,adaptiveRefinementTriggered:d,extendedSweepReached:!1};}}const m=up(e,y,l,r,t,u),h={feasible:!1,gammaNewHuman:0,gammaNewL:0n,gammaTotalHuman:0,q:0n,infeasibleReason:m.infeasibleReason,sweepSamples:u,bisectionSteps:0,validationRetries:0,adaptiveRefinementTriggered:d,extendedSweepReached:!0};return m.infeasibleReason==="price-unviable"?{...h,diagnosticCertainty:"heuristic"}:h;}function Wi(e,t){return{...{feasible:!1,gammaNewHuman:0,gammaNewL:0n,gammaTotalHuman:0,q:0n,infeasibleReason:e,sweepSamples:[],bisectionSteps:0,validationRetries:0,adaptiveRefinementTriggered:!1,extendedSweepReached:!1},diagnosticCertainty:t};}function rp(e,t,n){if(e<=0n)return 0;const r=10n**30n,a=1n<<96n,i=t+n;if(i%2===0){const l=10n**BigInt(i/2),u=a*l,c=(e*r+u-1n)/u;return Number(c)/Number(r)*(1+1e-9);}const o=Number(e)/Number(a),s=Math.pow(10,i/2);return o/s*(1+1e-9);}function ap(e,t){const n=1/t.gammaScale,r=e.collateralPolicy==="preserve-collateral"?rp(e.market.sqrtPriceX96,e.market.decimals0,e.market.decimals1):0;if(t.gammaPreHuman>0)return Math.max(n,t.gammaPreHuman*1e-12,r);const a=Number(e.marketEquityLWad??0n)/1e18,o=Math.max(a/1e9,0),l=Math.max(o,1e3)/t.gammaScale;if(Number.isFinite(l)&&l>0)return Math.max(l,r);const u=Nn(e.tauPips),d=1-u*u;if(t.xEff>0&&d>0){const c=Math.sqrt(d);return Math.max(t.xEff*t.sqrtP*(1-c)/Math.max(c,1e-9)*1e-9,r);}return Math.max(1e-9,r);}function ip(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))return!1;const n=Math.abs(e),r=Math.abs(t);return n<=0&&r<=0?!1:Math.max(n,r)/Math.max(Math.min(n,r),1e-300)>ep;}function op(e,t,n,r,a){let i=t,o=Kt(e,i,r);for(let s=1;s<=Ui;s++){const l=s/Ui,u=t+(n-t)*l,d=Kt(e,u,r);if(a.push({gammaHuman:u,gap:d,refinedFromPrevious:!0}),d>0)return{feasibleFound:!0,bracketLo:i,bracketHi:u,lastGammaHuman:u,lastGap:d};i=u,o=d;}return{feasibleFound:!1,bracketLo:t,bracketHi:n,lastGammaHuman:i,lastGap:o};}function sp(e,t,n,r){let a=t,i=n,o=0;for(;o<np;){const s=0.5*(a+i);if(!Number.isFinite(s)||s<=a||s>=i||(Kt(e,s,r)>0?i=s:a=s,o++,i-a<Math.max(tp*i,0)))break;}return{gammaResult:i,bisectionSteps:o};}function lp(e,t,n,r){let a=t;for(let i=0;i<=_r;i++){const o=Jd(e,a,r);if(o.integerFeasible)return{feasible:!0,gammaHuman:a,q:o.q,retries:i};const s=Math.max((n-t)/_r,a*1e-6);a+=s;}return{feasible:!1,gammaHuman:a,q:0n,retries:_r};}function up(e,t,n,r,a,i){const o=Nn(e.tauPips),s=Math.sqrt(Math.max(0,1-o*o)),l=r.xEff>0&&s>0&&s<1?r.xEff*r.sqrtP*(1-s)/s:0,u=Number.isFinite(n)?Math.max(10*n,100*l,t*100):Math.max(100*l,t*100);if(!Number.isFinite(u)||u<=t)return{infeasibleReason:"price-unviable"};let d=t;for(;d<u;){const c=Math.min(d*bs,u);if(c<=d)break;const p=Kt(e,c,a);if(i.push({gammaHuman:c,gap:p,refinedFromPrevious:!1}),p>0)return{infeasibleReason:"utilization-blocked"};d=c;}return{infeasibleReason:"price-unviable"};}var cp=Number(In)/1e6;function Qn(e){const{market:t,vault:n,deposit:r,tauPips:a,collateralPolicy:i}=e,o=e.depositIsToken0??!0,s=(()=>{const J=e.quoteHaircutBps;return J==null||!Number.isFinite(J)||J<=0?0:J>=1e4?1e4:Math.ceil(J);})(),l=s*100,u=(n==null?void 0:n.x0)??0n,d=(n==null?void 0:n.y0)??0n,c=(n==null?void 0:n.rL0)??0n,p={x0:o?u:d,y0:o?d:u,rL0:c},y=o?t.sqrtPriceX96:Zt(t.sqrtPriceX96),b=o?t.decimals0:t.decimals1,m=o?t.decimals1:t.decimals0,h={sqrtPriceX96:y,borrowIndexWad:t.borrowIndexWad,maxLtvPips:t.maxLtvPips,hardLtvPips:t.hardLtvPips,decimals0:b,decimals1:m},g={market:h,vault:p,deposit:r,// Capacity is y_w-independent, but the underlying math primitives accept
|
|
1557
|
+
// a yWtarget. Pass 0 — the ceilings (yMaxLtv*) don't read it.
|
|
1558
|
+
yWtarget:0n,tauPips:a},v=mt(y,b,m),w=a/1e6,E=Math.sqrt(Math.max(0,1-w*w)),A=Math.pow(10,(b+m)/2),T=Number(c)*Number(t.borrowIndexWad)/1e18/A,L=Number(r)/10**b,x=Number(p.x0)/10**b,k=Number(p.y0)/10**m,_=x+L-T/v,D=k-T*v,P=_>0&&E>0?_*v*(1-E)/E:0,W=P<T&&T>0;let q=null;if(!W){const J=Ot(y,b,m),se=D+_*J*(1-E)/(1+E);q=se>0?BigInt(Math.floor(se*10**m)):0n;}const R=(()=>{if(T<=0)return k>0?BigInt(Math.floor(k*10**m)):0n;const J=x+L;if(J<=0)return 0n;const se=k-T*T/(w*w*J);if(!Number.isFinite(se))return 0n;const Se=Math.max(0,Math.min(k,se));return BigInt(Math.floor(Se*10**m));})(),C=Uo(g),F=$o(g),j=Dc(g),K=t.equityLWad>0n?t.borrowedLWad*_e/t.equityLWad:0n,$=Number(K)/1e6;let S=null,re=Number.POSITIVE_INFINITY;const te=Ma(t);if(te===0n)S=0n,re=0;else{re=Number(te)/1e18/A;const se=Math.max(P,T),Se=T+re;if(Se>=se)S=null;else{const tn=_+Se/v;if(tn<=0)S=0n;else{const qt=D+Se*v-Se*Se/(w*w*tn);S=Number.isFinite(qt)&&qt>0?BigInt(Math.floor(qt*10**m)):0n;}}}const ne=R>F?R:F,ge=S!==null&&S<C?S:C,de=s===0?C:Lc(g,l),me=s===0?F:_c(g,l),ye=R>me?R:me,Ae=S!==null&&S<de?S:de;let pe,he,be,fe;if(i==="preserve-collateral"){pe=R,be=R;const J=dp({sizingMarket:h,canonVault:p,deposit:r,tauPips:a,utilMaxGammaNewHuman:re,// Path 3 (needs-borrow) only becomes the active regime once y_w
|
|
1559
|
+
// exceeds the path-1 idle short-circuit band. Probe from there.
|
|
1560
|
+
lowerBound:R+1n,upperBound:ge}),se=$i({sizingMarket:h,canonVault:p,deposit:r,tauPips:a,quoteHaircutBps:0,marketEquityLWad:t.equityLWad,utilMaxGammaNewHuman:re,upperBound:ge});if(he=J>se?J:se,s===0)fe=he;else{const Se=$i({sizingMarket:h,canonVault:p,deposit:r,tauPips:a,quoteHaircutBps:s,marketEquityLWad:t.equityLWad,utilMaxGammaNewHuman:re,upperBound:Ae});fe=J>Se?J:Se;}}else pe=ne,he=ge,be=ye,fe=Ae;const Y=pe>he?pe:he,ae=be>fe?be:fe,V=zo({market:h,vault:p,yWtarget:Y,tauPips:a});function Q(J){return W&&J.yMaxEffective_===0n&&T>0?"regime-b":J.yMaxNoDebt_>=J.yMaxBorrow_?i==="preserve-collateral"?"idle":J.yMaxLtvNoBorrow_>R?T>0?"ltv-no-new-borrow":"zero-debt-swap":"idle":S!==null&&S<J.yMaxLtvWithBorrow_?"utilization":W?"regime-b":"ltv";}const le=Q({yMaxEffective_:Y,yMaxNoDebt_:pe,yMaxBorrow_:he,yMaxLtvNoBorrow_:F,yMaxLtvWithBorrow_:C}),H=s>0?Q({yMaxEffective_:ae,yMaxNoDebt_:be,yMaxBorrow_:fe,yMaxLtvNoBorrow_:me,yMaxLtvWithBorrow_:de}):void 0,Z=Jt(t.equityLWad,t.borrowIndexWad),z=10n**18n,O=H??le;let Te,De;switch(O){case"utilization":{De=te,Te=te/z;break;}case"ltv":{const J=Wo(g);Te=J.gammaNewL,De=J.gammaNewL*z;break;}case"unknown":{Te=null,De=null;break;}// 'idle' | 'ltv-no-new-borrow' | 'zero-debt-swap' | 'regime-b' | 'min-debt':
|
|
1561
|
+
// No new borrow contributes at slider-max. `'min-debt'` is unreachable
|
|
1562
|
+
// from the capacity layer in practice (resolveBinding doesn't produce
|
|
1563
|
+
// it — recipe-side concept), but listing it here keeps the switch
|
|
1564
|
+
// exhaustive at the type level.
|
|
1565
|
+
default:Te=0n,De=0n;}const ue={yMaxLtv:j,yMaxFromUtilization:S,yMaxNoDebt:pe,yMaxBorrow:he,yMaxEffective:Y,yMaxNoDebtAtHaircut:be,yMaxBorrowAtHaircut:fe,yMaxEffectiveAtHaircut:ae,quoteHaircutBpsApplied:s,collateralPolicyApplied:i,yKnee:q,utilizationPre:$,utilizationCap:cp,minDebtFloorRl:Z,bindingConstraint:le,dMinNoSwap:V,gammaNewLAtEffectiveMax:Te,deltaLWadAtEffectiveMax:De};return H!==void 0&&(ue.bindingConstraintAtHaircut=H),ue;}function $i(e){const{sizingMarket:t,canonVault:n,deposit:r,tauPips:a,quoteHaircutBps:i,marketEquityLWad:o,utilMaxGammaNewHuman:s,upperBound:l}=e;if(l<=0n)return 0n;const u=p=>p<=0n?!1:Qr({market:t,vault:n,deposit:r,tauPips:a,collateralPolicy:"preserve-collateral",quoteHaircutBps:i,utilMaxGammaNewHuman:s,marketEquityLWad:o},p).feasible;if(!u(1n))return 0n;if(u(l))return l;let d=1n,c=l;for(let p=0;p<264&&c-d>1n;p++){const y=d+(c-d)/2n;u(y)?d=y:c=y;}return d;}function dp(e){const{sizingMarket:t,canonVault:n,deposit:r,tauPips:a,utilMaxGammaNewHuman:i,lowerBound:o,upperBound:s}=e;if(s<=0n||o>s)return 0n;const l=Math.pow(10,(t.decimals0+t.decimals1)/2),u=g=>jn({market:t,vault:n,deposit:r,yWtarget:g,tauPips:a}),d=g=>{if(g<=0n)return!1;const v=u(g);return!v.feasible||v.regime!=="needs-borrow"?!1:Number(v.gammaNewL)/l<=i;};if(d(s))return s;const c=g=>{if(g<=0n)return!1;const v=u(g);return v.feasible?v.regime!=="no-new-borrow":!0;};if(!c(s))return 0n;let p=o>1n?o-1n:0n,y=s;o>0n&&c(o)&&(y=o);for(let g=0;g<264&&y-p>1n;g++){const v=p+(y-p)/2n;c(v)?y=v:p=v;}const b=y;if(!d(b))return 0n;let m=b,h=s;for(let g=0;g<264&&h-m>1n;g++){const v=m+(h-m)/2n;d(v)?m=v:h=v;}return m;}function Xr(e){const t=Math.pow(10,(e.decimals0+e.decimals1)/2),n=Ma(e);return Number(n)/1e18/t;}function Ma(e){const t=In*e.equityLWad/_e-e.borrowedLWad;return t<=0n||e.borrowIndexWad<=0n?0n:t/e.borrowIndexWad*e.borrowIndexWad;}var pp=Number(In)/1e6;async function fp(e,t,n,r){if(!Number.isInteger(e.tauPips)||e.tauPips<0||e.deposit<0n||// Beyond int128 the BalanceDelta packing would WRAP the deposit into a
|
|
1566
|
+
// different (negative) on-chain amount — the encoder now throws, and
|
|
1567
|
+
// the quote surface refuses first with the typed reason.
|
|
1568
|
+
e.deposit>ce||e.comfortCapLtvPips!==void 0&&(!Number.isInteger(e.comfortCapLtvPips)||e.comfortCapLtvPips<0)||e.quoteHaircutBps!==void 0&&(!Number.isInteger(e.quoteHaircutBps)||e.quoteHaircutBps<0||e.quoteHaircutBps>1e4)){const O=r.capacity??gs(e);return Et(e,O,"invalid-input",0);}const i=e.tauPips>e.market.maxLtvPips;i&&(e={...e,tauPips:e.market.maxLtvPips});const o=r.capacity!==void 0&&!i?r.capacity:Qn({market:e.market,vault:e.vault,deposit:e.deposit,tauPips:e.tauPips,collateralPolicy:e.collateralPolicy,depositIsToken0:e.depositIsToken0??!0,...(e.quoteHaircutBps!==void 0?{quoteHaircutBps:e.quoteHaircutBps}:{})});if(r.capacity!==void 0&&r.capacity.collateralPolicyApplied!==e.collateralPolicy)throw new Error(`computeBorrowRecipeForTarget: input.collateralPolicy ('${e.collateralPolicy}') does not match opts.capacity.collateralPolicyApplied ('${r.capacity.collateralPolicyApplied}'). Capacity must be computed for the same policy as the recipe call.`);if(r.deadline!==void 0&&r.nowTimestamp!==void 0&&r.deadline<=r.nowTimestamp)return Et(e,o,"invalid-input",0);if(e.vault===null){const O=e.owner;if(O===void 0||O==="0x0000000000000000000000000000000000000000")return Et(e,o,"invalid-input",0);}if(t<0n||t>ce)return Et(e,o,"invalid-input",0);if(t>o.yMaxEffectiveAtHaircut){if(e.collateralPolicy==="preserve-collateral"){const O=Qn({market:e.market,vault:e.vault,deposit:e.deposit,tauPips:e.tauPips,collateralPolicy:"allow-collateral-swap",depositIsToken0:e.depositIsToken0??!0,...(e.quoteHaircutBps!==void 0?{quoteHaircutBps:e.quoteHaircutBps}:{})});if(t<=O.yMaxEffectiveAtHaircut)return Et(e,o,"preserve-collateral-blocked",0);}return Et(e,o,"above-capacity",0);}const s=t>o.yMaxNoDebtAtHaircut,{market:l,vault:u,deposit:d,tauPips:c}=e,p=e.depositIsToken0??!0,y=Ra(e.quoteHaircutBps),b=(u==null?void 0:u.x0)??0n,m=(u==null?void 0:u.y0)??0n,h=(u==null?void 0:u.rL0)??0n,g={x0:p?b:m,y0:p?m:b,rL0:h},v=p?l.sqrtPriceX96:Zt(l.sqrtPriceX96),w=p?l.decimals0:l.decimals1,E=p?l.decimals1:l.decimals0,A=t,I={sqrtPriceX96:v,borrowIndexWad:l.borrowIndexWad,maxLtvPips:l.maxLtvPips,hardLtvPips:l.hardLtvPips,decimals0:w,decimals1:E},T={market:I,vault:g,deposit:d,yWtarget:A,tauPips:c},L=Math.pow(10,(w+E)/2),k=Number(h)*Number(l.borrowIndexWad)/1e18/L;let _=0,D=!1,P={feasible:!1};if(!s){const O=jn(T);O.feasible&&O.regime==="no-new-borrow"&&(P={feasible:!0,dispatch:"no-new-borrow-noswap",branch:Hi(O.gammaTotalL,O.gammaNewL,O.xV,O.yV,p,l.decimals0,l.decimals1)});}const W=e.collateralPolicy==="preserve-collateral";let q={feasible:!1};if(!s&&!P.feasible&&!W){if(k>0){const O=await bp(T,k,p,l.decimals0,l.decimals1,I,A,L,n,r.signal);_+=O.quoteCount,O.feasible&&O.branch&&O.encodeMeta&&(q={feasible:!0,dispatch:"no-new-borrow-swap",branch:O.branch,encodeMeta:O.encodeMeta});}else if(A>0n){const O=await gp(T,p,l.decimals0,l.decimals1,I,A,y,n,r.signal);_+=O.quoteCount,O.feasible&&O.branch&&O.encodeMeta&&(q={feasible:!0,dispatch:"no-new-borrow-swap",branch:O.branch,encodeMeta:O.encodeMeta});}}let R={feasible:!1};if(!P.feasible&&!q.feasible){const O=jn(T);if(O.feasible&&O.regime==="needs-borrow"){const Te=Number(O.gammaNewL)/L,De=Xr(l);Te<=De&&(R={feasible:!0,dispatch:"needs-borrow-noswap",branch:Hi(O.gammaTotalL,O.gammaNewL,O.xV,O.yV,p,l.decimals0,l.decimals1)});}}let C={feasible:!1},F=null;if(!P.feasible&&!q.feasible&&!R.feasible){const O=await Ap(e,T,A,p,v,w,E,L,y,l.decimals0,l.decimals1,n,r.signal);_+=O.quoteCount,O.feasible&&O.branch&&O.encodeMeta?(C={feasible:!0,dispatch:"needs-borrow-swap",branch:O.branch,encodeMeta:O.encodeMeta},O.settleAdjusted&&(D=!0)):F=O.infeasibleReason;}const j=[P.feasible?{dispatch:"no-new-borrow-noswap",branch:P.branch??null,feasible:!0,infeasibleReason:null}:{dispatch:"no-new-borrow-noswap",branch:null,feasible:!1,infeasibleReason:null},q.feasible?{dispatch:"no-new-borrow-swap",branch:q.branch??null,feasible:!0,infeasibleReason:null}:{dispatch:"no-new-borrow-swap",branch:null,feasible:!1,infeasibleReason:null},R.feasible?{dispatch:"needs-borrow-noswap",branch:R.branch??null,feasible:!0,infeasibleReason:null}:{dispatch:"needs-borrow-noswap",branch:null,feasible:!1,infeasibleReason:null},C.feasible?{dispatch:"needs-borrow-swap",branch:C.branch??null,feasible:!0,infeasibleReason:null}:{dispatch:"needs-borrow-swap",branch:null,feasible:!1,infeasibleReason:F}],K=j.find(O=>O.feasible)??null;let $,S,re=null,te,ne;K?($=K.dispatch,S=K.branch,re=K.dispatch==="no-new-borrow-swap"&&q.feasible?q.encodeMeta??null:K.dispatch==="needs-borrow-swap"&&C.feasible?C.encodeMeta??null:null):(S=null,F==="utilization-blocked"?($="needs-borrow-swap",te="utilization-blocked"):F==="price-unviable"?($="needs-borrow-swap",te="price-unviable",ne="heuristic"):F==="preserve-collateral-blocked"?($="needs-borrow-swap",te="preserve-collateral-blocked"):($="infeasible",te="unknown"));const ge=(S==null?void 0:S.gammaNewL)??0n,de=ge>0n?xa(ge,l.borrowIndexWad):0n,me=l.borrowedLWad+de*l.borrowIndexWad,ye=l.equityLWad>0n?me*_e/l.equityLWad:0n,Ae=Number(ye)/1e6,pe=Jt(l.equityLWad,l.borrowIndexWad),he=h+(ge>0n?(ge*ie+l.borrowIndexWad-1n)/l.borrowIndexWad:0n),be=ge>0n&&he<pe;let fe;be&&S!==null&&(S.isSwap||(fe=mp(e,pe,h,l.borrowIndexWad,l.decimals0,l.decimals1,p)),S=null,$="infeasible",te="below-min-debt-floor",re=null);let Y,ae;e.comfortCapLtvPips!==void 0&&S!==null&&S.actualLtvPips>e.comfortCapLtvPips&&(Y=hp(e,S,p),ae=yp(e,S,t,p),S=null,$="infeasible",te="above-comfort-cap",re=null);const{recipeKind:V,debtDelta:Q,builderKind:le}=Tp(S),H=Ep(S,d,g.x0),Z=Ip(S,le,e,t,re,r.deadline),z={dispatch:$,branch:S,candidates:j,encodeInput:Z,builderKind:le,utilizationPre:o.utilizationPre,utilizationPost:Ae,utilizationCap:pp,minDebtFloorRl:pe,belowMinDebtFloor:be,quoteCount:_};return Q!==void 0&&(z.debtDelta=Q),V!==void 0&&(z.recipeKind=V),H!==void 0&&(z.swapAttribution=H),te!==void 0&&(z.infeasibleReason=te),ne!==void 0&&(z.diagnosticCertainty=ne),D&&(z.path4SettleAdjusted=!0),fe!==void 0&&(z.minBorrowableY_w=fe),Y!==void 0&&(z.maxY_wUnderComfortCap=Y),ae!==void 0&&(z.suggestedDepositIncreaseForComfortCap=ae),z;}function mp(e,t,n,r,a,i,o){var P,W;if(n>=t||r<=0n)return;const s=t-n;if(s<=0n)return;const l=s*r,u=o?e.market.decimals0:e.market.decimals1,d=o?e.market.decimals1:e.market.decimals0,c=Math.pow(10,(u+d)/2),p=Number(l)/1e18/c,y=((P=e.vault)==null?void 0:P.x0)??0n,b=((W=e.vault)==null?void 0:W.y0)??0n,m=o?y:b,h=o?b:y,g=mt(o?e.market.sqrtPriceX96:Zt(e.market.sqrtPriceX96),u,d),w=Number(n)*Number(r)/1e18/c,E=Number(m)/10**u,A=Number(h)/10**d,I=Number(e.deposit)/10**u,T=E+I-w/g,L=A-w*g,x=w+p,k=e.tauPips/1e6,_=T+x/g;if(_<=0)return;const D=L+x*g-x*x/(k*k*_);if(!(!Number.isFinite(D)||D<=0))return BigInt(Math.ceil(D*10**d));}function yp(e,t,n,r){var k,_,D;if(e.comfortCapLtvPips===void 0||t.isSwap)return;const a=e.comfortCapLtvPips/1e6;if(a<=0||a>=1)return;const i=r?e.market.decimals0:e.market.decimals1,o=r?e.market.decimals1:e.market.decimals0,s=Math.pow(10,(i+o)/2),l=mt(r?e.market.sqrtPriceX96:Zt(e.market.sqrtPriceX96),i,o),u=((k=e.vault)==null?void 0:k.x0)??0n,d=((_=e.vault)==null?void 0:_.y0)??0n,c=r?u:d,p=r?d:u,y=((D=e.vault)==null?void 0:D.rL0)??0n,m=Number(y)*Number(e.market.borrowIndexWad)/1e18/s,h=Number(c)/10**i,g=Number(p)/10**o,v=Number(e.deposit)/10**i,w=h+v-m/l,E=g-m*l,A=Number(n)/10**o,I=Number(t.gammaTotalL)/s,T=E+I*l-A;if(T<=0)return;const x=I*I/(a*a*T)-(w+I/l);if(!(!Number.isFinite(x)||x<=0))return BigInt(Math.ceil(x*10**i));}function hp(e,t,n){var T,L,x;if(e.comfortCapLtvPips===void 0||t.isSwap)return;const r=e.comfortCapLtvPips/1e6;if(r<=0||r>=1)return;const a=n?e.market.decimals0:e.market.decimals1,i=n?e.market.decimals1:e.market.decimals0,o=Math.pow(10,(a+i)/2),s=mt(n?e.market.sqrtPriceX96:Zt(e.market.sqrtPriceX96),a,i),l=((T=e.vault)==null?void 0:T.x0)??0n,u=((L=e.vault)==null?void 0:L.y0)??0n,d=n?l:u,c=n?u:l,p=((x=e.vault)==null?void 0:x.rL0)??0n,b=Number(p)*Number(e.market.borrowIndexWad)/1e18/o,m=Number(d)/10**a,h=Number(c)/10**i,g=Number(e.deposit)/10**a,v=m+g-b/s,w=h-b*s,E=Number(t.gammaTotalL)/o,A=v+E/s;if(A<=0)return;const I=w+E*s-E*E/(r*r*A);if(!(!Number.isFinite(I)||I<=0))return BigInt(Math.floor(I*10**i));}async function bp(e,t,n,r,a,i,o,s,l,u){const d=Ot(i.sqrtPriceX96,i.decimals0,i.decimals1),c=mt(i.sqrtPriceX96,i.decimals0,i.decimals1),p=Number(o)/10**i.decimals1,b=Number(e.vault.y0)/10**i.decimals1-t*c,m=Math.max(0,p-b),h=m>0?BigInt(Math.ceil(m/d*10**i.decimals0)):0n;if(h<=0n)return{feasible:!1,quoteCount:0};const g=await l({amountIn:h,inputIsToken0:n,purpose:"no-new-borrow-primary",signal:u}),v=Gr(e,h,g.minAmountOut);if(!v.feasible)return{feasible:!1,quoteCount:1};if(v.gammaMinHuman<=t&&t<=v.gammaMaxHuman){const I=jr(e,t,h,g.minAmountOut);if(I.feasible)return{feasible:!0,branch:Xn(I.gammaTotalL,0n,// γ_new = 0 (no-new-borrow path)
|
|
1569
|
+
h,g.minAmountOut,I.xV,I.yV,n,r,a),encodeMeta:{quote:g,amountIn:h,inputIsToken0:n},quoteCount:1};}if(t>=v.gammaMinHuman)return{feasible:!1,quoteCount:1};const w=kc(e,h,g.minAmountOut);if(w<=0n||w===h)return{feasible:!1,quoteCount:1};const E=await l({amountIn:w,inputIsToken0:n,purpose:"no-new-borrow-recovery",signal:u}),A=Gr(e,w,E.minAmountOut);if(!A.feasible)return{feasible:!1,quoteCount:2};if(A.gammaMinHuman<=t&&t<=A.gammaMaxHuman){const I=jr(e,t,w,E.minAmountOut);if(I.feasible)return{feasible:!0,branch:Xn(I.gammaTotalL,0n,w,E.minAmountOut,I.xV,I.yV,n,r,a),encodeMeta:{quote:E,amountIn:w,inputIsToken0:n},quoteCount:2};}return{feasible:!1,quoteCount:2};}async function gp(e,t,n,r,a,i,o,s,l){const u=Ot(a.sqrtPriceX96,a.decimals0,a.decimals1);if(u<=0)return{feasible:!1,quoteCount:0};const d=Ra(o)/1e4,c=u*(1-d);if(c<=0)return{feasible:!1,quoteCount:0};const p=e.vault.x0+e.deposit;if(p<=0n)return{feasible:!1,quoteCount:0};const y=i>e.vault.y0?i-e.vault.y0:0n;if(y===0n)return{feasible:!1,quoteCount:0};const m=Number(y)/10**a.decimals1/c;let h=BigInt(Math.ceil(m*10**a.decimals0));if(h<=0n)return{feasible:!1,quoteCount:0};h>p&&(h=p);const g=await s({amountIn:h,inputIsToken0:t,purpose:"no-new-borrow-primary",signal:l});if(g.minAmountOut+e.vault.y0>=i)return Zr(h,g,p,i,e,t,n,r,a,1);if(g.minAmountOut<=0n)return{feasible:!1,quoteCount:1};let w=(h*y+g.minAmountOut-1n)/g.minAmountOut;if(w>p&&(w=p),w===h)return{feasible:!1,quoteCount:1};const E=await s({amountIn:w,inputIsToken0:t,purpose:"no-new-borrow-primary",signal:l});if(E.minAmountOut+e.vault.y0>=i)return Zr(w,E,p,i,e,t,n,r,a,2);if(w===p)return{feasible:!1,quoteCount:2};const A=await s({amountIn:p,inputIsToken0:t,purpose:"no-new-borrow-primary",signal:l});return A.minAmountOut+e.vault.y0<i?{feasible:!1,quoteCount:3}:await wp(w,p,p,A,i,e,t,n,r,a,s,l,/* quotesUsedSoFar */3);}var vp=4;async function wp(e,t,n,r,a,i,o,s,l,u,d,c,p){let y=e,b=t,m=n,h=r,g=p;for(let v=0;v<vp&&!(b-y<=1n);v++){const w=y+(b-y)/2n;if(w<=y||w>=b)break;const E=await d({amountIn:w,inputIsToken0:o,purpose:"no-new-borrow-primary",signal:c});g++,E.minAmountOut+i.vault.y0>=a?(b=w,m=w,h=E):y=w;}return Zr(m,h,t,a,i,o,s,l,u,g);}function Zr(e,t,n,r,a,i,o,s,l,u){const d=n-e,c=a.vault.y0+t.minAmountOut-r;return d<0n||c<0n?{feasible:!1,quoteCount:u}:{feasible:!0,branch:Xn(0n,// γ_total = 0
|
|
1570
|
+
0n,// γ_new = 0
|
|
1571
|
+
e,t.minAmountOut,d,c,i,o,s),encodeMeta:{quote:t,amountIn:e,inputIsToken0:i},quoteCount:u};}async function Ap(e,t,n,r,a,i,o,s,l,u,d,c,p){const y=Xr(e.market),b={market:t.market,vault:t.vault,deposit:t.deposit,tauPips:t.tauPips,collateralPolicy:e.collateralPolicy,quoteHaircutBps:l,utilMaxGammaNewHuman:y,marketEquityLWad:e.market.equityLWad},m=Qr(b,n);if(!m.feasible)return e.collateralPolicy==="preserve-collateral"&&Qr({...b,collateralPolicy:"allow-collateral-swap"},n).feasible?{feasible:!1,infeasibleReason:"preserve-collateral-blocked",quoteCount:0}:{feasible:!1,infeasibleReason:m.infeasibleReason==="utilization-blocked"?"utilization-blocked":"price-unviable",quoteCount:0};const h=await c({amountIn:m.q,inputIsToken0:r,purpose:"needs-borrow-swap",signal:p}),g=Gr(t,m.q,h.minAmountOut);if(!g.feasible)return{feasible:!1,infeasibleReason:"price-unviable",quoteCount:1};let w=m.gammaTotalHuman,E=!1;if(w<g.gammaMinHuman&&(w=g.gammaMinHuman,E=!0),w>g.gammaMaxHuman)return{feasible:!1,infeasibleReason:"price-unviable",quoteCount:1};const A=Number(t.vault.rL0)*Number(t.market.borrowIndexWad)/1e18,I=Math.pow(10,(t.market.decimals0+t.market.decimals1)/2),T=A/I,L=Math.max(0,w-T),x=Xr(e.market);if(L>x)return{feasible:!1,infeasibleReason:"utilization-blocked",quoteCount:1};const k=jr(t,w,m.q,h.minAmountOut);if(!k.feasible)return{feasible:!1,infeasibleReason:"price-unviable",quoteCount:1};const _={feasible:!0,branch:Xn(k.gammaTotalL,k.gammaNewL,m.q,h.minAmountOut,k.xV,k.yV,r,u,d),encodeMeta:{quote:h,amountIn:m.q,inputIsToken0:r},infeasibleReason:null,quoteCount:1};return E&&(_.settleAdjusted=!0),_;}function Ra(e){return e==null||!Number.isFinite(e)||e<=0?0:e>=1e4?1e4:Math.ceil(e);}function Hi(e,t,n,r,a,i,o){const{xV:s,yV:l}=a?{xV:n,yV:r}:{xV:r,yV:n},u=gn(e,s,l,i,o);return{isSwap:!1,gammaTotalL:e,gammaNewL:t,q:0n,swapInputIsToken0:a,swapMinOutUsed:0n,xV:s,yV:l,actualLtvPips:u,feasible:!0};}function Xn(e,t,n,r,a,i,o,s,l){const{xV:u,yV:d}=o?{xV:a,yV:i}:{xV:i,yV:a},c=gn(e,u,d,s,l);return{isSwap:!0,gammaTotalL:e,gammaNewL:t,q:n,swapInputIsToken0:o,swapMinOutUsed:r,xV:u,yV:d,actualLtvPips:c,feasible:!0};}function Tp(e){return e===null?{builderKind:null}:e.gammaNewL===0n&&!e.isSwap?{recipeKind:"withdraw-idle",debtDelta:"none",builderKind:"borrow"}:e.gammaNewL===0n&&e.isSwap?{recipeKind:"internal-swap",debtDelta:"none",builderKind:"borrow"}:{recipeKind:"borrow",debtDelta:"new",builderKind:"borrow"};}function Ep(e,t,n){if(e===null||!e.isSwap||e.q<=0n)return;const r=e.q<n?e.q:n,a=e.q-r;return{inputCanon:e.q,fromExistingIdle:r,fromFreshDeposit:a<t?a:t};}function Ip(e,t,n,r,a,i){var p;if(e===null||t===null)return null;const o=n.depositIsToken0??!0,s=o?{amount0:n.deposit,amount1:0n}:{amount0:0n,amount1:n.deposit},l=o?{amount0:0n,amount1:r}:{amount0:r,amount1:0n},u=i??BigInt(Math.floor(Date.now()/1e3)+3600),d=((p=n.vault)==null?void 0:p.owner)??n.owner??"0x0000000000000000000000000000000000000000",c=e.isSwap&&e.q>0n;return{market:n.market,vault:n.vault,deposit:s,withdraw:l,borrowGammaNewL:e.gammaNewL,swap:{enabled:c,input:c?e.q:0n,inputIsToken0:e.swapInputIsToken0,minOutput:c?e.swapMinOutUsed:0n,route:(a==null?void 0:a.quote.route)??null,// The caller's slippage must reach the route encoder — omitting it
|
|
1572
|
+
// silently re-defaults to 50 bps in the builder. Pass the NORMALIZED
|
|
1573
|
+
// value (same clamp/round the sizing used): a fractional raw input
|
|
1574
|
+
// would size fine and then throw during BigInt route encoding.
|
|
1575
|
+
...(n.quoteHaircutBps!==void 0?{slippageBps:Ra(n.quoteHaircutBps)}:{})},maxLtvPips:n.tauPips,deadline:u,owner:d};}function gs(e){return Qn({market:e.market,vault:e.vault,deposit:0n,tauPips:0,collateralPolicy:e.collateralPolicy,depositIsToken0:e.depositIsToken0??!0});}function zi(e,t){return Et(e,gs(e),t,0);}function Et(e,t,n,r){const a=Jt(e.market.equityLWad,e.market.borrowIndexWad),i={dispatch:"infeasible",branch:null,candidates:[{dispatch:"no-new-borrow-noswap",branch:null,feasible:!1,infeasibleReason:null},{dispatch:"no-new-borrow-swap",branch:null,feasible:!1,infeasibleReason:null},{dispatch:"needs-borrow-noswap",branch:null,feasible:!1,infeasibleReason:null},{dispatch:"needs-borrow-swap",branch:null,feasible:!1,infeasibleReason:n??null}],encodeInput:null,builderKind:null,utilizationPre:t.utilizationPre,utilizationPost:t.utilizationPre,utilizationCap:t.utilizationCap,minDebtFloorRl:a,belowMinDebtFloor:!1,quoteCount:r};return n!==void 0&&(i.infeasibleReason=n),n==="price-unviable"&&(i.diagnosticCertainty="heuristic"),i;}function vs(e,t){return e.status==="unavailable"?{ok:!1,assessment:{status:"unavailable",reason:e.reason,refs:e.refs,detail:e.detail}}:e.idle0!==t.x0||e.idle1!==t.y0?{ok:!1,assessment:{status:"unavailable",reason:"vault-state-mismatch",refs:e.refs,detail:`collateral idle (${e.idle0}, ${e.idle1}) does not match lifecycle vault idle (${t.x0}, ${t.y0})`}}:{ok:!0,snapshot:e};}function xp(e,t,n){return{status:"unavailable",reason:e,refs:t,detail:n};}function ws(e,t,n){if(e.blockNumber!==t.blockNumber)throw new Error(`projectVerifiedCollateral: snapshot block ${e.blockNumber} does not match frame ${t.blockNumber}`);if(e.blockHash!==t.blockHash)throw new Error(`projectVerifiedCollateral: snapshot hash ${e.blockHash} does not match frame ${t.blockHash}`);const r=wa(e.version,{idle0:n.idle0Post,idle1:n.idle1Post,positions:e.positions});return{status:"verified-at-frame",basis:"sdk-contract-parity",frame:{blockNumber:t.blockNumber,blockHash:t.blockHash},vaultId:e.vaultId,refs:e.refs,positions:e.positions,currentFloorL:e.sdkFloorL,contractFloorL:e.contractFloorL,floorLPost:r,ltvPipsPost:kp(r,n.rLPost,n.borrowIndexWad)};}function kp(e,t,n){return t<=0n?null:e<=0n?_e:ds(e,t*n);}function Sa(e){return e.rL<=0n?!0:e.floorL<=0n?!1:ds(e.floorL,e.rL*e.borrowIndexWad)<=BigInt(e.maxLtvPips);}var Dp=200n;function Gi(e){return(e*(10000n+Dp)+9999n)/10000n;}function Bn(e){const{market:t,vault:n}=e,r=Jt(t.equityLWad,t.borrowIndexWad),a=e.deltaRl;if(a===0n)return{source:null,headroom:null,rLMin:r,feasible:!1,forbiddenZone:!1,residualLtvFails:!1,overRepayRequested:!1,fundedByLabel:"Nothing to repay"};if(a>n.rL0)return{source:null,headroom:null,rLMin:r,feasible:!1,forbiddenZone:!1,residualLtvFails:!1,overRepayRequested:!0,fundedByLabel:"Requested Δr exceeds outstanding debt — clamp to full repay"};const i=n.rL0-a;if(i>0n&&i<r)return{source:null,headroom:null,rLMin:r,feasible:!1,forbiddenZone:!0,residualLtvFails:!1,overRepayRequested:!1,fundedByLabel:"Below min-debt floor — repay in full or pick a smaller amount"};const o=Ke(a,t.borrowIndexWad),s=i,l=Ke(s,t.borrowIndexWad),u=n.x0,d=n.y0,c=e.walletBalance0??0n,p=e.walletBalance1??0n,y=Yn(t),b=lr({idle0:u,idle1:d,poolKey:t.poolKey,poolState:y})??0n,m=Number(t.sqrtPriceX96)/2**96,h=Math.max(1e3,t.maxLtvPips-1e4),g=Math.min(t.maxLtvPips,h),v=o+(l*1000000n+BigInt(h)-1n)/BigInt(h),w=_=>{const D=yt(_,t.poolKey,y,!0);if(D===null)return null;const P=D.amount0,W=D.amount1;if(b>=_)return{source:{source:"idle",fromIdle0:0n,fromIdle1:0n,fromWallet0:0n,fromWallet1:0n,swapInput:0n,swapInputIsToken0:!0,swapOutputMin:0n},fundedByLabel:"Vault idle (no approvals)"};const q=u<P?P-u:0n,R=d<W?W-d:0n,C=u>P?u-P:0n,F=d>W?d-W:0n,j=m*m;let K=null;if(C>0n&&R>0n){const ne=e.idleSwapInput??Gi(BigInt(Math.ceil(Number(R)/j)));ne>0n&&ne<=C&&(K={source:"idle-swap",fromIdle0:0n,fromIdle1:0n,fromWallet0:0n,fromWallet1:0n,swapInput:ne,swapInputIsToken0:!0,swapOutputMin:R});}else if(F>0n&&q>0n){const ne=e.idleSwapInput??Gi(BigInt(Math.ceil(Number(q)*j)));ne>0n&&ne<=F&&(K={source:"idle-swap",fromIdle0:0n,fromIdle1:0n,fromWallet0:0n,fromWallet1:0n,swapInput:ne,swapInputIsToken0:!1,swapOutputMin:q});}if(K)return{source:K,fundedByLabel:"Vault idle + internal swap (no approvals)"};const $=q>0n&&q<=c?q:0n,S=R>0n&&R<=p?R:0n,re={source:"idle+wallet",fromIdle0:0n,fromIdle1:0n,fromWallet0:$,fromWallet1:S,swapInput:0n,swapInputIsToken0:!0,swapOutputMin:0n};let te="Insufficient idle + wallet to cover this size";return $>0n&&S>0n?te="Vault idle + wallet (approvals on both sides)":$>0n?te="Vault idle + wallet (approval needed for token0)":S>0n&&(te="Vault idle + wallet (approval needed for token1)"),{source:re,fundedByLabel:te};},E=(_,D)=>{const P=w(_);if(P===null)return{source:null,headroom:null,feasible:!1,residualLtvFails:!1,fundedByLabel:"Cannot size repayment funding at this pool price"};const{source:W,fundedByLabel:q}=P,R=ur(n,W),C=Gd({requestedRl:a,projectedIdle:R,borrowIndexWad:t.borrowIndexWad,poolKey:t.poolKey,poolState:Yn(t)}),F=C.appliedRl>=a;let j=!1;if(F&&s>0n){const K=ms(t,n,W,o);if(K===null)j=!0;else if(e.collateral){const $=wa(e.collateral.version,{idle0:K.idle0,idle1:K.idle1,positions:e.collateral.positions});j=!Sa({floorL:$,rL:s,borrowIndexWad:t.borrowIndexWad,maxLtvPips:D});}else j=!jd({idle0:K.idle0,idle1:K.idle1,rLAfter:s,borrowIndexWad:t.borrowIndexWad,maxLtvPips:D});}return{source:W,fundedByLabel:q,headroom:C,residualLtvFails:j,feasible:F&&!j};},A=e.collateral&&s>0n?E(o,g):null,{source:I,fundedByLabel:T,headroom:L,residualLtvFails:x,feasible:k}=A!=null&&A.feasible?A:E(v,t.maxLtvPips);return{source:I,headroom:L,rLMin:r,feasible:k,forbiddenZone:!1,residualLtvFails:x,overRepayRequested:!1,fundedByLabel:T};}var Vt=Ct*Ct,Np=31556736;function Lp(e){const{market:t,vault:n,slippageBps:r}=e;if(!Number.isFinite(r)||!Number.isInteger(r)||r<0||r>1e4)throw new Error("computeVaultLtvProfile: slippageBps must be an integer in [0, 10000]");const{decimals0:a,decimals1:i}=t,o=t.hardLtvPips/1e6,s=Ke(n.rL0,t.borrowIndexWad);if(s===0n)return{hasDebt:!1,currentLtvFrac:0,bestLtvAfterRebalanceFrac:0,daysToLiquidation:"INF",rebalanceSwap:null};const u=gn(s,n.x0,n.y0,a,i)/1e6;let d=null;if(t.currentRatePerSecWad!==null){const E=Number(t.currentRatePerSecWad)/1e18*Np,A=us(u,o,E);d=A===1/0?"INF":A;}const c=t.sqrtPriceX96*t.sqrtPriceX96;if(c===0n)return{hasDebt:!0,currentLtvFrac:u,bestLtvAfterRebalanceFrac:u,daysToLiquidation:d,rebalanceSwap:null};const p=n.x0,y=n.y0,b=10000n-BigInt(r);let m=null,h=0n,g=!1;if(p*c>y*Vt&&b>0n){g=!0;const E=p/2n-y*Vt*10000n/(c*2n*b);E>0n&&(m=E,h=m*c*b/(Vt*10000n));}else if(y*Vt>p*c&&b>0n){g=!1;const E=y/2n-p*c*10000n/(Vt*2n*b);E>0n&&(m=E,h=m*Vt*b/(c*10000n));}let v=u;if(m!==null&&m>0n){const E=g?p-m:p+h,A=g?y+h:y-m,T=gn(s,E,A,a,i)/1e6;T<u?v=T:m=null;}return{hasDebt:!0,currentLtvFrac:u,bestLtvAfterRebalanceFrac:v,daysToLiquidation:d,rebalanceSwap:m===null||m===0n?null:{amountIn:m,inputIsToken0:g}};}var Pp={hasDebt:!1,debt:{gammaL:0n,valueT0:0,valueT1:0,repayShape:{t0Wei:0n,t1Wei:0n}}};function _p(e){const{market:t,vault:n}=e;fs(t);const{decimals0:r,decimals1:a}=t,i=_a(t.sqrtPriceX96,r,a);if(!Number.isFinite(i)||i<=0)throw new Error("computeVaultStateSnapshot: entry price derived from sqrtPriceX96 is non-finite or non-positive");const o=(n==null?void 0:n.x0)??0n,s=(n==null?void 0:n.y0)??0n,l=Math.pow(10,r),u=Math.pow(10,a),d=Number(o)/l,c=Number(s)/u,p=d*i+c,y=p/i,b={valueT0:y,valueT1:p,composition:{t0Wei:o,t1Wei:s}};if(n===null||n.rL0===0n)return{...Pp,idle:b,netValueAtSpot:{valueT0:y,valueT1:p}};const m=Ke(n.rL0,t.borrowIndexWad),h=Math.pow(10,(r+a)/2),g=Number(m)/h,v=$d(t.sqrtPriceX96,r,a),w=2*g*v,E=v>0?2*g/v:0,A={sqrtPriceX96:t.sqrtPriceX96,tick:t.tickCurrent,protocolFee:0,lpFee:0,liquidity:t.inRangeLiquidity},I=yt(m,t.poolKey,A,!0);if(I===null)throw new Error("computeVaultStateSnapshot: getAmountsForFullRangeLiquidity returned null for a debt-bearing vault — market.poolKey.tickSpacing or sqrtPriceX96 likely produces out-of-range full-range ticks. Check market context invariants.");const T={t0Wei:I.amount0,t1Wei:I.amount1};return{hasDebt:!0,debt:{gammaL:m,valueT0:E,valueT1:w,repayShape:T},idle:b,netValueAtSpot:{valueT0:y-E,valueT1:p-w}};}async function vn(e,t,n){try{await jt(e,t,n);}catch(r){if(r instanceof kn)return r;throw r;}return null;}async function Oa(e,t){const n=je(t.chainId,t.version,t.deployment),{addresses:r}=n,a=await Gt(e,t.blockNumber);ee(t.signal,t.fn);const i=a.blockNumber,[o,s,l,u,d]=await Promise.all([// Exits never consume the rate model, so custom-oracle markets must not
|
|
1576
|
+
// be blocked: assemble with the canonical model unconditionally and
|
|
1577
|
+
// surface a non-canonical oracle as data (the quotes warn).
|
|
1578
|
+
ns(e,{aegisStateView:r.aegisStateView,v4StateView:r.stateView,poolId:t.poolId,rateModel:t.rateModel??Dn.default(),blockNumber:i}),Qo(e,r.vaultRegistry,t.vaultId,i).then(h=>({exists:!0,owner:h})).catch(h=>{if(Kn(h))return{exists:!1,owner:null};throw h;}),rs(e,{aegisStateView:r.aegisStateView,vaultId:t.vaultId,owner:t.owner,frame:a}).then(h=>({reorg:null,vault:h}),h=>{if(h instanceof kn)return{reorg:h,vault:null};throw h;}),e.readContract({address:r.vaultRegistry,abi:Ht,functionName:"isApprovedForAll",args:[t.owner,r.aegisRouterV1],blockNumber:i}),// Least-privilege onboarding: a per-vault approval is as good as the
|
|
1579
|
+
// blanket one. Reverts (burned vault) fold into "not approved".
|
|
1580
|
+
e.readContract({address:r.vaultRegistry,abi:Ht,functionName:"getApproved",args:[t.vaultId],blockNumber:i}).catch(qn)]);ee(t.signal,t.fn);const c=l.reorg??(await vn(e,a,t.fn));ee(t.signal,t.fn),xn(n,o.context.poolKey.hooks);const p=!t.rateModel&&o.rateOracle.toLowerCase()!==r.variableInterestRate.toLowerCase(),y=p?{...o.context,currentRatePerSecWad:null}:o.context,b=u||d!==null&&d.toLowerCase()===r.aegisRouterV1.toLowerCase(),m=p?o.rateOracle:null;return{addresses:r,frame:a,market:y,vault:s.exists?l.vault:null,ownerOnChain:s.owner,routerApproved:b,nonCanonicalOracle:m,frameReorg:c};}function qa(e){return e?[`Market rate oracle ${e} is not the canonical model; the echoed market.currentRatePerSecWad is null (rate unavailable — this exit does not depend on it).`]:[];}function Ba(e,t,n){return e.status==="rejected-at-frame"?[`The complete ${n} call reverted at the quote frame; no calldata is returned.`]:e.status==="re-quote-required"?e.reason==="quote-frame-expired"?["The quote exceeded its freshness window; re-quote before submission."]:[`The quote frame ${t.blockNumber} is no longer the current head; re-quote before submission.`]:[];}function Fa(e){const t=[];return e.ownerOnChain.toLowerCase()!==e.expectedOwner.toLowerCase()&&t.push({gate:"ownership",vaultId:e.vaultId,ownerOnChain:e.ownerOnChain,expectedOwner:e.expectedOwner}),e.vaultPoolId.toLowerCase()!==e.expectedPoolId.toLowerCase()&&t.push({gate:"pool-identity",vaultPoolId:e.vaultPoolId,expectedPoolId:e.expectedPoolId}),e.routerApproved||t.push({gate:"router-authorization",owner:e.expectedOwner,router:e.router,vaultRegistry:e.vaultRegistry}),e.deadline<=e.blockTimestamp&&t.push({gate:"deadline-expired",deadline:e.deadline,blockTimestamp:e.blockTimestamp}),t;}async function As(e,t,n,r,a,i){const o=u=>u===ke?e.getBalance({address:n,blockNumber:r}):Jc(e,u,n,r),[s,l]=await Promise.all([a!==void 0?Promise.resolve(a):o(t.currency0),i!==void 0?Promise.resolve(i):o(t.currency1)]);return{walletBalance0:s,walletBalance1:l};}function Jr(e,t,n,r){const a=[];return t>0n&&a.push(ji(e.currency0,t,r)),n>0n&&a.push(ji(e.currency1,n,r)),a;}function ji(e,t,n){const r=e===ke;return{approvalType:"permit2",token:e,amount:t,required:!r,nativeValue:r?t:0n,spender:n};}var Cp=(1n<<160n)-1n,ea=2**48-1,Ts=(1n<<256n)-1n;function en(e){const{permit:t,ownerOnChain:n,router:r,requiredTokens:a,blockTimestamp:i}=e,o=l=>({gate:"permit-invalid",detail:l});if(t.owner.toLowerCase()!==n.toLowerCase())return o(`permit owner ${t.owner} is not the on-chain vault owner ${n}`);if(t.permitBatch.spender.toLowerCase()!==r.toLowerCase())return o(`permit spender ${t.permitBatch.spender} is not the router ${r}`);if(t.permitBatch.sigDeadline<0n||t.permitBatch.sigDeadline>Ts)return o("permit sigDeadline is outside the uint256 encoding domain");if(t.permitBatch.sigDeadline<=i)return o(`permit sigDeadline ${t.permitBatch.sigDeadline} expired at chain time`);const s=/* @__PURE__ */new Set();for(const l of t.permitBatch.details){if(l.amount<0n||l.amount>Cp)return o(`permit amount for ${l.token} is outside the uint160 encoding domain`);if(!Number.isSafeInteger(l.expiration)||l.expiration<0||l.expiration>ea)return o(`permit expiration for ${l.token} is outside the uint48 encoding domain`);if(!Number.isSafeInteger(l.nonce)||l.nonce<0||l.nonce>ea)return o(`permit nonce for ${l.token} is outside the uint48 encoding domain`);const u=l.token.toLowerCase();if(s.has(u))return o(`permit contains duplicate entries for token ${l.token}`);s.add(u);}for(const l of a){if(l.amount<=0n||l.token===ke)continue;const u=t.permitBatch.details.find(d=>d.token.toLowerCase()===l.token.toLowerCase());if(!u)return o(`permit is missing required token ${l.token}`);if(u.amount<l.amount)return o(`permit amount ${u.amount} for ${l.token} is below the required ${l.amount}`);if(BigInt(u.expiration)<=i)return o(`permit allowance for ${l.token} expired at chain time`);}return null;}async function Es(e,t){const n=en(t);if(n)return n;const r=await So(e,{chainId:t.chainId,permit2Address:t.permit2Address,permit:t.permit,blockNumber:t.blockNumber});return cr({...t.permit,verification:r},t.router,{blockNumber:t.blockNumber,permit2:t.permit2Address,chainId:t.chainId});}function cr(e,t,n){const r=l=>({gate:"permit-invalid",detail:l}),a=e.verification;if(a===void 0)return r("permit signature/nonces are unverified — supply permit.verification from verifyPermit2Batch");if(n.blockNumber===void 0)return r("no bound block to pin the permit verification to — a verified permit requires a quote frame");if(a.blockNumber!==n.blockNumber)return r(`permit verification block ${a.blockNumber} is not the quote's bound block ${n.blockNumber}`);const i=n.permit2??hc;if(a.permit2.toLowerCase()!==i.toLowerCase())return r(`permit verification ran against Permit2 ${a.permit2}, expected ${i}`);if(n.chainId===void 0)return r("no target chainId to bind the permit verification to");if(a.chainId!==n.chainId)return r(`permit verification ran for chain ${a.chainId}, expected ${n.chainId}`);const o=Ro(e.permitBatch,a.chainId,a.permit2);if(a.payloadDigest!==o)return r("permit verification is bound to a different permit payload or domain");if(a.signatureDigest!==xt(e.signature))return r("permit verification is bound to a different signature");if(a.owner.toLowerCase()!==e.owner.toLowerCase()||a.spender.toLowerCase()!==t.toLowerCase())return r("permit verification was performed for a different owner/spender pair");if(!a.signatureValid)return r(`permit signature failed pinned EIP-712/1271 verification for owner ${e.owner}`);const s=/* @__PURE__ */new Set();for(const l of e.permitBatch.details){const u=l.token.toLowerCase();if(s.has(u))return r(`permit contains duplicate entries for token ${l.token}`);s.add(u);}if(a.nonces.length!==e.permitBatch.details.length)return r(`verification carries ${a.nonces.length} nonce rows for a ${e.permitBatch.details.length}-detail batch — exact coverage required`);for(const l of e.permitBatch.details){const u=a.nonces.find(d=>d.token.toLowerCase()===l.token.toLowerCase());if(u===void 0)return r(`permit nonce for ${l.token} was not verified`);if(u.permitNonce!==l.nonce)return r(`verified nonce ${u.permitNonce} for ${l.token} does not match the permit's ${l.nonce}`);if(u.permitNonce!==u.onChainNonce)return r(`permit nonce ${u.permitNonce} for ${l.token} does not match the live Permit2 nonce ${u.onChainNonce}`);}return a.valid?null:r("permit verification evidence reports itself invalid");}function dr(e){const t=e.quoteTtlSeconds!==void 0&&e.quoteTtlSeconds<0n;if(e.frame===null)return{expiresAt:null,ttlInvalid:t};const n=Vc(e.deadline,e.frame,t?0n:e.quoteTtlSeconds);return{expiresAt:Rt(n,e.permitBatch,e.requiredTokens??[]),ttlInvalid:t};}function Rt(e,t,n){if(t===void 0)return e;if(t.sigDeadline<0n||t.sigDeadline>Ts)return 0n;let r=e<t.sigDeadline?e:t.sigDeadline;for(const a of n){if(a.amount<=0n||a.token===ke)continue;const i=t.details.find(o=>o.token.toLowerCase()===a.token.toLowerCase());if(i!==void 0){if(!Number.isSafeInteger(i.expiration)||i.expiration<0||i.expiration>ea)return 0n;const o=BigInt(i.expiration);o<r&&(r=o);}}return r;}var Cr=60n;function Is(e){const t=e.quoteTtlSeconds??Cr,n=t>Cr,{expiresAt:r,ttlInvalid:a}=dr({deadline:e.deadline,frame:e.frame,quoteTtlSeconds:n?Cr:t,permitBatch:e.permitBatch}),i=a||n;return{expiresAt:r,ttlInvalid:i,warnings:i?[`${e.fn} requires quoteTtlSeconds between 0 and 60.`]:[]};}function Zn(e){return{validUntil:e.validUntil,expiresAt:e.validUntil,validity:{mode:"frame-only",requestedDeadline:e.requestedDeadline,validUntil:e.validUntil,reQuoteRequiredAfterBlock:(e.executionFrameMaxAgeSeconds??0n)>0n?null:e.frame.blockNumber,...((e.executionFrameMaxAgeSeconds??0n)>0n?{executionFrameMaxAgeSeconds:e.executionFrameMaxAgeSeconds}:{}),reason:"delayed-success-bound-unproven",maximumBorrowIndexWad:null,maximumEngineTokenDebit:e.maximumEngineTokenDebit}};}var xs=365n*86400n,Mp=100n*xs,Rp=(1n<<256n)-1n,Sp=["constant-rate","static-collateral","no-position-actions","no-compounding-into-principal","horizon-overstated-vs-compounding","integer-pip-display-input"];function Op(e){return e!==null&&typeof e.blockNumber=="bigint"&&e.blockNumber>=0n&&typeof e.blockTimestamp=="bigint"&&e.blockTimestamp>=0n&&/^0x[0-9a-fA-F]{64}$/.test(e.blockHash)&&Number.isSafeInteger(e.observedAt)&&e.observedAt>=0;}function Ki(e){const t=e.maximumHorizonSeconds??xs,n=Op(e.frame)?{...e.frame}:null,r={thresholdKind:e.thresholdKind,thresholdPips:e.thresholdPips,currentLtvPips:e.currentLtvPips,rate:{...e.rate},frame:n,asOfTimestamp:(n==null?void 0:n.blockTimestamp)??null,maximumHorizonSeconds:t,assumptions:Sp},a=d=>({...r,status:"unavailable",seconds:null,reason:d}),{currentLtvPips:i,thresholdPips:o,rate:s}=e;if(!["borrow-limit","hard-liquidation"].includes(e.thresholdKind)||typeof e.hasDebt!="boolean"||!Number.isSafeInteger(o)||o<=0||o>1e6||i!==null&&(!Number.isSafeInteger(i)||i<0)||typeof t!="bigint"||t<1n||t>Mp||!["current-pre-action","projected-post-action","unavailable"].includes(s.basis)||(s.basis==="unavailable"?s.ratePerSecWad!==null:typeof s.ratePerSecWad!="bigint"||s.ratePerSecWad<0n||s.ratePerSecWad>Rp)||!e.hasDebt&&i!==null&&i!==0)return a("invalid-input");if(n===null)return a("frame-unavailable");if(!e.hasDebt)return{...r,status:"no-debt",seconds:null};if(i===null)return a("ltv-unavailable");if(i>=o)return{...r,status:"at-threshold",seconds:0n};if(i===0)return a("ltv-below-resolution");if(s.basis==="unavailable")return a("rate-unavailable");if(s.ratePerSecWad===0n)return{...r,status:"no-growth",seconds:null};const l=BigInt(o-i)*ie,u=BigInt(i)*s.ratePerSecWad;return l>t*u?{...r,status:"beyond-horizon",seconds:null}:{...r,status:"estimated",seconds:l/u,bound:"upper"};}function qp(e){const t=e.maxLtvPips<=e.hardLtvPips;return{borrowLimit:Ki({...e,thresholdKind:"borrow-limit",thresholdPips:t?e.maxLtvPips:0}),hardLiquidation:Ki({...e,thresholdKind:"hard-liquidation",thresholdPips:t?e.hardLtvPips:0})};}var Bp=31556736;async function Fp(e){var Ae,pe,he,be,fe,Y,ae;let t;if((e.deployment??((Ae=e.aprProjection)==null?void 0:Ae.deployment))||e.chainId!==void 0){if(e.chainId===void 0)throw new Error("Aegis deployment requires a quote chainId.");const V=e.chainId,Q=e.market.poolKey.hooks,le=Hr(V,Q,e.deployment);t=le;const H=e.aprProjection;if(H&&(je(H.chainId,H.version,le),H.deployment)){const z=Hr(V,Q,H.deployment);if(Object.keys(le.addresses).some(Te=>le.addresses[Te].toLowerCase()!==z.addresses[Te].toLowerCase()))throw new Error("Borrow projection does not match the pool hook Aegis deployment.");}const Z=e.execution;if(Z&&(Z.router.toLowerCase()!==le.addresses.aegisRouterV1.toLowerCase()||Z.vaultRegistry.toLowerCase()!==le.addresses.vaultRegistry.toLowerCase()))throw new Error("Borrow execution does not match the pool hook Aegis deployment.");}const r=e.frame??null,a=e.deadline??(r?r.blockTimestamp+3600n:BigInt(Math.floor(Date.now()/1e3)+3600)),i=(pe=e.execution)==null?void 0:pe.permit,s=[{token:e.inputIsToken0?e.market.poolKey.currency0:e.market.poolKey.currency1,amount:e.collateralIn}],l=a<=Kr(r),{expiresAt:u,ttlInvalid:d}=dr({deadline:a,frame:r,quoteTtlSeconds:e.quoteTtlSeconds,permitBatch:i==null?void 0:i.permitBatch,requiredTokens:s}),c=Vp(e.vault,r),p=e.collateralPolicy??"preserve-collateral",y={market:e.market,vault:e.vault,deposit:e.collateralIn,tauPips:e.tauPips,collateralPolicy:p,depositIsToken0:e.inputIsToken0,quoteHaircutBps:e.slippageBps,...(e.comfortCapLtvPips!==void 0?{comfortCapLtvPips:e.comfortCapLtvPips}:{}),...(e.owner!==void 0?{owner:e.owner}:{})},b=d||l?zi(y,"invalid-input"):c.status==="unavailable"?zi(y,"collateral-unavailable"):await fp(y,e.borrowOut,e.fetchQuote,{signal:e.signal,...(e.capacity!==void 0?{capacity:e.capacity}:{}),deadline:a,...(r?{nowTimestamp:r.blockTimestamp}:{})}),m=b.branch,h=m!==null&&m.feasible&&b.encodeInput!==null;let g=null,v=null,w=0n,E=0n;h&&(w=xa(m.gammaNewL,e.market.borrowIndexWad),E=w*e.market.borrowIndexWad,g=(((he=e.vault)==null?void 0:he.rL0)??0n)+w,v=Ke(g,e.market.borrowIndexWad));const A=h?{needed:m.isSwap,amountIn:m.q,isToken0:m.swapInputIsToken0,minAmountOut:m.swapMinOutUsed}:null,I=h?{xV:m.xV,yV:m.yV,gammaTotalLTarget:m.gammaTotalL,gammaNewLTarget:m.gammaNewL,rL0Post:g,gammaTotalLPostRounded:v}:null,T=e.market.currentRatePerSecWad===null?null:Number(e.market.currentRatePerSecWad)/1e18*Bp*100;let L=null;h&&e.market.equityLWad>0n&&(L=(e.market.borrowedLWad+E)*_e/e.market.equityLWad);let x=null;if(h){const V=((be=e.vault)==null?void 0:be.owner)??e.owner,Q={vaultId:((fe=e.vault)==null?void 0:fe.vaultId)??0n,poolId:e.market.poolId,owner:V,x0:m.xV,y0:m.yV,rL0:g};x=Lp({market:e.market,vault:Q,slippageBps:e.slippageBps});}let k=null;if(h&&e.aprProjection&&T!==null){const V=(x==null?void 0:x.currentLtvFrac)??m.actualLtvPips/1e6;k=cs({equityLWad:e.market.equityLWad,borrowedLWad:e.market.borrowedLWad,deltaLWad:E,fullUtilRate:e.aprProjection.fullUtilRate,rateOracleAddress:e.aprProjection.rateOracleAddress,chainId:e.aprProjection.chainId,version:e.aprProjection.version,...(t?{deployment:t}:{}),currentAprPct:T,entryLtv:V,thetaL:e.market.hardLtvPips/1e6,...(e.aprProjection.rateModel?{rateModel:e.aprProjection.rateModel}:{})});}const _=x?Math.max(0,Math.min(1e6,Math.floor(x.currentLtvFrac*1e6))):null,D=100,P=x?Math.ceil(x.currentLtvFrac*1e6):null,W=h&&P!==null&&P>e.market.maxLtvPips,q=h&&!W;let R=null;if(q&&b.encodeInput){const V=P===null?b.encodeInput.maxLtvPips:Math.max(b.encodeInput.maxLtvPips,Math.min(e.market.maxLtvPips,P+D));R={...b.encodeInput,maxLtvPips:V,...(i?{permit:Ta(i)}:{})};}const C=[];if(e.execution&&q){const V=e.execution,Q=((Y=e.vault)==null?void 0:Y.owner)??e.owner;(Q===void 0||V.owner.toLowerCase()!==Q.toLowerCase())&&C.push({gate:"evidence-mismatch",detail:`evidence owner ${V.owner} is not the quote owner ${Q??"(none)"}`});const le=((ae=e.vault)==null?void 0:ae.vaultId)??null;if(V.vaultId!==le&&C.push({gate:"evidence-mismatch",detail:`evidence vaultId ${V.vaultId} does not match the quote vault ${le}`}),r?V.blockNumber!==r.blockNumber&&C.push({gate:"evidence-mismatch",detail:`evidence block ${V.blockNumber} is stale for frame block ${r.blockNumber}`}):C.push({gate:"evidence-mismatch",detail:"no read frame to bind the evidence to — quote assembled frame-less"}),V.vaultId!==null&&Q!==void 0){const H=V.ownerOnChain??ke;H.toLowerCase()!==Q.toLowerCase()&&C.push({gate:"ownership",vaultId:V.vaultId,ownerOnChain:H,expectedOwner:Q}),V.vaultPoolId===null?C.push({gate:"evidence-mismatch",detail:`evidence lacks the getVaultPoolId read for vault ${V.vaultId}`}):V.vaultPoolId.toLowerCase()!==e.market.poolId.toLowerCase()&&C.push({gate:"pool-identity",vaultPoolId:V.vaultPoolId,expectedPoolId:e.market.poolId});}if(V.routerApproved||C.push({gate:"router-authorization",owner:V.owner,router:V.router,vaultRegistry:V.vaultRegistry}),e.chainId===void 0?C.push({gate:"evidence-mismatch",detail:"no target chainId to bind the execution evidence to — pass QuoteBorrowInput.chainId"}):V.chainId!==e.chainId&&C.push({gate:"evidence-mismatch",detail:`evidence chainId ${V.chainId} is not the quote target chain ${e.chainId}`}),V.permit){const H=en({permit:V.permit,// No on-chain owner exists for the createVault path; validate
|
|
1581
|
+
// against the resolved owner the calldata is built for.
|
|
1582
|
+
ownerOnChain:Q??V.owner,router:V.router,requiredTokens:s,// Chain time when a frame exists; else the LOCAL clock as a
|
|
1583
|
+
// documented screening fallback — an expired permit must not ride
|
|
1584
|
+
// executable calldata just because no frame was supplied.
|
|
1585
|
+
blockTimestamp:Kr(r)});if(H)C.push(H);else{const Z=cr(V.permit,V.router,{blockNumber:V.blockNumber,chainId:e.chainId});Z&&C.push(Z);}}}let F=null,j=!1;if(q&&R)try{F=Rc(R);}catch{j=!0;}const K=q&&!j,$=K&&e.execution!==void 0&&C.length===0,S=$?F:null,re=k!=null&&k.oracleSupported?k.postBorrowRatePerSecWad:null,te={ltvHorizons:qp({currentLtvPips:K?_:null,hasDebt:K&&g!==null&&g>0n,maxLtvPips:e.market.maxLtvPips,hardLtvPips:e.market.hardLtvPips,rate:re!=null?{basis:"projected-post-action",ratePerSecWad:re}:e.market.currentRatePerSecWad!==null?{basis:"current-pre-action",ratePerSecWad:e.market.currentRatePerSecWad}:{basis:"unavailable",ratePerSecWad:null},frame:K?r:null}),postBorrowLtvPips:_,currentLtvFracPost:(x==null?void 0:x.currentLtvFrac)??null,bestLtvAfterRebalanceFrac:(x==null?void 0:x.bestLtvAfterRebalanceFrac)??null,daysToLiquidationAtCurrentApr:(x==null?void 0:x.daysToLiquidation)??null,postBorrowDaysToLiquidation:k&&k.oracleSupported?k.postBorrowDaysToLiq:null,preBorrowAprPct:T,postBorrowAprPct:k&&k.oracleSupported?k.postBorrowAprPct:null,postBorrowUtilPips:L,postBorrowRatePerSecWad:(k==null?void 0:k.postBorrowRatePerSecWad)??null,postBorrowRateBasis:k&&k.oracleSupported?"projected-oracle":null,postBorrowRateUnavailableReason:k&&!k.oracleSupported?k.unsupportedReason:e.aprProjection&&T===null?"oracle-not-canonical":null},ne=j?"builder-error":W?"above-capacity":b.infeasibleReason,ge={utilizationPre:b.utilizationPre,utilizationPost:b.utilizationPost,utilizationCap:b.utilizationCap,minDebtFloorRl:b.minDebtFloorRl,belowMinDebtFloor:b.belowMinDebtFloor,withinComfortCap:b.infeasibleReason!=="above-comfort-cap",aboveCapacity:ne==="above-capacity"},de={};b.minBorrowableY_w!==void 0&&(de.minBorrowableY_w=b.minBorrowableY_w),b.suggestedDepositIncreaseForComfortCap!==void 0&&(de.suggestedDepositIncreaseForComfortCap=b.suggestedDepositIncreaseForComfortCap),b.maxY_wUnderComfortCap!==void 0&&(de.maxY_wUnderComfortCap=b.maxY_wUnderComfortCap);let me=null;if(e.chart&&h){const V={depositT0:e.inputIsToken0?e.collateralIn:0n,depositT1:e.inputIsToken0?0n:e.collateralIn,loanT0:e.inputIsToken0?0n:e.borrowOut,loanT1:e.inputIsToken0?e.borrowOut:0n},Q=e.vault?{xV:e.vault.x0,yV:e.vault.y0,gammaTotalL:Ke(e.vault.rL0,e.market.borrowIndexWad)}:void 0;me=zd({market:{sqrtPriceX96:e.market.sqrtPriceX96,decimals0:e.market.decimals0,decimals1:e.market.decimals1},// Rounded γ ⇒ chart's α=1 point agrees with LTV display.
|
|
1586
|
+
postAction:{xV:m.xV,yV:m.yV,gammaTotalL:v},...(Q?{preAction:Q}:{}),blAction:V,...(e.chart?{options:e.chart}:{})});}const ye={feasible:K,executable:$,gateFailures:C,dispatch:b.dispatch,recipe:b,encodeInput:K?R:null,call:S,swap:K?A:null,finalVault:K?I:null,display:te,invariants:ge,hints:de,collateral:c,chart:K?me:null,frame:r,deadline:a,expiresAt:u};return ne!==void 0&&(ye.infeasibleReason=ne),b.diagnosticCertainty!==void 0&&(ye.diagnosticCertainty=b.diagnosticCertainty),ye;}function Vp(e,t){if(e===null)return{status:"not-required",reason:"fresh-vault"};const n=e.attachedPositionEvidence;if(!n)return{status:"unavailable",reason:"position-refs-unavailable",blockNumber:null,blockHash:null,refs:[]};const r=a=>({status:"unavailable",reason:a,blockNumber:n.blockNumber,blockHash:n.blockHash,refs:n.refs});return t?n.vaultId!==e.vaultId?r("position-refs-vault-mismatch"):n.blockNumber!==t.blockNumber||n.blockHash!==t.blockHash?r("position-refs-frame-mismatch"):n.refs.length>0?r("nft-aware-borrow-solver-unproven"):{status:"verified-empty-at-frame",blockNumber:n.blockNumber,blockHash:n.blockHash,refs:[]}:r("quote-frame-unavailable");}function ks(e){return{status:"re-quote-required",reason:"read-frame-not-canonical",call:null,currentHeadBlockNumber:e.frameBlockNumber,currentHeadBlockHash:e.observedBlockHash,evidence:null};}function It(e){return{status:e.status,executable:e.status==="verified-at-frame",call:e.call,execution:e};}function Va(e,t){return t===0n?{amount0:0n,amount1:0n}:yt(t,e.poolKey,Yn(e),!0);}var wn=50,Up=500;function Fn(e){return e===void 0?!0:Number.isInteger(e)&&e>=0&&e<=Up;}function Yi(e,t){if(e<=0n)return 1n;const r=(e*(10000n+BigInt(t))+9999n)/10000n;return r<1n?1n:r;}function Jn(e,t,n=wn){return e<=0n?null:{amount0:Yi(t.amount0,n),amount1:Yi(t.amount1,n)};}function Ua(e){const t=ur(e.vault,e.source),n=(r,a,i,o)=>{const s=a-r;if(s<=0n)return i;const l=o-i;return l<=0n?i:i+(s<l?s:l);};return{...e.source,fromWallet0:n(t.x,e.target.amount0,e.source.fromWallet0,e.walletBalance0),fromWallet1:n(t.y,e.target.amount1,e.source.fromWallet1,e.walletBalance1)};}function ta(e){const t=Va(e.market,e.requiredLiquidityL),n=e.synchronized??null;return{basis:"quote-frame",blockNumber:e.frame.blockNumber,blockTimestamp:e.frame.blockTimestamp,previewBorrowIndexWad:e.market.borrowIndexWad,principalDeltaRl:e.principalDeltaRl,requiredLiquidityL:e.requiredLiquidityL,synchronizedAppliedLiquidityL:(n==null?void 0:n.appliedLiquidityL)??null,synchronizedEngineTokenDebit:n===null?null:{basis:"router-minimum-error-probes",amount0:n.engineTokenDebit.amount0,amount1:n.engineTokenDebit.amount1},enforcedMaximumEngineTokenDebit:e.enforcedMaximumEngineTokenDebit??null,engineDebitToleranceBps:e.engineDebitToleranceBps,projectedEngineTokenRequirementAtFrame:t===null?null:{amount0:t.amount0,amount1:t.amount1,rounding:"engine-round-up"},fundingPlanAtFrame:e.source?{walletTopUp0:e.source.fromWallet0,walletTopUp1:e.source.fromWallet1,swapInput:e.source.swapInput,swapInputIsToken0:e.source.swapInputIsToken0,swapOutputMinimum:e.source.swapOutputMin}:null};}function na(e){return e instanceof Ya||e instanceof Ji||e instanceof to&&(e.code===Ya.code||no(e.data)&&e.data!=="0x");}function Wp(e){return na(e)?!0:e instanceof oa?e.walk(na)!==null:!1;}var $p=[...un,...$e];function Hp(e){const t=e instanceof oa?e.walk(na):e,n=t instanceof to&&no(t.data)?t.data:null;if(n===null||n==="0x")return{errorName:null,args:void 0};try{const r=$s({abi:$p,data:n});return{errorName:r.errorName,args:r.args};}catch{return{errorName:null,args:void 0};}}async function Wa(e,t){const n=t.fn??"callRouterAtFrame";ee(t.signal,n);try{await e.request({method:"eth_call",params:[{from:t.account,to:t.router,data:t.call.calldata,value:Us(t.call.value)},{blockHash:t.frame.blockHash,requireCanonical:!0}]});}catch(r){if(ee(t.signal,n),Wp(r))return{outcome:"reverted",...Hp(r)};let a;try{a=(await e.getBlock({blockNumber:t.frame.blockNumber})).hash;}catch{throw r;}if(ee(t.signal,n),a===t.frame.blockHash)throw r;return{outcome:"frame-not-canonical",observedBlockHash:a};}return ee(t.signal,n),{outcome:"passed"};}function dn(e,t,n){return{status:"re-quote-required",reason:e,call:null,currentHeadBlockNumber:t.number,currentHeadBlockHash:t.hash,evidence:n};}function Ds(e,t,n){return{kind:"router-call",scope:"complete-call-at-frame",account:e.account,router:e.router,calldataHash:xt(t.calldata),value:t.value,blockNumber:e.frame.blockNumber,blockHash:e.frame.blockHash,blockTimestamp:e.frame.blockTimestamp,headBefore:n.number,headBeforeHash:n.hash};}function Ns(e){return e===void 0||typeof e=="bigint"&&e>=0n&&e<=60n;}function $a(e,t,n){const r=e.executionFrameMaxAgeSeconds??0n;return r===0n?t.number===e.frame.blockNumber&&t.hash===e.frame.blockHash?null:dn("quote-frame-is-not-head",t,n):t.number<e.frame.blockNumber||t.timestamp<e.frame.blockTimestamp?dn("quote-frame-is-not-head",t,n):t.timestamp-e.frame.blockTimestamp>r||e.validUntil===void 0||t.timestamp>=e.validUntil?dn("quote-frame-expired",t,n):null;}async function Ls(e,t,n,r){const a=$a(t,n,r);if(a)return a.reason==="quote-frame-is-not-head"?dn("head-advanced-during-preflight",n,r):a;if((t.executionFrameMaxAgeSeconds??0n)>0n){const i=await e.getBlock({blockNumber:t.frame.blockNumber});if(ee(t.signal,t.fn),i.hash!==t.frame.blockHash)return Ha(r,i.hash);}return null;}function Ha(e,t){return dn("head-advanced-during-preflight",{number:e.blockNumber,hash:t},{...e,outcome:"indeterminate",headAfter:e.blockNumber,headAfterHash:t});}async function Ps(e,t,n,r,a,i){const o=await e.getBlock();ee(r,a);const s={...n,outcome:"reverted",headAfter:o.number,headAfterHash:o.hash},l=await Ls(e,{frame:t,signal:r,fn:a,...i},o,s);return l||{status:"rejected-at-frame",reason:"execution-reverted",call:null,evidence:s};}async function za(e,t){ee(t.signal,t.fn);const n=await e.getBlock();ee(t.signal,t.fn);const r=Ds(t,t.call,n),a=$a(t,n,{...r,outcome:"not-run",headAfter:null,headAfterHash:null});if(a)return a;const i=await Wa(e,{account:t.account,router:t.router,call:t.call,frame:t.frame});if(ee(t.signal,t.fn),i.outcome==="frame-not-canonical")return Ha(r,i.observedBlockHash);if(i.outcome==="reverted")return Ps(e,t.frame,r,t.signal,t.fn,t);const o=await e.getBlock();ee(t.signal,t.fn);const s={...r,outcome:"passed",headAfter:o.number,headAfterHash:o.hash},l=await Ls(e,t,o,s);return l||{status:"verified-at-frame",call:t.call,evidence:s};}var pn=1n,_s=(1n<<135n)-1n,Mr={engineTokenDebit0:{maxEngineTokenDebit0:pn,maxEngineTokenDebit1:0n,minLiquidityDelta:0n},engineTokenDebit1:{maxEngineTokenDebit0:0n,maxEngineTokenDebit1:pn,minLiquidityDelta:0n},requiredLiquidity:{maxEngineTokenDebit0:0n,maxEngineTokenDebit1:0n,minLiquidityDelta:_s}},Qi=["InsufficientIdleAmount0","InsufficientIdleAmount1"];async function zp(e,t){ee(t.signal,t.fn);const n=await e.getBlock();ee(t.signal,t.fn);const r=p=>Ds(t,p,n),a=$a(t,n,{...r(t.calls.engineTokenDebit0),outcome:"not-run",headAfter:null,headAfterHash:null});if(a)return a;const i=p=>Ps(e,t.frame,r(p),t.signal,t.fn,t),o=async p=>{ee(t.signal,t.fn);const y=await Wa(e,{account:t.account,router:t.router,call:p,frame:t.frame});return ee(t.signal,t.fn),y.outcome==="frame-not-canonical"?{kind:"assessment",assessment:Ha(r(p),y.observedBlockHash)}:y.outcome==="passed"?{kind:"passed"}:{kind:"reverted",revert:y};},s=async p=>{const y=p===0?t.calls.engineTokenDebit0:t.calls.engineTokenDebit1,b=p===0?t.previewEngineTokenDebit.amount0:t.previewEngineTokenDebit.amount1,m=await o(y);if(m.kind==="assessment")return m.assessment;if(m.kind==="passed")return b>pn?{status:"unavailable",detail:`the amount${p} Engine debit guard did not trip against a projected ${b} wei requirement`}:pn;const{errorName:h,args:g}=m.revert;if(h!==Qi[p])return i(y);const[v,w]=g??[];return typeof v!="bigint"||typeof w!="bigint"||w!==-pn||v>=w?{status:"unavailable",detail:`the ${Qi[p]} probe payload did not carry the expected sentinel`}:-v;},l=await s(0);if(typeof l!="bigint")return l;const u=await s(1);if(typeof u!="bigint")return u;const d=await o(t.calls.requiredLiquidity);if(d.kind==="assessment")return d.assessment;let c=null;if(d.kind==="reverted"){const{errorName:p,args:y}=d.revert;if(p!=="InsufficientLiquidityDelta")return i(t.calls.requiredLiquidity);const[b,m]=y??[];typeof b=="bigint"&&b>=0n&&m===_s&&(c=b);}return{status:"recovered",funding:{appliedLiquidityL:c,engineTokenDebit:{amount0:l,amount1:u}}};}var Ga=class extends Error{constructor(t,n){super(n instanceof Error?n.message:t);oe(this,"original");this.name="LifecycleFundingProbeBuilderError",this.original=n;}};function Cs(e,t){return n=>{let r;try{r={engineTokenDebit0:t.encode(n,Mr.engineTokenDebit0),engineTokenDebit1:t.encode(n,Mr.engineTokenDebit1),requiredLiquidity:t.encode(n,Mr.requiredLiquidity)};}catch(a){throw new Ga(t.builderFallbackMessage,a);}return zp(e,{account:t.account,router:t.router,frame:t.frame,executionFrameMaxAgeSeconds:t.executionFrameMaxAgeSeconds,validUntil:t.validUntil,calls:r,previewEngineTokenDebit:t.previewEngineTokenDebit,...(t.signal?{signal:t.signal}:{}),fn:t.fn});};}function Ms(e){return`Could not stabilize the synchronized Engine debit at the quote frame: ${e}.`;}function Rs(e,t){return{amount0:e.amount0,amount1:e.amount1,enforcement:"router-min-idle",basis:t===null?"frame-preview":"router-synchronized-probe"};}var Rr=3;async function Ss(e){let t=e.initialSource;for(let n=1;n<=Rr;n+=1){const r=await e.probe(t);if(r.status==="unavailable")return{...r,source:t,passes:n};if(r.status!=="recovered")return{status:"assessment",assessment:r,source:t,passes:n};const a=Jn(e.requiredLiquidityL,r.funding.engineTokenDebit,e.engineDebitToleranceBps);if(a===null)return{status:"unavailable",detail:"the synchronized debit could not activate Router token-debit guards",source:t,passes:n};const i=Ua({vault:e.vault,source:t,target:a,walletBalance0:e.walletBalance0,walletBalance1:e.walletBalance1});if(i.fromWallet0===t.fromWallet0&&i.fromWallet1===t.fromWallet1)return{status:"stable",source:t,funding:r.funding,engineDebitLimit:a,passes:n};t=i;}return{status:"unavailable",detail:`the synchronized funding source did not stabilize within ${Rr} probe passes`,source:t,passes:Rr};}var Gp=["funding-sized-at-frame-price","swap-output-at-quoted-minimum","partial-post-ltv-uses-version-aware-sdk-contract-parity","delayed-success-and-index-bounds-unproven","engine-token-debit-capped-by-router-min-idle","wallet-legs-top-up-toward-tolerance-maximum-subject-to-balance","unconsumed-funding-remains-vault-idle-collateral"],Xi="Repay funding legs exceed the int128 action encoding — split into multiple partial repays.",jp=new AbortController().signal;async function Kp(e,t){var ae,V,Q,le;const{addresses:n,frame:r,market:a,vault:i,ownerOnChain:o,routerApproved:s,nonCanonicalOracle:l,frameReorg:u}=await Oa(e,{chainId:t.chainId,version:t.version,deployment:t.deployment,poolId:t.poolId,vaultId:t.vaultId,owner:t.owner,rateModel:t.rateModel,blockNumber:t.blockNumber,signal:t.signal,fn:"quoteRepay"}),d=t.deadline,{expiresAt:c,ttlInvalid:p,warnings:y}=Is({deadline:d,frame:r,quoteTtlSeconds:t.quoteTtlSeconds,permitBatch:(ae=t.permit)==null?void 0:ae.permitBatch,fn:"quoteRepay"}),b=Fn(t.engineDebitToleranceBps)?t.engineDebitToleranceBps??wn:wn,m=[...qa(l),...y];Fn(t.engineDebitToleranceBps)||m.push("quoteRepay requires an integer engineDebitToleranceBps between 0 and 500.");const h={kind:"repay",market:a,frame:r,deadline:d,...Zn({requestedDeadline:d,validUntil:c,frame:r,maximumEngineTokenDebit:null,executionFrameMaxAgeSeconds:t.executionFrameMaxAgeSeconds}),warnings:m,assumptions:Gp},g={feasible:!1,gateFailures:[],vault:null,principalDeltaRl:null,fullRepayIntent:!1,fullRepay:!1,requiredL:null,plan:null,fromWallet0:0n,fromWallet1:0n,approvals:[],swap:null,repayEffectBound:null,collateral:null,requestedPrincipalPostProjection:null,post:null,encodeInput:null,fundingAtFrame:null},v=H=>({...h,...It(ks(H)),...g});if(u)return v(u);if(i===null||o===null)return{...h,...It({status:"rejected",reason:"quote-infeasible",call:null,evidence:null}),...g,infeasibleReason:"vault-not-found",collateral:{status:"not-required",reason:"vault-not-found"}};const w=Fa({vaultId:t.vaultId,ownerOnChain:o,expectedOwner:t.owner,vaultPoolId:i.poolId,expectedPoolId:t.poolId,deadline:c,blockTimestamp:r.blockTimestamp,routerApproved:s,router:n.aegisRouterV1,vaultRegistry:n.vaultRegistry}),E=t.repayRl==="full"?i.rL0:t.repayRl,A=E<0n?null:Ke(E,a.borrowIndexWad),I=i.rL0>0n&&E===i.rL0,T=A===null?null:{basis:"verified-contract-source",requestedPrincipalRl:E,exactAppliedPrincipalRl:null,minimumAppliedPrincipalRl:0n,maximumAppliedPrincipalRl:E,guarantee:"at-most-requested"};let L=E===i.rL0?{status:"not-required",reason:"zero-residual-debt"}:null;const x=(H,Z,z=(Z==null?void 0:Z.source)??null)=>{const O=(z==null?void 0:z.fromWallet0)??0n,Te=(z==null?void 0:z.fromWallet1)??0n;return{...h,...It({status:"rejected",reason:"quote-infeasible",call:null,evidence:null}),feasible:!1,infeasibleReason:H,gateFailures:w,vault:i,principalDeltaRl:E,fullRepayIntent:I,fullRepay:I,requiredL:A,plan:Z,fromWallet0:O,fromWallet1:Te,approvals:Jr(a.poolKey,O,Te,n.aegisRouterV1),swap:null,repayEffectBound:T,collateral:L,requestedPrincipalPostProjection:null,post:null,encodeInput:null,fundingAtFrame:A===null?null:ta({frame:r,market:a,principalDeltaRl:E,requiredLiquidityL:A,source:z,engineDebitToleranceBps:b})};};if(p||!Ns(t.executionFrameMaxAgeSeconds)||!Fn(t.engineDebitToleranceBps)||t.slippageBps!==void 0&&(!Number.isInteger(t.slippageBps)||t.slippageBps<0||t.slippageBps>=1e4)||t.maxLtvPips!==void 0&&(!Number.isInteger(t.maxLtvPips)||t.maxLtvPips<=0||t.maxLtvPips>1e6)||A===null)return x("invalid-input",null);if(E===0n)return x("nothing-to-repay",null);if(E<=i.rL0&&E>zn)return m.push("Repay principal exceeds the int128 action encoding — split into multiple partial repays."),x("requires-split",null);const{walletBalance0:_,walletBalance1:D}=await As(e,a.poolKey,t.owner,r.blockNumber,t.walletBalance0,t.walletBalance1);ee(t.signal,"quoteRepay");const P=await vn(e,r,"quoteRepay");if(P)return v(P);ee(t.signal,"quoteRepay");const W=Math.min(t.maxLtvPips??a.maxLtvPips,a.maxLtvPips),q=W===a.maxLtvPips?a:{...a,maxLtvPips:W},R=Bn({market:q,vault:i,deltaRl:E,walletBalance0:_,walletBalance1:D});if(R.overRepayRequested)return m.push(R.fundedByLabel),x("over-repay",R);if(R.forbiddenZone)return m.push(R.fundedByLabel),x("below-min-debt-floor",R);let C=null;if(!I){let H;try{H=await Xo(e,{chainId:t.chainId,version:t.version,deployment:t.deployment,vaultId:t.vaultId,expectedPoolId:i.poolId,frame:r});}catch(z){if(z instanceof kn)return v(z);throw z;}ee(t.signal,"quoteRepay");const Z=vs(H,i);if(!Z.ok)return L=Z.assessment,m.push(Z.assessment.reason==="vault-state-mismatch"?"Partial-repay collateral reads do not match the lifecycle vault snapshot.":`Partial-repay collateral is unavailable: ${Z.assessment.detail}.`),x("collateral-unavailable",null);C=Z.snapshot;}let F=C===null?R:Bn({market:q,vault:i,deltaRl:E,walletBalance0:_,walletBalance1:D,collateral:{version:t.version,positions:C.positions}});if(m.push(F.fundedByLabel),F.residualLtvFails)return x("residual-ltv",F);if(!F.feasible||F.source===null)return x("insufficient-funding",F);let j=F.source;const K=Va(a,A);if(K===null)return m.push("Could not derive Engine token-debit guards at the quote frame; refusing unbounded calldata."),x("engine-debit-bound-unavailable",F);const $=Jn(A,K,b);if($===null)return m.push("Could not activate Engine token-debit guards for this repayment."),x("engine-debit-bound-unavailable",F);let S=j;if(j.source==="idle-swap"){if(!t.fetchQuote)return m.push("Idle-swap repay needs a swap quote; no fetchQuote provider was supplied."),x("quote-unavailable",F);for(let H=0;H<3;H++){const Z=j.swapInputIsToken0?i.y0:i.x0,z=j.swapInputIsToken0?$.amount1:$.amount0,O=z>Z?z-Z:0n,Te=j.swapOutputMin>O?j.swapOutputMin:O,De=await t.fetchQuote({amountIn:j.swapInput,inputIsToken0:j.swapInputIsToken0,blockNumber:r.blockNumber,purpose:"repay-idle-swap",signal:t.signal??jp});if(ee(t.signal,"quoteRepay"),De.minAmountOut>=Te){S={...j,swapOutputMin:De.minAmountOut,swapRoute:De.route,swapSlippageBps:t.slippageBps??50};break;}const ue=()=>(m.push(`Swap quote minAmountOut (${De.minAmountOut}) is below the required rebalance output (${Te}).`),x("swap-output-insufficient",F));if(H===2||De.minAmountOut<=0n)return ue();const J=(j.swapInput*Te+De.minAmountOut-1n)/De.minAmountOut,se=j.swapInputIsToken0?i.x0:i.y0,Se=j.swapInputIsToken0?$.amount0:$.amount1,tn=(J*10010n+9999n)/10000n,qt=se-Se,Ka=tn<qt?tn:qt;if(Ka<=j.swapInput)return ue();const nn=Bn({market:q,vault:i,deltaRl:E,walletBalance0:_,walletBalance1:D,idleSwapInput:Ka,...(C?{collateral:{version:t.version,positions:C.positions}}:{})});if(!nn.feasible||((V=nn.source)==null?void 0:V.source)!=="idle-swap"||nn.source.swapInputIsToken0!==j.swapInputIsToken0)return ue();F=nn,j=nn.source;}}$!==null&&(S=Ua({vault:i,source:S,target:$,walletBalance0:_,walletBalance1:D}));const re=(H,Z,z)=>({market:a,vault:i,principalDeltaRl:E,source:H,maxLtvPips:W,maxEngineTokenDebit0:z.maxEngineTokenDebit0,maxEngineTokenDebit1:z.maxEngineTokenDebit1,minLiquidityDelta:z.minLiquidityDelta,deadline:Z,...(t.permit?{permit:t.permit}:{})}),te=(H,Z,z,O)=>(m.push(O instanceof Error?O.message:"buildRepayRecipe failed."),{...x("builder-error",F,Z),validUntil:z,expiresAt:z,validity:{...h.validity,validUntil:z,maximumEngineTokenDebit:null},encodeInput:H});let ne=null,ge=null,de=null;if(w.length===0){let H=S;const Z=Cs(e,{account:t.owner,router:n.aegisRouterV1,frame:r,executionFrameMaxAgeSeconds:t.executionFrameMaxAgeSeconds,validUntil:c,previewEngineTokenDebit:K,...(t.signal?{signal:t.signal}:{}),fn:"quoteRepay",builderFallbackMessage:"buildRepayRecipe failed.",encode:(z,O)=>_i(re(z,c,O))});try{const z=await Ss({initialSource:S,vault:i,requiredLiquidityL:A,engineDebitToleranceBps:b,walletBalance0:_,walletBalance1:D,probe:O=>(H=O,Z(O))});if(S=z.source,z.status==="unavailable")return m.push(Ms(z.detail)),x("engine-debit-bound-unavailable",F,S);z.status==="assessment"?ge=z.assessment:(ne=z.funding,de=z.engineDebitLimit);}catch(z){if(!(z instanceof Ga))throw z;if(H.fromWallet0>ce||H.fromWallet1>ce||H.swapInput>ce||H.swapOutputMin>ce)return m.push(Xi),x("requires-split",F,H);const O=[{token:a.poolKey.currency0,amount:H.fromWallet0},{token:a.poolKey.currency1,amount:H.fromWallet1}],Te=Rt(c,(Q=t.permit)==null?void 0:Q.permitBatch,O);if(t.permit){const J=en({permit:t.permit,ownerOnChain:o,router:n.aegisRouterV1,requiredTokens:O,blockTimestamp:r.blockTimestamp});J&&w.push(J);}const De=$??{amount0:0n,amount1:0n},ue=re(H,Te,{maxEngineTokenDebit0:De.amount0,maxEngineTokenDebit1:De.amount1,minLiquidityDelta:0n});return te(ue,H,Te,z.original);}}const me=de??Jn(A,K,b);if(me===null)return m.push("Could not activate Engine token-debit guards for this repayment."),x("engine-debit-bound-unavailable",F,S);if(me.amount0>ct||me.amount1>ct)return m.push("Engine token-debit guards exceed the negated int128 encoding — split the repayment."),x("requires-split",F,S);if(S.fromWallet0>ce||S.fromWallet1>ce||S.swapInput>ce||S.swapOutputMin>ce)return m.push(Xi),x("requires-split",F,S);const ye=Rs(me,ne),Ae=Yp(a,i,S,E,A,r,C,(ne==null?void 0:ne.engineTokenDebit)??null);if(Ae===null)return L=xp("vault-state-mismatch",(C==null?void 0:C.refs)??[],"could not project the post-repay idle state from the verified quote inputs"),m.push("Could not project the partial-repay collateral floor."),x("collateral-unavailable",F,S);if(L=Ae.collateral,L.status==="verified-at-frame"&&!Sa({floorL:L.floorLPost,rL:i.rL0-E,borrowIndexWad:a.borrowIndexWad,maxLtvPips:W}))return x("residual-ltv",F,S);const pe=[{token:a.poolKey.currency0,amount:S.fromWallet0},{token:a.poolKey.currency1,amount:S.fromWallet1}],he=Rt(c,(le=t.permit)==null?void 0:le.permitBatch,pe);if(t.permit){const H=await Es(e,{permit:t.permit,ownerOnChain:o,router:n.aegisRouterV1,requiredTokens:pe,blockTimestamp:r.blockTimestamp,chainId:t.chainId,permit2Address:n.permit2,blockNumber:r.blockNumber});H&&w.push(H),ee(t.signal,"quoteRepay");const Z=await vn(e,r,"quoteRepay");if(Z)return v(Z);ee(t.signal,"quoteRepay");}const be=re(S,he,{maxEngineTokenDebit0:me.amount0,maxEngineTokenDebit1:me.amount1,minLiquidityDelta:0n});let fe;try{fe=_i(be);}catch(H){return te(be,S,he,H);}const Y=w.length>0?{status:"blocked",reason:"execution-gate",call:null,evidence:null}:ge??(await za(e,{account:t.owner,router:n.aegisRouterV1,call:fe,frame:r,executionFrameMaxAgeSeconds:t.executionFrameMaxAgeSeconds,validUntil:he,...(t.signal?{signal:t.signal}:{}),fn:"quoteRepay"}));return m.push(...Ba(Y,r,"repay")),{...h,...It(Y),// Tightened past the base clamp now that the wallet legs — and their
|
|
1587
|
+
// per-token allowance expirations — are sized.
|
|
1588
|
+
...Zn({requestedDeadline:d,validUntil:he,frame:r,maximumEngineTokenDebit:ye,executionFrameMaxAgeSeconds:t.executionFrameMaxAgeSeconds}),feasible:!0,gateFailures:w,vault:i,principalDeltaRl:E,fullRepayIntent:I,fullRepay:I,requiredL:A,plan:F,fromWallet0:S.fromWallet0,fromWallet1:S.fromWallet1,approvals:Jr(a.poolKey,S.fromWallet0,S.fromWallet1,n.aegisRouterV1),swap:{needed:S.source==="idle-swap",amountIn:S.swapInput,isToken0:S.swapInputIsToken0,minAmountOut:S.swapOutputMin},repayEffectBound:T,collateral:L,requestedPrincipalPostProjection:Ae.post,post:null,encodeInput:be,fundingAtFrame:ta({frame:r,market:a,principalDeltaRl:E,requiredLiquidityL:A,source:S,engineDebitToleranceBps:b,synchronized:ne,enforcedMaximumEngineTokenDebit:ye})};}function Yp(e,t,n,r,a,i,o,s){const l=ys(e,t,n,a,s);if(l===null)return null;const u=t.rL0-r;if(u===0n)return{collateral:{status:"not-required",reason:"zero-residual-debt"},post:{rL0Post:u,debtLPost:0n,idle0Post:l.idle0,idle1Post:l.idle1,collateralFloorLPost:null,collateralBasis:"not-required-zero-debt",ltvPipsPost:null}};if(o===null)return null;const d=ws(o,i,{idle0Post:l.idle0,idle1Post:l.idle1,rLPost:u,borrowIndexWad:e.borrowIndexWad});return{collateral:d,post:{rL0Post:u,debtLPost:Ke(u,e.borrowIndexWad),idle0Post:l.idle0,idle1Post:l.idle1,collateralFloorLPost:d.floorLPost,collateralBasis:d.basis,ltvPipsPost:d.ltvPipsPost}};}var Qp=[],Xp=["slippage: n/a - exact idle amounts, no conversion","post-LTV basis: version-aware SDK floor with same-frame contract parity","executable basis: complete Router call accepted at the quote frame - not a later-block guarantee"];function Zp(e,t){return{gate:"router-preflight",reason:e.reason,router:t,blockNumber:e.evidence.blockNumber,blockHash:e.evidence.blockHash,calldataHash:e.evidence.calldataHash};}async function Jp(e,t){const{addresses:n,frame:r,market:a,vault:i,ownerOnChain:o,routerApproved:s,nonCanonicalOracle:l,frameReorg:u}=await Oa(e,{chainId:t.chainId,version:t.version,deployment:t.deployment,poolId:t.poolId,vaultId:t.vaultId,owner:t.owner,rateModel:t.rateModel,blockNumber:t.blockNumber,signal:t.signal,fn:"quoteIdleWithdraw"});if(u)throw u;const d=qa(l),{expiresAt:c,ttlInvalid:p}=dr({deadline:t.deadline,frame:r,quoteTtlSeconds:t.quoteTtlSeconds}),y={kind:"idle-withdraw",market:a,approvals:Qp,frame:r,deadline:t.deadline,expiresAt:c,warnings:d,assumptions:Xp};if(i===null||o===null)return{...y,feasible:!1,executable:!1,infeasibleReason:"vault-not-found",gateFailures:[],vault:null,withdraw0:null,withdraw1:null,post:null,collateral:{status:"not-required",reason:"vault-not-found"},encodeInput:null,call:null};const b=Fa({vaultId:t.vaultId,ownerOnChain:o,expectedOwner:t.owner,vaultPoolId:i.poolId,expectedPoolId:t.poolId,deadline:t.deadline,blockTimestamp:r.blockTimestamp,routerApproved:s,router:n.aegisRouterV1,vaultRegistry:n.vaultRegistry}),{amount0:m,amount1:h}=t.withdraw==="all"?{amount0:i.x0,amount1:i.y0}:t.withdraw;let g=null;const v=W=>({...y,feasible:!1,executable:!1,infeasibleReason:W,gateFailures:b,vault:i,withdraw0:m,withdraw1:h,post:null,collateral:g,encodeInput:null,call:null}),w=t.maxLtvPips===void 0||Number.isInteger(t.maxLtvPips)&&t.maxLtvPips>0&&t.maxLtvPips<=1e6,E=t.withdraw==="all"||t.withdraw.amount0>=0n&&t.withdraw.amount1>=0n;if(!w||!E||p)return v("invalid-input");if(m===0n&&h===0n)return v("nothing-to-withdraw");if(m>i.x0||h>i.y0)return v("exceeds-idle");if(m>ce||h>ce)return d.push("Withdraw amount exceeds the int128 action encoding — split into multiple withdrawals."),v("requires-split");const A=Math.min(t.maxLtvPips??a.maxLtvPips,a.maxLtvPips),I=i.x0-m,T=i.y0-h;if(i.rL0===0n)g={status:"not-required",reason:"zero-residual-debt"};else{const W=await Xo(e,{chainId:t.chainId,version:t.version,deployment:t.deployment,vaultId:t.vaultId,expectedPoolId:i.poolId,frame:r});ee(t.signal,"quoteIdleWithdraw");const q=vs(W,i);if(!q.ok)return g=q.assessment,v("collateral-unavailable");g=ws(q.snapshot,r,{idle0Post:I,idle1Post:T,rLPost:i.rL0,borrowIndexWad:a.borrowIndexWad});}if(!(g.status==="not-required"||g.status==="verified-at-frame"&&Sa({floorL:g.floorLPost,rL:i.rL0,borrowIndexWad:a.borrowIndexWad,maxLtvPips:A})))return v("residual-ltv");const x={market:a,vault:i,deposit:{amount0:0n,amount1:0n},withdraw:{amount0:m,amount1:h},maxLtvPips:A,deadline:t.deadline},k=g.status==="verified-at-frame"?g:null,_={rL0Post:i.rL0,debtLPost:Ke(i.rL0,a.borrowIndexWad),idle0Post:I,idle1Post:T,collateralFloorLPost:(k==null?void 0:k.floorLPost)??null,collateralBasis:k?k.basis:"not-required-zero-debt",ltvPipsPost:(k==null?void 0:k.ltvPipsPost)??null};let D;try{D=Sc(x);}catch(W){return d.push(W instanceof Error?W.message:"buildIdleWithdrawRecipe failed."),{...v("builder-error"),encodeInput:x};}if(b.length===0){const W=await za(e,{account:t.owner,router:n.aegisRouterV1,call:D,frame:r,...(t.signal?{signal:t.signal}:{}),fn:"quoteIdleWithdraw"});W.status!=="verified-at-frame"&&(b.push(Zp(W,n.aegisRouterV1)),d.push(...Ba(W,r,"idle-withdraw")));}const P=b.length===0;return{...y,feasible:!0,executable:P,gateFailures:b,vault:i,withdraw0:m,withdraw1:h,post:_,collateral:g,encodeInput:x,call:P?D:null};}var e0=["Close outputs are price-dependent and unenforced on-chain: the close sequence settles via closeAE/takeAE open deltas, so no encodable min-out slot exists in the calldata.","Protection is the transaction deadline plus re-quoting — re-quote near submission for a fresh frame instead of relying on an on-chain minimum.","Borrow-index and token-funding values are frame-only; no delayed token-funding bound is proven.","Wallet legs top up toward the tolerance-inflated maximum Engine debit, subject to available balance; the close drains whatever the Engine does not consume back to the owner.","The current close sequence routes detached NFTs to recipient but settles drained tokens to the transaction sender."],Sr="Close funding legs exceed the int128 action encoding — repay in parts before closing.";async function t0(e,t){var O,Te,De;const{addresses:n,frame:r,market:a,vault:i,ownerOnChain:o,routerApproved:s,nonCanonicalOracle:l,frameReorg:u}=await Oa(e,{chainId:t.chainId,version:t.version,deployment:t.deployment,poolId:t.poolId,vaultId:t.vaultId,owner:t.owner,rateModel:t.rateModel,blockNumber:t.blockNumber,signal:t.signal,fn:"quoteCloseVault"}),d=t.recipient??t.owner,{expiresAt:c,ttlInvalid:p,warnings:y}=Is({deadline:t.deadline,frame:r,quoteTtlSeconds:t.quoteTtlSeconds,permitBatch:(O=t.permit)==null?void 0:O.permitBatch,fn:"quoteCloseVault"}),b=Fn(t.engineDebitToleranceBps),m=p||!b||!Ns(t.executionFrameMaxAgeSeconds),h=b?t.engineDebitToleranceBps??wn:wn,g=[...qa(l),...y];b||g.push("quoteCloseVault requires an integer engineDebitToleranceBps between 0 and 500.");const v={kind:"close-vault",market:a,minimum:null,frame:r,deadline:t.deadline,...Zn({requestedDeadline:t.deadline,validUntil:c,frame:r,maximumEngineTokenDebit:null,executionFrameMaxAgeSeconds:t.executionFrameMaxAgeSeconds}),warnings:g,assumptions:e0},w={feasible:!1,gateFailures:[],vault:null,principalDeltaRl:null,requiredL:null,plan:null,fromWallet0:0n,fromWallet1:0n,approvals:[],nftsToDetach:[],nftRecipient:d,tokenRecipient:t.owner,expected:null,post:null,encodeInput:null,fundingAtFrame:null,closeOutcomeAtFrame:null},E=ue=>({...v,...It(ks(ue)),...w});if(u)return E(u);if(i===null||o===null)return{...v,...It({status:"rejected",reason:"quote-infeasible",call:null,evidence:null}),...w,infeasibleReason:"vault-not-found"};const A=i.rL0,I=Ke(A,a.borrowIndexWad),T=Va(a,I),L=T===null?null:Jn(I,T,h),[x,k]=await Promise.all([i.attachedPositionEvidence!==void 0?Promise.resolve([...i.attachedPositionEvidence.refs]):Da(e,n.aegisStateView,t.vaultId,r.blockNumber),A>0n?As(e,a.poolKey,t.owner,r.blockNumber,t.walletBalance0,t.walletBalance1):Promise.resolve(null)]);ee(t.signal,"quoteCloseVault");const _=await vn(e,r,"quoteCloseVault");if(_)return E(_);ee(t.signal,"quoteCloseVault");let D=null,P=null;const W=(k==null?void 0:k.walletBalance0)??0n,q=(k==null?void 0:k.walletBalance1)??0n;let R=!0,C;m?(R=!1,C="invalid-input"):t.recipient!==void 0&&t.recipient.toLowerCase()!==t.owner.toLowerCase()?(R=!1,C="unsupported-token-recipient",g.push("The current close sequence settles drained tokens to the transaction sender; use the vault owner as recipient.")):A>zn&&(R=!1,C="requires-split",g.push("Vault principal exceeds the int128 action encoding — repay in parts before closing.")),R&&k!==null&&(D=Bn({market:a,vault:i,deltaRl:A,walletBalance0:W,walletBalance1:q}),P=D.source,P!==null&&L!==null&&(P=Ua({vault:i,source:P,target:L,walletBalance0:W,walletBalance1:q})),D.feasible?((Te=D.source)==null?void 0:Te.source)==="idle-swap"&&(R=!1,C="requires-rebalance",g.push("Funding this close needs an idle rebalance swap, which the close recipe excludes — run quoteRepay first to rebalance, then re-quote the close.")):(R=!1,C="insufficient-funding"));let F=(P==null?void 0:P.fromWallet0)??0n,j=(P==null?void 0:P.fromWallet1)??0n;R&&(F>ce||j>ce)&&(R=!1,C="requires-split",g.push(Sr)),R&&T===null?(R=!1,C="engine-debit-bound-unavailable",g.push("Could not derive Engine token-debit guards at the quote frame; refusing unbounded calldata.")):R&&L!==null&&(L.amount0>ct||L.amount1>ct)&&(R=!1,C="requires-split",g.push("Engine token-debit guards exceed the negated int128 encoding — repay in parts first."));const K={source:"idle",fromIdle0:0n,fromIdle1:0n,fromWallet0:0n,fromWallet1:0n,swapInput:0n,swapInputIsToken0:!0,swapOutputMin:0n},$=(ue,J,se)=>({vaultId:t.vaultId,deadline:J,currency0:a.poolKey.currency0,currency1:a.poolKey.currency1,recipient:d,currentDebt:A,maxEngineTokenDebit0:se.maxEngineTokenDebit0,maxEngineTokenDebit1:se.maxEngineTokenDebit1,minLiquidityDelta:se.minLiquidityDelta,attachedNfts:x,accrualPoke:{poolId:t.poolId,recipient:t.owner},...(ue.fromWallet0>0n?{fromWallet0:ue.fromWallet0}:{}),...(ue.fromWallet1>0n?{fromWallet1:ue.fromWallet1}:{}),...(t.permit?{permit:t.permit}:{})});let S=!1;if(R)try{Nr($(P??K,c,{maxEngineTokenDebit0:(L==null?void 0:L.amount0)??0n,maxEngineTokenDebit1:(L==null?void 0:L.amount1)??0n,minLiquidityDelta:0n}));}catch(ue){g.push(ue instanceof Error?ue.message:"buildCloseVault failed."),S=!0;}const re=R&&!S,te=Fa({vaultId:t.vaultId,ownerOnChain:o,expectedOwner:t.owner,vaultPoolId:i.poolId,expectedPoolId:t.poolId,deadline:c,blockTimestamp:r.blockTimestamp,routerApproved:s,router:n.aegisRouterV1,vaultRegistry:n.vaultRegistry});let ne=null,ge=null,de=!1,me=null;if(re&&te.length===0&&A>0n&&P!==null&&T!==null){let ue=P;const J=Cs(e,{account:t.owner,router:n.aegisRouterV1,frame:r,executionFrameMaxAgeSeconds:t.executionFrameMaxAgeSeconds,validUntil:c,previewEngineTokenDebit:T,...(t.signal?{signal:t.signal}:{}),fn:"quoteCloseVault",builderFallbackMessage:"buildCloseVault failed.",encode:(se,Se)=>Nr($(se,c,Se))});try{const se=await Ss({initialSource:P,vault:i,requiredLiquidityL:I,engineDebitToleranceBps:h,walletBalance0:W,walletBalance1:q,probe:Se=>(ue=Se,J(Se))});P=se.source,se.status==="unavailable"?(de=!0,g.push(Ms(se.detail))):se.status==="assessment"?ge=se.assessment:(ne=se.funding,me=se.engineDebitLimit);}catch(se){if(!(se instanceof Ga))throw se;P=ue,ue.fromWallet0>ce||ue.fromWallet1>ce?(R=!1,C="requires-split",g.push(Sr)):(S=!0,g.push(se.original instanceof Error?se.original.message:"buildCloseVault failed."));}}F=(P==null?void 0:P.fromWallet0)??0n,j=(P==null?void 0:P.fromWallet1)??0n,R&&(F>ce||j>ce)&&(R=!1,C="requires-split",g.push(Sr));const ye=A===0n?null:me??L;R&&ye!==null&&(ye.amount0>ct||ye.amount1>ct)&&(R=!1,C="requires-split",g.push("Engine token-debit guards exceed the negated int128 encoding — repay in parts first."));const Ae=R&&!S&&!de,pe=[{token:a.poolKey.currency0,amount:F},{token:a.poolKey.currency1,amount:j}],he=Rt(c,(De=t.permit)==null?void 0:De.permitBatch,pe);if(t.permit){const ue=Ae?await Es(e,{permit:t.permit,ownerOnChain:o,router:n.aegisRouterV1,requiredTokens:pe,blockTimestamp:r.blockTimestamp,chainId:t.chainId,permit2Address:n.permit2,blockNumber:r.blockNumber}):en({permit:t.permit,ownerOnChain:o,router:n.aegisRouterV1,requiredTokens:pe,blockTimestamp:r.blockTimestamp});if(ue&&te.push(ue),ee(t.signal,"quoteCloseVault"),Ae){const J=await vn(e,r,"quoteCloseVault");if(J)return E(J);ee(t.signal,"quoteCloseVault");}}let be=null;if(Ae){const J=ys(a,i,P??K,A>0n?I:0n,(ne==null?void 0:ne.engineTokenDebit)??null);J===null?(R=!1,C="insufficient-funding",g.push("Could not project the amounts the burn pulls at the frame price — treating the close as unfundable; re-quote against a fresh frame.")):be={amount0:J.idle0,amount1:J.idle1};}const fe=Ae&&be!==null,Y=fe?$(P??K,he,{maxEngineTokenDebit0:(ye==null?void 0:ye.amount0)??0n,maxEngineTokenDebit1:(ye==null?void 0:ye.amount1)??0n,minLiquidityDelta:0n}):null;let ae=null;if(Y!==null)try{ae=Nr(Y);}catch(ue){g.push(ue instanceof Error?ue.message:"buildCloseVault failed."),S=!0;}const V=fe&&!S&&ae!==null,le=V&&ye!==null?Rs(ye,ne):null,H=S?"builder-error":de?"engine-debit-bound-unavailable":C,Z=!V||ae===null?{status:"rejected",reason:"quote-infeasible",call:null,evidence:null}:te.length>0?{status:"blocked",reason:"execution-gate",call:null,evidence:null}:ge??(await za(e,{account:t.owner,router:n.aegisRouterV1,call:ae,frame:r,executionFrameMaxAgeSeconds:t.executionFrameMaxAgeSeconds,validUntil:he,...(t.signal?{signal:t.signal}:{}),fn:"quoteCloseVault"}));g.push(...Ba(Z,r,"close"));const z=V?{rL0Post:0n,debtLPost:0n,idle0Post:0n,idle1Post:0n,collateralFloorLPost:null,collateralBasis:"not-required-zero-debt",ltvPipsPost:null}:null;return{...v,...It(Z),// Tightened past the base clamp now that the wallet legs are sized.
|
|
1589
|
+
...Zn({requestedDeadline:t.deadline,validUntil:he,frame:r,maximumEngineTokenDebit:le,executionFrameMaxAgeSeconds:t.executionFrameMaxAgeSeconds}),feasible:V,...(H!==void 0?{infeasibleReason:H}:{}),gateFailures:te,vault:i,principalDeltaRl:A,requiredL:I,plan:D,fromWallet0:F,fromWallet1:j,approvals:Jr(a.poolKey,F,j,n.aegisRouterV1),nftsToDetach:x,nftRecipient:d,tokenRecipient:t.owner,// Both are documented null-when-infeasible, so they follow the demotion.
|
|
1590
|
+
expected:V?be:null,post:z,encodeInput:V?Y:null,fundingAtFrame:ta({frame:r,market:a,principalDeltaRl:A,requiredLiquidityL:I,source:P,engineDebitToleranceBps:h,synchronized:ne,enforcedMaximumEngineTokenDebit:le}),closeOutcomeAtFrame:Z.status==="verified-at-frame"?{vaultBurned:!0,residualDebtRl:0n}:null};}var n0=31556736;function Or(e,t){return t===0n?ie:e/t;}function r0(e){const{startSharePriceWad:t,endSharePriceWad:n,elapsedSeconds:r}=e;if(t<=0n||n<0n||r<=0)return{aprPct:null,apyPct:null};const a=Number(t)/Number(ie),i=Number(n)/Number(ie);if(!Number.isFinite(a)||!Number.isFinite(i)||a<=0)return{aprPct:null,apyPct:null};const o=i/a-1,s=n0/r,l=o*s*100,u=(Math.pow(1+o,s)-1)*100;return{aprPct:Number.isFinite(l)?l:null,apyPct:Number.isFinite(u)?u:null};}function ja(e){const t=e.horizonSeconds??86400n;if(e.totalShares<=0n||t<=0n){const l=Or(e.market.equityLWad,e.totalShares);return{aprPct:null,apyPct:null,sharePriceStartWad:l,sharePriceEndWad:l,equityLWadStart:e.market.equityLWad,equityLWadEnd:e.market.equityLWad,horizonSeconds:t,unavailableReason:e.totalShares<=0n?"empty-market":"zero-horizon"};}const n=e.oracle.previewAccrual(e.market,e.nowTimestamp),r={...e.market,borrowIndexWad:n.borrowIndexWadLatest,equityLWad:n.equityLWadLatest,fullUtilRate:n.fullUtilRateLatest,lastAccrueTimestamp:e.nowTimestamp},a=e.oracle.previewAccrual(r,e.nowTimestamp+t),i=Or(n.equityLWadLatest,e.totalShares),o=Or(a.equityLWadLatest,e.totalShares),s=r0({startSharePriceWad:i,endSharePriceWad:o,elapsedSeconds:Number(t)});return{aprPct:s.aprPct,apyPct:s.apyPct,sharePriceStartWad:i,sharePriceEndWad:o,equityLWadStart:n.equityLWadLatest,equityLWadEnd:a.equityLWadLatest,horizonSeconds:t,...(s.aprPct===null?{unavailableReason:"non-finite"}:{})};}function a0(e){const t=e.oracle.previewAccrual(e.market,e.nowTimestamp),n={...e.market,borrowIndexWad:t.borrowIndexWadLatest,equityLWad:t.equityLWadLatest+e.liquidityDelta*ie,fullUtilRate:t.fullUtilRateLatest,lastAccrueTimestamp:e.nowTimestamp};return ja({market:n,totalShares:e.totalShares+e.expectedShares,oracle:e.oracle,nowTimestamp:e.nowTimestamp,...(e.horizonSeconds!==void 0?{horizonSeconds:e.horizonSeconds}:{})});}var i0=["constant-rate-model-config","no-other-flows-over-horizon"];async function o0(e){var x,k,_;if(e.deployment||e.chainId!==void 0){if(e.chainId===void 0)throw new Error("Aegis deployment requires a quote chainId.");const D=Hr(e.chainId,e.market.poolKey.hooks,e.deployment);if(e.approvalSpender!==void 0&&e.approvalSpender.toLowerCase()!==D.addresses.aegisRouterV1.toLowerCase())throw new Error("Deposit approval spender does not match the pool hook Aegis deployment.");e={...e,approvalSpender:D.addresses.aegisRouterV1};}const t=[],n=e.inputIsToken0?e.market.poolKey.currency0:e.market.poolKey.currency1,r=y0(e,n),a=Kr(e.frame,e.nowTimestamp),i=[{token:n,amount:e.amountIn}],o=Rt(h0(e,a),(x=e.permit)==null?void 0:x.permitBatch,i),s=e.apyProjection?ja({market:e.apyProjection.market,totalShares:e.apyProjection.totalShares,oracle:e.apyProjection.oracle,nowTimestamp:e.apyProjection.nowTimestamp,...(e.apyProjection.horizonSeconds!==void 0?{horizonSeconds:e.apyProjection.horizonSeconds}:{})}):null,l={lendAprPct:(s==null?void 0:s.aprPct)??null,lendApyPct:(s==null?void 0:s.apyPct)??null};let u=null;e.permit&&(e.approvalSpender===void 0?u={gate:"permit-invalid",detail:"approvalSpender (the router the permit must authorize) is required to validate a permit"}:(u=en({permit:e.permit,ownerOnChain:e.owner,router:e.approvalSpender,requiredTokens:i,// Chain time when known; else the LOCAL clock as a documented
|
|
1591
|
+
// screening fallback — an expired permit must not ride executable
|
|
1592
|
+
// calldata just because no chain clock was supplied.
|
|
1593
|
+
blockTimestamp:a}),u===null&&(u=cr(e.permit,e.approvalSpender,{blockNumber:(k=e.frame)==null?void 0:k.blockNumber,chainId:e.chainId}))),u&&u.gate==="permit-invalid"&&t.push(`Permit cannot fund this deposit: ${u.detail}`));const d=u?[u]:[],c=(D,P)=>({feasible:!1,executable:!1,infeasibleReason:D,encodeInput:null,call:null,swap:null,deposit:null,expectedSharePriceWad:e.sharePriceWad,routeSummary:null,priceImpactBps:null,approvalPlan:r,gateFailures:d,expiresAt:o,warnings:t,display:l,apyEstimate:s,postDeposit:null,frame:e.frame??null,quoteCount:P});if(e.deadline<=a)return t.push("Deadline expired at quote time — re-quote with a fresh deadline."),c("invalid-input",0);if(e.amountIn<=1n||e.sharePriceWad<=0n)return t.push("Deposit zap requires amountIn > 1 and a positive sharePriceWad."),c("invalid-input",0);if(e.amountIn>ce)return t.push("Deposit amountIn exceeds the signed int128 calldata domain."),c("invalid-input",0);if(!Number.isInteger(e.slippageBps)||e.slippageBps<0||e.slippageBps>=1e4)return t.push("Deposit zap requires an integer slippageBps between 0 and 9,999."),c("invalid-input",0);if(e.quoteTtlSeconds!==void 0&&e.quoteTtlSeconds<0n)return t.push("Deposit zap requires quoteTtlSeconds >= 0."),c("invalid-input",0);const p=d0(e.market);if(p===null)return t.push("Deposit zap requires the current lpFeePips from V4 StateView for a dynamic-fee pool."),c("invalid-input",0);const y=m0(e.market),b=u0(e,y,p);if(b<=0n||b>=e.amountIn)return t.push("No positive swap split can produce full-range deposit liquidity."),c("zero-liquidity",0);const m=1;let h;try{h=await s0(e,y,b);}catch(D){return t.push(D instanceof Error?D.message:"Deposit zap quote failed."),c("quote-unavailable",m);}if(h===null)return t.push("No candidate swap split produced positive full-range liquidity."),c("zero-liquidity",m);if(h.expectedShares<=0n||h.minDeltaShares<=0n)return t.push("Expected shares round to zero at the supplied share price and slippage."),c("insufficient-output",m);const g=e.recipient??e.owner,v={poolId:e.market.poolId,poolKey:e.market.poolKey,inputIsToken0:e.inputIsToken0,amountIn:e.amountIn,swapAmountIn:h.swapAmountIn,minSwapAmountOut:h.minAmountOut,liquidityDelta:h.liquidityDelta,recipient:g,minDeltaShares:h.minDeltaShares,amount0Max:h.amount0Max,amount1Max:h.amount1Max,deadline:e.deadline,route:h.quote.route,slippageBps:e.slippageBps,...(e.permit?{permit:Ta(e.permit)}:{})};let w=null;try{w=wc(v);}catch(D){return t.push(D instanceof Error?D.message:"buildDepositZapRecipe failed."),{...c("builder-error",m),encodeInput:v};}(h.quote.route===null||h.quote.route.length===0)&&t.push("Swap route unavailable; calldata will use the market single-hop fallback.");const E=e.priceImpactWarningBps??100;h.quote.priceImpactBps!==void 0&&h.quote.priceImpactBps>E&&t.push(`Price impact exceeds ${E} bps.`),t.push("Deposit zap amount maxima are sized from the conservative quote frame; use fresh quotes and tight transaction deadlines.");const A={amount0:h.amount0,amount1:h.amount1,liquidityDelta:h.liquidityDelta,expectedShares:h.expectedShares,minDeltaShares:h.minDeltaShares,expectedSharePriceWad:e.sharePriceWad,amount0Max:h.amount0Max,amount1Max:h.amount1Max},I=Rt(qs(e.deadline,h.quote.expiresAt??o),(_=e.permit)==null?void 0:_.permitBatch,i),T=e.apyProjection?Os(e.apyProjection,h):null,L=d.length===0;return{feasible:!0,executable:L,gateFailures:d,encodeInput:v,call:L?w:null,swap:{needed:h.swapAmountIn>0n,amountIn:h.swapAmountIn,isToken0:e.inputIsToken0,amountOut:h.amountOut,minAmountOut:h.minAmountOut},deposit:A,expectedSharePriceWad:e.sharePriceWad,routeSummary:h.quote.routeSummary??b0(h.quote.route),priceImpactBps:h.quote.priceImpactBps??null,approvalPlan:r,expiresAt:I,warnings:t,display:l,apyEstimate:s,postDeposit:T,frame:e.frame??null,quoteCount:m};}function Os(e,t){const n=a0({market:e.market,totalShares:e.totalShares,oracle:e.oracle,nowTimestamp:e.nowTimestamp,...(e.horizonSeconds!==void 0?{horizonSeconds:e.horizonSeconds}:{}),liquidityDelta:t.liquidityDelta,expectedShares:t.expectedShares});return{basis:"projected-post-deposit",aprPct:n.aprPct,apyPct:n.apyPct,totalSharesPost:e.totalShares+t.expectedShares,equityLWadPost:n.equityLWadStart,horizonSeconds:n.horizonSeconds,estimate:n,unavailableReason:n.unavailableReason??null,assumptions:i0};}async function s0(e,t,n){const r=await e.fetchQuote({amountIn:n,inputIsToken0:e.inputIsToken0,purpose:"deposit-zap-split",signal:e.signal});if(r.minAmountOut<=0n)return null;const a=r.minAmountOut,i=r.amountOut??a,o=e.inputIsToken0?e.amountIn-n:a,s=e.inputIsToken0?a:e.amountIn-n,l=lr({idle0:o,idle1:s,poolKey:e.market.poolKey,poolState:t});if(l===null||l<=0n)return null;const u=l0(l,e.sharePriceWad);return{quote:r,swapAmountIn:n,amountOut:i,minAmountOut:a,amount0:o,amount1:s,liquidityDelta:l,expectedShares:u,minDeltaShares:f0(u,e.slippageBps),amount0Max:o,amount1Max:s};}function l0(e,t){return t<=0n?0n:e*ie/t;}function u0(e,t,n){const r=yt(e.market.inRangeLiquidity,e.market.poolKey,t,!1);if(r===null)return 0n;const a=e.inputIsToken0?r.amount0:r.amount1;if(a<=0n)return 0n;const i=BigInt(n),o=1000000n,s=o-i;if(s<=0n)return 0n;const l=2n*o-i,u=l*l*a*a+4n*s*e.amountIn*a*o,d=p0(u),c=l*a;if(d<=c)return 0n;const p=(d-c)/(2n*s);return p<=0n?0n:p>=e.amountIn?e.amountIn-1n:p;}var c0=8388608;function d0(e){const n=(e.poolKey.fee&c0)!==0?e.lpFeePips:e.poolKey.fee;return n===void 0||!Number.isInteger(n)||n<0||n>=1e6?null:n;}function p0(e){if(e<0n)throw new Error("sqrtFloor: negative input");if(e<2n)return e;let t=e,n=(t+e/t)/2n;for(;n<t;)t=n,n=(t+e/t)/2n;return t;}function f0(e,t){const n=BigInt(Math.max(0,1e4-t));return e*n/10000n;}function m0(e){return{sqrtPriceX96:e.sqrtPriceX96,tick:e.tickCurrent,protocolFee:0,lpFee:e.lpFeePips??0,liquidity:e.inRangeLiquidity};}function y0(e,t){const n=t.toLowerCase()===ke?e.amountIn:0n,r={approvalType:"permit2",token:t,amount:e.amountIn,required:n===0n,nativeValue:n};return e.approvalSpender?{...r,spender:e.approvalSpender}:r;}function h0(e,t){const n=e.quoteTtlSeconds??60n,r=n<0n?0n:n;return qs(e.deadline,t+r);}function qs(e,t){return e<t?e:t;}function b0(e){return!e||e.length===0?null:e.map(t=>{if(t.length===0)return"";const n=t[0];if(!n)return"";const r=[n.tokenIn.symbol];for(const a of t)r.push(a.tokenOut.symbol);return r.join(" -> ");}).filter(t=>t.length>0).join(" / ");}var Zi=(1n<<128n)-1n,ra=(1n<<256n)-1n;function g0(e){var K;const t=e.quoteTtlSeconds??60n,n=st(e.deadline,e.frame.blockTimestamp+(t<0n?0n:t)),r=$=>({mode:"balanced",feasible:!1,executable:!1,infeasibleReason:$,frame:e.frame,expiresAt:n,deposit:null,unused:null,walletRemainder:null,limitingSide:null,nativeGasReserve:e.funding.nativeGasReserve,nativeValue:0n,approvalPlans:[],gateFailures:[],encodeInput:null,call:null,swap:{needed:!1},display:{lendAprPct:null,lendApyPct:null},apyEstimate:null,postDeposit:null});if(!v0(e))return r("invalid-input");if(n<=e.frame.blockTimestamp)return r("expired");if(e.funding.nativeBalance<e.funding.nativeGasReserve)return r("insufficient-native-gas-reserve");const{currency0:a,currency1:i}=e.market.poolKey,o=a.toLowerCase()===ke,s=i.toLowerCase()===ke,l=e.funding.nativeBalance-e.funding.nativeGasReserve,u=st(e.amount0Max,st(e.funding.balance0,o?l:ra)),d=st(e.amount1Max,st(e.funding.balance1,s?l:ra));if(u===0n||d===0n)return r("insufficient-pair-balance");const c={sqrtPriceX96:e.market.sqrtPriceX96,tick:e.market.tickCurrent,liquidity:e.market.inRangeLiquidity,protocolFee:0,lpFee:e.market.lpFeePips??0},p=lr({idle0:u,idle1:d,poolKey:e.market.poolKey,poolState:c});if(p===null||p<=0n)return r("zero-liquidity");if(p>ce)return r("requires-split");const y=$=>yt($,e.market.poolKey,c,!0),b=$=>$!==null&&$.amount0<=u&&$.amount1<=d;let m=p,h=y(m);if(!b(h)){let $=0n,S=m;for(;S-$>1n;){const re=($+S)/2n;b(y(re))?$=re:S=re;}m=$,h=y(m);}if(!b(h)||h.amount0<=0n||h.amount1<=0n)return r("zero-liquidity");if(h.amount0>ce||h.amount1>ce)return r("requires-split");const g=e.totalShares===0n&&e.version!=="v0.4.0"?xo:0n;if(e.totalShares===0n&&m<=g)return r("insufficient-output");const v=e.totalShares===0n?m-g:m*ie/e.sharePriceWad,E=(e.totalShares===0n?v:m*ie/(e.sharePriceWad+1n))*BigInt(1e4-e.slippageBps)/10000n;if(E<=0n)return r("insufficient-output");const A=$=>($*BigInt(1e4+e.slippageBps)+9999n)/10000n,I=st(Zi,st(u,A(h.amount0))),T=st(Zi,st(d,A(h.amount1))),L=o?I:s?T:0n,x=[{approvalType:"permit2",token:a,amount:I,required:!o,nativeValue:o?L:0n,spender:e.approvalSpender},{approvalType:"permit2",token:i,amount:T,required:!s,nativeValue:s?L:0n,spender:e.approvalSpender}],k=x.filter($=>$.required).map(({token:$,amount:S})=>({token:$,amount:S})),_=[];if(e.permit){const $=en({permit:e.permit,ownerOnChain:e.owner,router:e.approvalSpender,requiredTokens:k,blockTimestamp:e.frame.blockTimestamp})??cr(e.permit,e.approvalSpender,{blockNumber:e.frame.blockNumber,chainId:e.chainId});$&&_.push($);}const D=Rt(n,(K=e.permit)==null?void 0:K.permitBatch,k),P={poolId:e.market.poolId,liquidityDelta:m,recipient:e.recipient??e.owner,deadline:D,minShares:E,amount0Max:I,amount1Max:T,currency0:a,currency1:i,value:L,refundNative:L>0n,...(e.permit?{permit:Ta(e.permit)}:{})},W=y(m+1n),q=W===null||W.amount0>u,R=W===null||W.amount1>d,C=e.apyProjection?{...e.apyProjection,nowTimestamp:e.frame.blockTimestamp}:null,F=C?ja(C):null,j=_.length===0;return{mode:"balanced",feasible:!0,executable:j,infeasibleReason:null,frame:e.frame,expiresAt:D,deposit:{...h,liquidityDelta:m,expectedShares:v,minDeltaShares:E,expectedSharePriceWad:e.sharePriceWad,amount0Max:I,amount1Max:T},unused:{amount0:e.amount0Max-h.amount0,amount1:e.amount1Max-h.amount1},walletRemainder:{amount0:e.funding.balance0-h.amount0,amount1:e.funding.balance1-h.amount1},limitingSide:q&&R?"both":q?"token0":R?"token1":null,nativeGasReserve:e.funding.nativeGasReserve,nativeValue:L,approvalPlans:x,gateFailures:_,encodeInput:P,call:j?bc(P):null,swap:{needed:!1},display:{lendAprPct:(F==null?void 0:F.aprPct)??null,lendApyPct:(F==null?void 0:F.apyPct)??null},apyEstimate:F,postDeposit:C?Os(C,{liquidityDelta:m,expectedShares:v+g}):null};}function st(e,t){return e<t?e:t;}function v0(e){const t=e.market.poolKey;return[e.amount0Max,e.amount1Max,e.sharePriceWad,e.totalShares,e.funding.balance0,e.funding.balance1,e.funding.nativeBalance,e.funding.nativeGasReserve].some(r=>r<0n||r>ra)||e.sharePriceWad===0n&&e.totalShares!==0n||!["v0.4.0","v1.0.2","v1.0.3"/* V1_0_3 */].includes(e.version)||!Number.isInteger(e.slippageBps)||e.slippageBps<0||e.slippageBps>=1e4||!Number.isSafeInteger(e.chainId)||e.chainId<=0||(e.quoteTtlSeconds??60n)<0n||e.frame.blockNumber<0n||e.frame.blockTimestamp<0n||!/^0x[0-9a-fA-F]{64}$/.test(e.frame.blockHash)||!Number.isFinite(e.frame.observedAt)||e.frame.observedAt<0||!Number.isInteger(t.tickSpacing)||t.tickSpacing<=0||t.tickSpacing>32767||!Number.isInteger(t.fee)||t.fee<0||t.fee>16777215||!Number.isInteger(e.market.tickCurrent)||e.market.tickCurrent<-887272||e.market.tickCurrent>887272||e.market.sqrtPriceX96<=0n||e.market.inRangeLiquidity<0n||[e.owner,e.recipient??e.owner,e.approvalSpender].some(r=>!sn(r)||r.toLowerCase()===ke)||!sn(t.currency0)||!sn(t.currency1)||!sn(t.hooks)||BigInt(t.currency0)>=BigInt(t.currency1)?!1:ar(t).toLowerCase()===e.market.poolId.toLowerCase();}var w0={"v0.4.0":null,"v1.0.2":950000n,"v1.0.3":950000n};function A0(e){return ba(w0,e);}function T0({sharesToBurn:e,equityLWad:t,shareSupply:n}){if(e<0n)throw new Error("calculateRedeemLiquidity: sharesToBurn must be non-negative");if(t<0n)throw new Error("calculateRedeemLiquidity: equityLWad must be non-negative");if(n<=0n)throw new Error("calculateRedeemLiquidity: shareSupply must be positive");if(e>n)throw new Error("calculateRedeemLiquidity: sharesToBurn must not exceed shareSupply");}function E0(e){return T0(e),e.sharesToBurn*e.equityLWad/(e.shareSupply*ie);}function I0(e){if(e.borrowedLWad<0n)throw new Error("assessPostRedeemUtilization: borrowedLWad must be non-negative");if(e.capPips!==null&&e.capPips<0n)throw new Error("assessPostRedeemUtilization: capPips must be non-negative");const t=E0(e),n=e.equityLWad-t*ie,r=n===0n?0n:e.borrowedLWad*_e/n;return{liquidityDelta:t,postEquityLWad:n,postUtilizationPips:r,capPips:e.capPips,passes:e.capPips===null||r<=e.capPips};}var aa=(1n<<128n)-1n,ia=["InsufficientAmount0Received","InsufficientAmount1Received"],on=["The StateView projection is an interest-only estimate made before fee collection, residue reinvestment, and protocol-share minting.","A verified-at-frame result proves only that the exact protected Router call succeeded at the pinned frame; later state may still make it revert.","expiresAt is an operational re-quote policy, not a mathematical extension of the preflight proof."],x0=["fee-collection","residue-reinvestment","protocol-share-mint"];function k0(e,t){if(e.errorName!==ia[t]||!e.args||e.args.length<2)return null;const[n,r]=e.args;return typeof n!="bigint"||n<0n||typeof r!="bigint"||r!==aa?null:n;}function D0(e){if(e.errorName!=="AegisEngineError"||!e.args||e.args.length!==1)return!1;const[t]=e.args;return t===19;}async function N0(e,t){const{poolId:n,owner:r,shares:a,slippageBps:i,deadline:o}=t,s=A0(t.version),l=je(t.chainId,t.version,t.deployment),{addresses:u}=l;ee(t.signal,"quoteRedeem");const d=await Gt(e,t.blockNumber);ee(t.signal,"quoteRedeem");const c=d.blockNumber,p=d.blockHash,{expiresAt:y,ttlInvalid:b}=dr({deadline:o,frame:d,quoteTtlSeconds:t.quoteTtlSeconds});let m;try{m=await Promise.all([ka(e,u.aegisStateView,n,c),ts(e,u.stateView,n,c),Pa(e,u.aegisStateView,n,c),ed(e,u.aegisEngine,r,n,c),e.readContract({address:u.aegisEngine,abi:$e,functionName:"isOperator",args:[r,u.aegisRouterV1],blockNumber:c}),e.readContract({address:u.aegisEngine,abi:$e,functionName:"allowance",args:[r,u.aegisRouterV1,BigInt(n)],blockNumber:c})]),ee(t.signal,"quoteRedeem"),await jt(e,d,"quoteRedeem"),ee(t.signal,"quoteRedeem");}catch(Y){if(!(Y instanceof kn))throw Y;return{kind:"redeem",status:"unavailable",reason:"frame-not-canonical",retryable:!0,gateFailures:[],sharesDelta:a==="all"?null:a,shareBalance:null,projection:null,approvals:[],frame:d,deadline:o,expiresAt:y,warnings:[`Block ${c} changed from ${p} to ${Y.observedBlockHash} during the read wave; re-quote against a fresh frame.`],output:null,minimum:null,encodeInput:null,call:null,preflight:null,assumptions:[...on]};}const[h,g,v,w,E,A]=m,{market:I,latestBorrowIndexWad:T,latestEquityLWad:L}=h;xn(l,I.poolKey.hooks);const x=o<=d.blockTimestamp?[{gate:"deadline-expired",deadline:o,blockTimestamp:d.blockTimestamp}]:[],k=[],_=a==="all"?w:a;!E&&A<_&&x.push({gate:"operator-authorization",owner:r,router:u.aegisRouterV1,engine:u.aegisEngine});const D={kind:"redeem",sharesDelta:_,shareBalance:w,approvals:[],frame:d,deadline:o,expiresAt:y,warnings:k},P=(Y,ae={})=>({...D,status:"rejected",reason:Y,output:null,gateFailures:x,projection:ae.projection??null,minimum:ae.minimum??null,encodeInput:ae.encodeInput??null,call:null,preflight:ae.preflight??null,assumptions:[...on]});if(!Number.isInteger(i)||i<0||i>=1e4)return k.push("quoteRedeem requires an integer slippageBps between 0 and 9,999."),P("invalid-input");if(b)return k.push("quoteRedeem requires quoteTtlSeconds >= 0."),P("invalid-input");if(a!=="all"&&a<=0n)return k.push("quoteRedeem requires shares > 0 (or 'all')."),P("invalid-input");if(_>ce)return k.push("Redeem exceeds the int128 action encoding — split into multiple partial redeems."),P("requires-split");if(_===0n||_>w)return k.push(_===0n?"No shares to redeem: the in-frame ERC-6909 balance is zero.":"Requested share burn exceeds the in-frame ERC-6909 balance."),P("insufficient-shares");if(v<=0n||_>v||L<0n)return k.push("Observed market share supply/equity cannot support the requested share calculation."),P("invalid-state");const W=I.totalRlBorrowed*T,q=I0({sharesToBurn:_,equityLWad:L,shareSupply:v,borrowedLWad:W,capPips:s}),R=yt(q.liquidityDelta,I.poolKey,g,!1),C={quality:"estimated-incomplete-synchronization",basis:"state-view-interest-preview",liquidityDeltaEstimate:q.liquidityDelta,tokenOutputEstimate:R,capAssessment:{applies:s!==null,capPips:s,postUtilizationPipsEstimate:q.postUtilizationPips,passesEstimate:q.passes},omittedSynchronization:[...x0]};if(s!==null&&!q.passes&&k.push(`The incomplete StateView projection is above the ${s}-pip cap; the Router preflight remains authoritative for this request.`),R===null&&k.push("StateView produced no token estimate; Router output probes remain authoritative."),x.length>0)return{...D,status:"blocked",reason:"execution-gate",gateFailures:x,projection:C,output:null,minimum:null,encodeInput:null,call:null,preflight:null,assumptions:[...on]};const F={poolId:n,sharesDelta:_,owner:r,recipient:t.recipient??r,deadline:o,currency0:I.poolKey.currency0,currency1:I.poolKey.currency1,minAmount0:0n,minAmount1:0n};let j,K;try{j=Dr({...F,minAmount0:aa}),K=Dr({...F,minAmount1:aa});}catch(Y){return k.push(Y instanceof Error?Y.message:"buildRedeem failed."),P("requires-split",{projection:C});}const $=(Y,ae)=>({kind:"router-simulation",method:"minimum-error-output-probes",scope:"synchronized-output-and-protected-call-at-frame",blockNumber:c,blockHash:p,blockTimestamp:d.blockTimestamp,account:r,router:u.aegisRouterV1,calldataHash:xt(Y.calldata),attempts:ae}),S=Y=>Wa(e,{account:r,router:u.aegisRouterV1,call:Y,frame:d,signal:t.signal,fn:"quoteRedeem"}),re=(Y,ae,V,Q=null,le=null)=>({...D,status:"unavailable",reason:Y,retryable:Y!=="probe-invariant",gateFailures:[],projection:C,output:null,minimum:Q,encodeInput:le,call:null,preflight:{...$(ae,V),outcome:"unavailable"},assumptions:[...on]}),te=(Y,ae,V=null,Q=null)=>(k.push(`Block ${c} is no longer the canonical block ${p}; re-quote against a fresh frame.`),re("frame-not-canonical",Y,ae,V,Q)),ne=(Y,ae,V,Q)=>{if(Y.errorName===null)return k.push("The RPC returned an undecodable Router revert during output probing."),re("preflight-revert-data-unavailable",ae,V);if(Y.errorName===ia[Q])return k.push(`The ${ia[Q]} probe payload did not contain the expected uint128 sentinel.`),re("probe-invariant",ae,V);const le=D0(Y)?"utilization-cap":"execution-reverted";return k.push(le==="utilization-cap"?"The synchronized Router simulation rejected redemption above the utilization cap.":`The synchronized Router simulation reverted with ${Y.errorName}.`),P(le,{projection:C,preflight:{...$(ae,V),outcome:"reverted"}});},ge=async(Y,ae,V)=>{const Q=await S(ae);if(Q.outcome==="frame-not-canonical")return te(ae,V);if(Q.outcome==="passed")return k.push(`The amount${Y} sentinel probe unexpectedly succeeded.`),re("probe-invariant",ae,V);const le=k0(Q,Y);return le===null?ne(Q,ae,V,Y):le;},de=await ge(0,j,1);if(typeof de!="bigint")return de;const me=await ge(1,K,2);if(typeof me!="bigint")return me;const ye={quality:"same-frame-simulated",basis:"router-minimum-error-probes",amount0:de,amount1:me},Ae=BigInt(1e4-i),pe={amount0:ye.amount0*Ae/10000n,amount1:ye.amount1*Ae/10000n};if(pe.amount0===0n||pe.amount1===0n)return k.push("Redeem too small to protect: a slippage-floored minimum rounds to zero."),P("insufficient-output",{projection:C});const he={...F,minAmount0:pe.amount0,minAmount1:pe.amount1},be=Dr(he),fe=await S(be);return fe.outcome==="frame-not-canonical"?te(be,3,pe,he):fe.outcome==="reverted"?(k.push("The final protected call disagreed with same-frame output probes; no calldata is returned."),re("inconsistent-simulation",be,3,pe,he)):{...D,status:"verified-at-frame",gateFailures:[],projection:C,output:ye,minimum:pe,encodeInput:he,call:be,preflight:{...$(be,3),outcome:"passed",probeCalldataHashes:[xt(j.calldata),xt(K.calldata)]},assumptions:[...on]};}sa(["event HookFee(bytes32 indexed poolId, address indexed sender, uint128 feeAmount0, uint128 feeAmount1)","event HookFeeReinvested(bytes32 indexed poolId, address indexed sender, uint128 feeAmount0, uint128 feeAmount1)","event HookFeePpmUpdated(bytes32 indexed poolId, uint256 hookFeePpm)"]);sa(["event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)","event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId)","event ApprovalForAll(address indexed owner, address indexed operator, bool approved)"]);Hs("Transfer(address,address,uint256)");sa(["event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)"]);function L0(e){const{poolKey:t,poolId:n,owner:r,deadline:a,deposit0:i,deposit1:o,principalDelta:s,swapRoute:l,swapInputAmount:u,swapInputIsToken0:d,depositAfterSwap0:c,depositAfterSwap1:p,maxLtvPips:y=0n,slippageBps:b=50,value:m=0n,permit:h}=e,g=d?t.currency0:t.currency1,v=d?t.currency1:t.currency0,w=u>0n,E=l.some(k=>k.length>0),A=c>0n||p>0n;if(w!==E||w!==A)throw new Error("Tap open swap input, route, and output deposit must be present together");const I=new ft();if(I.addCreateVault(n,r),I.addUnlockVault(bt),(i>0n||o>0n)&&(I.addModifyIdle(bt,Mt(i,o)),i>0n&&I.addCloseAE(t.currency0),o>0n&&I.addCloseAE(t.currency1)),I.addModifyDebt(bt,s),w){const[k,_]=d?[u,0n]:[0n,u];I.addModifyIdle(bt,or(k,_)),I.addTakeAE(g,zt);const D=/* @__PURE__ */new Set();for(const P of l)for(const W of P)D.add(Qa(W.tokenIn.address)),D.add(Qa(W.tokenOut.address));Ia(I,l,b,D),I.addSettle(g,Ue,!1),I.addTake(v,zt,Ue),I.addModifyIdle(bt,Mt(c,p)),I.addSettleAE(v,Ue,!1);}I.addLockVault(bt,y),w&&(I.addSweep(t.currency0,ze),I.addSweep(t.currency1,ze));const T=I.finalize({requiresV4Unlock:w}),L=Xa(t.currency0,ke)?i:Xa(t.currency1,ke)?o:0n,x=m>L?m:L;if(h){const k=Ze.encodePermitBatch(h.owner,h.permitBatch,h.signature),{calldata:_}=Ze.encodeExecute([T],a);return Ze.encodeMulticall([k,_],x);}return Ze.encodeExecute([T],a,x);}const R0={buildDegenPosition:Fd,buildTapOpenPosition:L0,computeActualLtvPips:gn,computeBorrowCapacity:Qn,computeMaxEfficientDeposit:Vd,computeVaultStateSnapshot:_p,createSubgraphClient:sd,deltaMaxByUtil:ls,dMinNoSwap:zo,estimatePostBorrowRate:cs,fetchBorrowQuoteContext:Qc,fetchBorrowVaultContext:rs,fetchLendQuoteContext:Xc,fetchMarket:jo,fetchMarketWithAccrual:ka,fetchMarketLtvThresholds:Oc,fetchMarketSharePriceLatest:Ko,fetchPositionsBatch:td,fetchPoolState:ts,getAmountsForFullRangeLiquidity:yt,fetchTotalSupply:Pa,fetchVaultDebtActions:Nd,fetchVaultIdleActions:Ld,getChainConfigForHook:Ku,forwardFunctionNoSwap:jn,interestCostOverHorizon:Ec,invertSqrtPriceX96:Zt,minDebtFloorRl:Jt,PIPS_DENOMINATOR:_e,previewFullRangeBorrow:od,priceFromSqrtX96:Ot,quoteBorrow:Fp,quoteBalancedDeposit:g0,quoteCloseVault:t0,quoteDeposit:o0,quoteIdleWithdraw:Jp,quoteRedeem:N0,quoteRepay:Kp,quoteExactInputSingle:Od,tauFromTimeToLiq:Tc,uniswapV4QuoterAbi:os,UTILIZATION_CAP_PIPS:In,utilizationHeadroomGammaNewLWad:Ma,verifyPermit2Batch:So};export{R0 as engineSdkRuntime};
|