@domfi/sdk 0.1.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/LICENSE +16 -0
- package/README.md +786 -0
- package/dist/actions.cjs +1 -0
- package/dist/actions.d.cts +17 -0
- package/dist/actions.d.ts +17 -0
- package/dist/actions.js +1 -0
- package/dist/api.cjs +1 -0
- package/dist/api.d.cts +664 -0
- package/dist/api.d.ts +664 -0
- package/dist/api.js +0 -0
- package/dist/chunk-2VSPOLVO.js +1 -0
- package/dist/chunk-5YZVCHRU.js +0 -0
- package/dist/chunk-77XMXAXE.js +1 -0
- package/dist/chunk-7OVWNPZQ.js +1 -0
- package/dist/chunk-BMYMNNJK.js +1 -0
- package/dist/chunk-C5Y2WM7C.js +1 -0
- package/dist/chunk-C64LJM7D.js +2 -0
- package/dist/chunk-CLOFJTBP.js +1 -0
- package/dist/chunk-CMREWGOI.js +1 -0
- package/dist/chunk-D5VE2O4F.js +1 -0
- package/dist/chunk-LDE3JHVE.js +1 -0
- package/dist/chunk-N4Q67DTE.js +1 -0
- package/dist/chunk-SZE5DE54.js +1 -0
- package/dist/chunk-XHQVWI2J.js +1 -0
- package/dist/chunk-YU5DN3PI.js +1 -0
- package/dist/config.cjs +2 -0
- package/dist/config.d.cts +132 -0
- package/dist/config.d.ts +132 -0
- package/dist/config.js +1 -0
- package/dist/contracts.cjs +1 -0
- package/dist/contracts.d.cts +13073 -0
- package/dist/contracts.d.ts +13073 -0
- package/dist/contracts.js +1 -0
- package/dist/delegation.cjs +1 -0
- package/dist/delegation.d.cts +7 -0
- package/dist/delegation.d.ts +7 -0
- package/dist/delegation.js +0 -0
- package/dist/errors.cjs +3 -0
- package/dist/errors.d.cts +155 -0
- package/dist/errors.d.ts +155 -0
- package/dist/errors.js +3 -0
- package/dist/index.cjs +2 -0
- package/dist/index.d.cts +216 -0
- package/dist/index.d.ts +216 -0
- package/dist/index.js +1 -0
- package/dist/math.cjs +1 -0
- package/dist/math.d.cts +273 -0
- package/dist/math.d.ts +273 -0
- package/dist/math.js +1 -0
- package/dist/position-BnhSFyGe.d.cts +56 -0
- package/dist/position-BnhSFyGe.d.ts +56 -0
- package/dist/rawSchemas-MAT7EZCV.js +1 -0
- package/dist/referrals.cjs +1 -0
- package/dist/referrals.d.cts +66 -0
- package/dist/referrals.d.ts +66 -0
- package/dist/referrals.js +1 -0
- package/dist/serde.cjs +1 -0
- package/dist/serde.d.cts +24 -0
- package/dist/serde.d.ts +24 -0
- package/dist/serde.js +1 -0
- package/dist/token.cjs +1 -0
- package/dist/token.d.cts +32 -0
- package/dist/token.d.ts +32 -0
- package/dist/token.js +0 -0
- package/dist/trading.cjs +1 -0
- package/dist/trading.d.cts +20 -0
- package/dist/trading.d.ts +20 -0
- package/dist/trading.js +1 -0
- package/dist/types-7s13ZSql.d.ts +533 -0
- package/dist/types-BK6dYOXr.d.cts +118 -0
- package/dist/types-CMtixBIP.d.cts +464 -0
- package/dist/types-DB1r_Ppi.d.ts +464 -0
- package/dist/types-DDgJiEFg.d.ts +780 -0
- package/dist/types-DJBX-p4X.d.cts +780 -0
- package/dist/types-DQft82W7.d.cts +533 -0
- package/dist/types-DhCzEwnS.d.ts +118 -0
- package/dist/types-veTDfbhq.d.ts +436 -0
- package/dist/types-x1MvxSdy.d.cts +436 -0
- package/dist/units-BYd75H7U.d.cts +22 -0
- package/dist/units-BYd75H7U.d.ts +22 -0
- package/dist/units.cjs +1 -0
- package/dist/units.d.cts +248 -0
- package/dist/units.d.ts +248 -0
- package/dist/units.js +1 -0
- package/dist/valuation.cjs +1 -0
- package/dist/valuation.d.cts +5 -0
- package/dist/valuation.d.ts +5 -0
- package/dist/valuation.js +1 -0
- package/dist/vault.cjs +1 -0
- package/dist/vault.d.cts +34 -0
- package/dist/vault.d.ts +34 -0
- package/dist/vault.js +1 -0
- package/package.json +181 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {e,k,j as j$1,g as g$1,h,i,a as a$2,d as d$1}from'./chunk-LDE3JHVE.js';import {a as a$1}from'./chunk-D5VE2O4F.js';import {b as b$1,d,e as e$1,f}from'./chunk-C5Y2WM7C.js';import {a as a$3,b as b$2}from'./chunk-C64LJM7D.js';import {a}from'./chunk-YU5DN3PI.js';import*as A from'@domfi/sdk/errors';import {ValidationError,WalletAccountMismatchError,MissingAccountError,MissingApiClientError,TimeoutError,MissingPublicClientError,AbortError,ReadModelNotReadyError}from'@domfi/sdk/errors';import {WaitForTransactionReceiptTimeoutError,decodeEventLog,toEventSelector}from'viem';function Ue(e,n){let i={sdkVersion:a$1,sourceTag:"runtime-guards",chainId:n};return new ValidationError({message:e,diagnostics:i})}function it(e,n){if(e.kind!=="open_position"||e.wallet===void 0||e.pairIndex===void 0||e.index===void 0||e.tradeId===void 0)throw Ue("Open account position is missing verified position identity fields",n);return {wallet:e.wallet,pairIndex:e.pairIndex,index:e.index,tradeId:e.tradeId,chainId:n,source:"api"}}function tt(e,n){if(e.action!=="open"||e.orderType!=="limit"||e.triggerOrderType!=="limit"&&e.triggerOrderType!=="stop"||e.status!=="pending_execution"||e.isPending!==true||e.isCancelled!==false||e.wallet===void 0||e.pairIndex===void 0||e.limitIndex===void 0||e.lifecycleKey===void 0||e.initiatedTxHash===void 0||e.initiatedEventType===void 0)throw Ue("Open trigger account order is missing verified trigger identity fields",n);return {wallet:e.wallet,pairIndex:e.pairIndex,index:e.limitIndex,chainId:n,lifecycleKey:e.lifecycleKey,orderId:e.orderId,orderType:e.triggerOrderType,initiatedTxHash:e.initiatedTxHash,initiatedEventType:e.initiatedEventType,source:"api"}}var fe=Symbol("domfi.internalReceiptWaiterOptions"),_n=1e3;function ze(e){return {sdkVersion:a$1,sourceTag:"internal-receipt-polling",chainId:e?.chainId??0}}function Ke(e,n,i,t){return new ValidationError({message:`${e} must be ${n}`,diagnostics:ze(t),cause:i})}function G(e,n){if(e!==void 0&&(!Number.isFinite(e)||e<=0))throw new ValidationError({message:"pollingIntervalMs must be a finite positive number",diagnostics:ze(n),hint:"Omit pollingIntervalMs to use the chain default, or pass a value greater than 0.",cause:e})}function le(e,n){if(e!==void 0&&!(Number.isInteger(e)&&e>0))throw Ke("confirmations","a finite positive integer",e,n)}function Ye(e,n){if(e!==void 0&&!(Number.isFinite(e)&&e>0))throw Ke("timeoutMs","a finite positive number",e,n)}function X(e,n){if(e!==void 0)return Ye(e,n),Math.max(1,Math.floor(e))}function Z(e,n){le(e?.confirmations,n),e?.[fe]===true&&e.timeoutMs===0||Ye(e?.timeoutMs,n),G(e?.pollingIntervalMs,n);}function Ge(e,n){if(n!==void 0)return G(n,e),Math.max(1,Math.floor(n));let i=e?.blockTimeMs;return i!==void 0&&Number.isFinite(i)&&i>0?Math.max(1,Math.floor(i/2)):_n}var J=new Map,Xe=new WeakMap;function $n(e){let n=e.uid;return typeof n=="string"?n:void 0}function me(){if(typeof DOMException=="function")return new DOMException("The operation was aborted","AbortError");let e=new Error("The operation was aborted");return e.name="AbortError",e}function jn(e,n){if(n!==void 0){let t=J.get(n);return t===void 0&&(t=new Map,J.set(n,t)),t}let i=Xe.get(e);return i===void 0&&(i=new Map,Xe.set(e,i)),i}function Bn(e,n){return new Promise((i,t)=>{let r=()=>t(me());n.addEventListener("abort",r,{once:true}),e.then(i,t).finally(()=>{n.removeEventListener("abort",r);});})}function Ze(e,n,i,t){if(t?.aborted===true)return Promise.reject(me());let r=$n(e),d=jn(e,r),a=n.toLowerCase(),c=d.get(a),o;if(c===void 0)try{o=i({queued:!1});}catch(s){o=Promise.reject(s);}else o=c.then(()=>{if(t?.aborted===true)throw me();return i({queued:true})});let u=o.then(()=>{},()=>{});return d.set(a,u),u.then(()=>{d.get(a)===u&&(d.delete(a),r!==void 0&&d.size===0&&J.get(r)===d&&J.delete(r));}),t===void 0?o:Bn(o,t)}function Un(e){return Object.assign(new Error("receipt wait was aborted"),{cause:e})}function qn(e){return Object.assign(new Error("receipt wait timed out"),{cause:e})}function zn(){if(typeof DOMException=="function")return new DOMException("The operation was aborted","AbortError");let e=new Error("The operation was aborted");return e.name="AbortError",e}function Je(e){let n=e?.confirmations;return n===void 0||n<=1?1:n}function Kn(e,n){return {...e?.confirmations!==void 0?{confirmations:e.confirmations}:{},...e?.pollingIntervalMs!==void 0?{pollingIntervalMs:e.pollingIntervalMs}:{},...n!==void 0?{signal:n}:{},timeoutMs:0,[fe]:true}}function Yn(e){return X(e)}function Gn(e,n,i,t,r){let d=o=>o.finally(r),a=n?.signal,c=Yn(n?.timeoutMs);return a?.aborted===true?d(Promise.reject(i(a.reason))):d(a===void 0&&c===void 0?e:new Promise((o,u)=>{let s,f=()=>{s!==void 0&&clearTimeout(s),a?.removeEventListener("abort",m);},m=()=>{f(),u(i(a?.reason));};a?.addEventListener("abort",m,{once:true}),c!==void 0&&(s=setTimeout(()=>{f(),u(t(new Error("receipt wait timed out")));},c)),e.then(x=>{f(),o(x);},x=>{f(),u(x);});}))}function Qe(e,n){let i,t;for(let[r,d]of e)!d.settled||r<n||(i===void 0||r<i)&&(i=r,t=d);return t}function en(e){let n=new Map,i=Promise.resolve(),t=e.mapAbort??Un,r=e.mapTimeout??qn;return e.initialReceipt!==void 0&&n.set(Je(e.initialReceiptConfirmations===void 0?void 0:{confirmations:e.initialReceiptConfirmations}),{controller:new AbortController,promise:Promise.resolve(e.initialReceipt),settled:true,subscribers:0}),d=>{try{Z(d);}catch(u){return Promise.reject(u)}if(d?.signal?.aborted===true)return Promise.reject(t(d.signal.reason));let a=Je(d),c=Qe(n,a)??n.get(a);if(c===void 0){let u=new AbortController,s={controller:u,promise:void 0,settled:false,subscribers:0},f=i.catch(()=>{}).then(()=>{if(u.signal.aborted)throw zn();let m=Qe(n,a);return m!==void 0&&m!==s?m.promise:e.wait(Kn(d,u.signal))}).catch(m=>{throw n.get(a)===s&&n.delete(a),m});s.promise=f,f.then(()=>{s.settled=true;},()=>{s.settled=true;}),i=f.catch(()=>{}),f.catch(()=>{}),n.set(a,s),c=s;}let o=c;return o.subscribers+=1,Gn(o.promise,d,t,r,()=>{o.subscribers-=1,o.subscribers===0&&!o.settled&&(o.controller.abort(),n.get(a)===o&&n.delete(a));})}}var Jn="trading-execution",Qn="0x0000000000000000000000000000000000000000";function ei(e){return {sdkVersion:a$1,sourceTag:Jn,chainId:e.chain.chainId}}function F(e,n,i){return {message:n,diagnostics:ei(e),...i!==void 0?{hint:i}:{}}}function ee(e,n){return e.toLowerCase()===n.toLowerCase()}function nn(e){let n=e?.account;if(n!==void 0){if(typeof n=="string")return n;if(typeof n=="object"&&n!==null&&"address"in n){let i=n.address;if(typeof i=="string")return i}}}function Q(e,n,i){if(ee(n,Qn))throw new ValidationError(F(e,`${i} cannot be the zero address`))}function tn(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function rn(e,n,i){if(!(typeof n!="object"||n===null)&&tn(n,"trader"))throw new ValidationError(F(e,`${i} options cannot include trader`,"Use delegation: { trader } instead."))}function ni(e,n,i){if(!(typeof n!="object"||n===null)&&tn(n,"delegation"))throw new ValidationError(F(e,`${i} options cannot include delegation`,"Pass delegation: { trader } when preparing the transaction or initiating the action."))}function mt(e,n){rn(e,n,"trading prepare");let i=n?.account??e.account??nn(e.walletClient);if(i!==void 0&&Q(e,i,"sender"),n?.delegation===void 0)return i===void 0?{mode:"direct"}:{mode:"direct",trader:i,sender:i};let t=n.delegation.trader;return Q(e,t,"trader"),{mode:"delegated",trader:t,...i!==void 0?{sender:i}:{}}}function pt(e,n,i,t,r,d){rn(e,t,d),ni(e,t,d);let a=i??n?.sender;if(a!==void 0&&t?.account!==void 0&&!ee(t.account,a))throw new WalletAccountMismatchError(F(e,`requested account ${t.account} does not match prepared sender ${a}`,"Send with the same account used to prepare the transaction."));let c=a??t?.account??e.account??nn(r);if(c===void 0)throw new MissingAccountError(F(e,`${d} requires an account`));Q(e,c,"sender");let o=n?.trader??c;return Q(e,o,"trader"),n?.mode==="delegated"?{mode:"delegated",trader:o,sender:c}:{mode:"direct",trader:o,sender:c}}var di=1e3,ai=new Set(["executed","canceled","timed_out","identity_mismatch"]);function Ie(e){return ai.has(e.status)}function oi(e){return Ie(e)?true:e.status==="timeout_available"&&e.canHandleTimeout===true}async function ht(e,n){for await(let i of e.watch(n))if(i.phase==="terminal"||"result"in i&&i.result!==void 0&&oi(i.result))return i.result;return e.waitTerminal(n)}function v(e,n){return new AbortError({message:"trading lifecycle was aborted",diagnostics:e.diagnostics(),...n!==void 0?{cause:n}:{}})}function O(e){return new TimeoutError({message:"trading lifecycle timed out",diagnostics:e.diagnostics()})}function dn(e,n,i){return new ValidationError({message:n,hint:i,diagnostics:e.diagnostics()})}function N(e,n,i,t){let r=n;if(r?.account!==void 0&&r.delegation!==void 0)throw dn(e,"tracking options cannot include both account and delegation","Use account for direct tracking or delegation: { trader } for delegated tracking.");let d=r?.delegation?.trader??r?.account;if(t!==void 0&&d!==void 0&&!ee(t,d))throw dn(e,"tracking identity conflicts with the recovered transaction identity","Use the same trader identity as the recovered or delegated transaction.");let a=t??d;if(n===void 0&&i===void 0&&a===void 0)return;if(a===void 0)return {...n??{},...i!==void 0?{timeoutMs:i}:{}};let{account:c,delegation:o,...u}=n??{};return {...u,account:a,...i!==void 0?{timeoutMs:i}:{}}}function an(e){return e?.maxAttempts===void 0?Number.POSITIVE_INFINITY:Math.max(0,e.maxAttempts)}function un(e){let n=e.filter(i=>typeof i=="number"&&Number.isFinite(i)&&i>0);if(n.length!==0)return Date.now()+Math.min(...n)}function on(e){return un([e?.maxDurationMs])}function ci(e){return un([e?.timeoutMs,e?.maxDurationMs])}function ge(e,n){let i=e.diagnostics();j$1(n?.intervalMs,i),g$1(n?.timeoutMs,"timeoutMs",i),g$1(n?.maxDurationMs,"maxDurationMs",i),h(n?.maxAttempts,"maxAttempts",i),le(n?.confirmations,{chainId:i.chainId}),G(n?.pollingIntervalMs,{chainId:i.chainId});}function C(e){if(e!==void 0)return e-Date.now()}function ne(e,n){let i=[];e?.timeoutMs!==void 0&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0&&i.push(e.timeoutMs);let t=C(n);if(t!==void 0&&t>0&&i.push(t),i.length!==0)return Math.max(1,Math.floor(Math.min(...i)))}function si(e,n){let i=e?.intervalMs??di,t=C(n);return t===void 0?i:t<=0?0:Math.min(i,t)}function ui(e){return Ie(e)?"terminal":e.status==="unknown"?"unknown":"tracking"}async function fn(e,n,i){if(n?.aborted===true)throw v(e,n.reason);return n===void 0?i:new Promise((t,r)=>{let d=()=>n.removeEventListener("abort",a),a=()=>{d(),r(v(e,n.reason));};n.addEventListener("abort",a,{once:true}),i.then(c=>{d(),t(c);},c=>{d(),r(c);});})}async function fi(e,n,i,t){let r=ne(i,t);return fn(n,i?.signal,e.waitReceipt({...i?.signal!==void 0?{signal:i.signal}:{},...i?.confirmations!==void 0?{confirmations:i.confirmations}:{},...i?.pollingIntervalMs!==void 0?{pollingIntervalMs:i.pollingIntervalMs}:{},...r!==void 0?{timeoutMs:r}:{}}))}async function Te(e,n,i,t){let r=ne(i,t);return fn(n,i?.signal,e.orderId({...i?.signal!==void 0?{signal:i.signal}:{},...i?.confirmations!==void 0?{confirmations:i.confirmations}:{},...i?.pollingIntervalMs!==void 0?{pollingIntervalMs:i.pollingIntervalMs}:{},...r!==void 0?{timeoutMs:r}:{}}))}async function cn(e,n,i){let t=C(i);if(t!==void 0&&t<=0)throw O(e);let r=si(n,i);await k({...n?.signal!==void 0?{signal:n.signal}:{},diagnostics:e.diagnostics(),...r!==void 0?{intervalMs:r}:{}}).waitInterval(a=>v(e,a));}async function sn(e,n,i,t){let r=ne(i,t);return k({...i?.signal!==void 0?{signal:i.signal}:{},...r!==void 0?{timeoutMs:r}:{},diagnostics:e.diagnostics(),...i?.intervalMs!==void 0?{intervalMs:i.intervalMs}:{}}).runAttempt(()=>e.trackOnce(n,N(e,i,r,e.expectedTrader)),a=>v(e,a),()=>O(e))}function ln(e,n){return {...e,track:async t=>{ge(n,t);let r=N(n,t,void 0,n.expectedTrader),d=ci(r),a=await Te(e,n,r,d),c=C(d);if(c!==void 0&&c<=0)throw O(n);let o=ne(r,d);return n.track(a,N(n,r,o,n.expectedTrader))},async waitTerminal(t){ge(n,t);let r=N(n,t,void 0,n.expectedTrader),d=an(r);if(d<=0)throw O(n);let a=on(r),c=k({...r,diagnostics:n.diagnostics()});c.throwIfAborted(s=>v(n,s));let o=await Te(e,n,r,a),u=0;for(;;){c.throwIfAborted(m=>v(n,m));let s=C(a);if(s!==void 0&&s<=0)throw O(n);let f=await sn(n,o,r,a);if(u+=1,Ie(f))return f;if(u>=d)throw O(n);await cn(n,r,a);}},watch(t){ge(n,t);let r=N(n,t,void 0,n.expectedTrader),d=false;return {async*[Symbol.asyncIterator](){if(d)throw new Error("async order lifecycle watch is single-use");d=true;let a=an(r),c=on(r),o=k({...r,diagnostics:n.diagnostics()}),u=0;o.throwIfAborted(m=>v(n,m)),yield {phase:"submitted",hash:e.hash};let s=await fi(e,n,r,c);yield {phase:"mined",hash:e.hash,receipt:s};let f=n.orderIdFromReceipt?.(s)??await Te(e,n,r,c);if(yield {phase:"indexed",hash:e.hash,orderId:f},a<=0)throw O(n);for(;;){o.throwIfAborted(Vn=>v(n,Vn));let m=C(c);if(m!==void 0&&m<=0)throw O(n);let x=await sn(n,f,r,c);u+=1;let Ve=ui(x);if(Ve==="terminal"){yield {phase:"terminal",hash:e.hash,orderId:f,result:x};return}if(Ve==="unknown"?yield {phase:"unknown",hash:e.hash,orderId:f,result:x}:yield {phase:"tracking",hash:e.hash,orderId:f,result:x},u>=a)throw O(n);await cn(n,r,c);}}}}}}function Re(e){return en({...e.initialReceipt!==void 0?{initialReceipt:e.initialReceipt}:{},...e.initialReceiptConfirmations!==void 0?{initialReceiptConfirmations:e.initialReceiptConfirmations}:{},wait:n=>e.wait(e.hash,n),mapAbort:e.mapAbort,mapTimeout:e.mapTimeout})}function mn(e){return {kind:"receipt",hash:e.hash,waitReceipt:Re(e)}}function pn(e){let n=Re(e),i={kind:"async_order",verb:e.verb,hash:e.hash,waitReceipt:n,orderId:async t=>e.orderIdFromReceipt(await n(t))};return e.lifecycle===void 0?i:ln(i,{...e.lifecycle,orderIdFromReceipt:e.orderIdFromReceipt})}function gn(e){let n=Re(e);return {kind:"trigger_order",hash:e.hash,waitReceipt:n,verifiedRef:async i=>e.verifiedRefFromReceipt(await n(i))}}var Ti="trading-track";function b(e){let n={sdkVersion:a$1,sourceTag:Ti,chainId:e.chain.chainId};return e.chain.registryAddress!==void 0&&(n.registryAddress=e.chain.registryAddress),n}function _(e,n,i,t){return {message:n,diagnostics:b(e),...i!==void 0?{hint:i}:{},...t!==void 0?{cause:t}:{}}}function ye(e,n){if(e.api!==void 0)return e;throw new MissingApiClientError(_(e,`${n} requires an API client`,"Create the client with API support."))}function Ii(e,n){if(e.publicClient!==void 0)return e.publicClient;throw new MissingPublicClientError(_(e,`${n} requires a public client`,"Pass publicClient to createDomfiClient."))}function Oe(e,n){throw new AbortError(_(e,"trading tracking was aborted",void 0,n))}function Rn(e,n){return new TimeoutError(_(e,"trading tracking timed out",void 0,n))}function L(e,n){throw Rn(e,n)}function xn(e){return e instanceof AbortError||e instanceof Error&&e.name==="AbortError"?true:typeof e=="object"&&e!==null&&"code"in e&&e.code==="ABORTED"}function hn(e){return e instanceof ReadModelNotReadyError?true:typeof e=="object"&&e!==null&&"code"in e&&(e.code==="READ_MODEL_NOT_READY"||e.code==="API_ORDER_NOT_FOUND")}function Ri(e){return e instanceof TimeoutError||e instanceof Error&&e.name==="WaitForTransactionReceiptTimeoutError"?true:typeof e=="object"&&e!==null&&"code"in e&&e.code==="TIMEOUT"}function V(e,n){n?.aborted===true&&Oe(e,n.reason);}function bn(e,n){let i={};return e?.signal!==void 0&&(i.signal=e.signal),n!==void 0&&(i.timeoutMs=n),e?.readinessPolicy!==void 0&&(i.readinessPolicy=e.readinessPolicy),i}function yn(e,n){let i=n;if(i?.account!==void 0&&i.delegation!==void 0)throw new ValidationError({message:"recovery options cannot include both account and delegation",diagnostics:b(e),hint:"Use account for direct recovery or delegation: { trader } for delegated recovery."});return i?.delegation?.trader??i?.account}function xi(e,n){if(n===void 0)return e;let{account:i,delegation:t,...r}=e??{};return {...r,account:n}}function On(e){return [e?.timeoutMs,e?.maxDurationMs].filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0)}function ke(e){let n=On(e);if(n.length!==0)return Date.now()+Math.min(...n)}function S(e){if(e!==void 0)return e-Date.now()}function hi(e){return e?.maxAttempts!==void 0||e?.maxDurationMs!==void 0||e?.timeoutMs!==void 0}function bi(e){return e?.maxAttempts!==void 0?Math.max(0,e.maxAttempts):On(e).length>0?Number.POSITIVE_INFINITY:1}function ve(e,n){let i=b(e);j$1(n?.intervalMs,i),g$1(n?.timeoutMs,"timeoutMs",i),g$1(n?.maxDurationMs,"maxDurationMs",i),h(n?.maxAttempts,"maxAttempts",i);}function yi(e,n){return i(n?.intervalMs,b(e))}function we(e,n){let i=[];e?.timeoutMs!==void 0&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0&&i.push(e.timeoutMs);let t=S(n);if(t!==void 0&&t>0&&i.push(t),i.length!==0)return Math.max(1,Math.floor(Math.min(...i)))}function ie(e,n){let i=S(n);return i!==void 0&&i<=0&&L(e),i}function kn(e,n,i){ie(e,i);let t=we(n,i);return t===void 0?n:{...n??{},timeoutMs:t}}async function Tn(e,n,i,t){let r=ie(e,i),d=kn(e,n,i);if(r===void 0)return t(d);let a;try{let c=new Promise((o,u)=>{a=setTimeout(()=>u(Rn(e)),Math.max(1,Math.floor(r)));});return await Promise.race([c,t(d)])}finally{a!==void 0&&clearTimeout(a);}}async function Oi(e,n,i){if(V(e,i),n<=0)return;let t;await new Promise((r,d)=>{let a=setTimeout(r,n);t=()=>{clearTimeout(a),d(new AbortError(_(e,"trading tracking was aborted",void 0,i?.reason)));},i?.addEventListener("abort",t,{once:true});}).finally(()=>{t!==void 0&&i?.removeEventListener("abort",t);});}function vn(e,n){let i={order:e};return e.removeCollateral!==void 0&&(i.removeCollateral=e.removeCollateral),n!==void 0&&(i.diagnostics=n),i}function In(e,n){return {...b(e),...n!==void 0?{apiFreshness:n.freshness}:{}}}function ki(e){if(typeof e=="object"&&e!==null&&"diagnostics"in e&&typeof e.diagnostics=="object")return e.diagnostics}function vi(e){return e.terminalTradeId??e.positionRef?.tradeId??e.initiatedTradeId}function xe(e,n){return e$1.toString(e)===e$1.toString(n)}function wi(e,n){return b$1.toNumber(e)===b$1.toNumber(n)}function wn(e,n){return e.toLowerCase()===n.toLowerCase()}function he(e){return e.status==="pending_execution"||e.status==="timeout_available"||e.status==="executed"&&e.action==="open"&&e.positionRef===null}function Ai(e){return e.status==="executed"&&e.action==="open"&&e.positionRef===null}function Ei(e,n){return {wallet:n.wallet,pairIndex:n.pairIndex,index:n.index,tradeId:n.tradeId,chainId:e.chain.chainId,source:"api"}}async function Di(e,n,i,t){if(n.status!=="executed")return {kind:"result",result:n};let r=n.order.positionRef;if(r==null)return {kind:"result",result:n};let d=Ei(e,r),a={...n,positionRef:d},c=S(t);if(c!==void 0&&c<=0)return {kind:"result",result:a};let o;try{o=await e.api.account.position(r.wallet,{pairIndex:r.pairIndex,index:r.index,tradeId:r.tradeId},bn(i,we(i,t)));}catch(s){if(s instanceof TimeoutError||hn(s))return {kind:"result",result:a};throw s}if(o.freshness.isStale)return {kind:"result",result:a};let u=o.data.status==="found"&&o.data.position?.kind==="open_position"?{...o.data.position,verifiedRef:o.data.position.verifiedRef??d}:void 0;if(u!==void 0&&i?.account!==void 0){let s=u.verifiedRef.wallet;if(!wn(s,i.account))return {kind:"result",result:{status:"identity_mismatch",expectedWallet:i.account,actualWallet:s,...vn(n.order,n.diagnostics)}}}return {kind:"result",result:{...a,...u!==void 0?{openedPosition:u}:{}}}}function Pi(e,n,i){let t=n.data,r=vn(t,n.diagnostics??b(e));if(i?.account!==void 0&&!wn(t.wallet,i.account))return {status:"identity_mismatch",expectedWallet:i.account,actualWallet:t.wallet,...r};if(i?.pairIndex!==void 0){let d=t.pairIndex??t.positionRef?.pairIndex;if(d===void 0||!wi(i.pairIndex,d))return {status:"identity_mismatch",expectedPairIndex:i.pairIndex,...d!==void 0?{actualPairIndex:d}:{},...r}}if(i?.initiatedTradeId!==void 0){let d=t.initiatedTradeId;if(d!==void 0?!xe(i.initiatedTradeId,d):!he(t))return {status:"identity_mismatch",expectedTradeId:i.initiatedTradeId,...d!==void 0?{actualTradeId:d}:{},...r}}if(i?.terminalTradeId!==void 0){let d=t.terminalTradeId??t.positionRef?.tradeId;if(d!==void 0?!xe(i.terminalTradeId,d):!he(t))return {status:"identity_mismatch",expectedTradeId:i.terminalTradeId,...d!==void 0?{actualTradeId:d}:{},...r}}if(i?.expectedTradeId!==void 0){let d=vi(t);if(d!==void 0?!xe(i.expectedTradeId,d):!he(t))return {status:"identity_mismatch",expectedTradeId:i.expectedTradeId,...d!==void 0?{actualTradeId:d}:{},...r}}switch(t.status){case "pending_execution":return {status:"pending_execution",...r};case "executed":return {status:"executed",...r};case "canceled":return {status:"canceled",...r};case "timeout_available":return {status:"timeout_available",canHandleTimeout:t.timeoutAvailable===true,...r};case "timed_out":return {status:"timed_out",...r};case "unknown":return {status:"unknown",order:t,...t.removeCollateral!==void 0?{removeCollateral:t.removeCollateral}:{},...r.diagnostics!==void 0?{diagnostics:r.diagnostics}:{}}}}async function An(e,n,i,t){try{let r=await e.api.orders.get(n,bn(i,we(i,t)));if(r.freshness.isStale&&i?.readinessPolicy!=="ignore")return {kind:"lag",diagnostics:In(e,r)};let d=Pi(e,r,i);return d.status==="identity_mismatch"?{kind:"result",result:d}:Ai(r.data)?{kind:"lag",diagnostics:In(e,r)}:Di(e,d,i,t)}catch(r){if(r instanceof TimeoutError)throw r;if((xn(r)||i?.signal?.aborted===true)&&Oe(e,r),hn(r))return {kind:"lag",diagnostics:ki(r)??b(e)};throw r}}async function Ae(e,n,i){let t=ye(e,"trading.trackOrder");ve(e,i);let r=ke(i),d=bi(i),a=yi(e,i),c=hi(i),o=0;for(V(e,i?.signal),d<=0&&L(e);;){V(e,i?.signal);let u=S(r);u!==void 0&&u<=0&&L(e),o+=1;let s=await An(t,n,i,r);if(s.kind==="result")return s.result;if(!c)return {status:"unknown",diagnostics:s.diagnostics??b(e)};o>=d&&L(e);let f=S(r);f!==void 0&&f<=0&&L(e),await Oi(e,Math.min(a,f??a),i?.signal);}}async function En(e,n,i){let t=ye(e,"trading.trackOrder");ve(e,i);let r=ke(i);V(e,i?.signal);let d=await An(t,n,i,r);return d.kind==="result"?d.result:{status:"unknown",diagnostics:d.diagnostics??b(e)}}async function Mi(e,n,i){V(e,i?.signal);let t=yn(e,i),r=Ii(e,"trading.recoverTransaction"),d;try{d=await $(r,n,i,e.chain);}catch(a){throw (xn(a)||i?.signal?.aborted===true)&&Oe(e,a),Ri(a)&&L(e,a),a}return Dn(e,d,{...i,...t!==void 0?{expectedTrader:t}:{}})}async function Pt(e,n,i){ye(e,"trading.trackTransaction"),ve(e,i);let t=yn(e,i),r=ke(i),d=await Tn(e,i,r,o=>Mi(e,n,o));if(ie(e,r),d.kind!=="async_order")return {status:"unknown",diagnostics:b(e)};let a=xi(i,t),c=await Tn(e,a,r,o=>d.orderId(o));return ie(e,r),Ae(e,c,kn(e,a,r))}var Wi="trading-receipts",Pn="0x0000000000000000000000000000000000000000",Ln=/^(?:0|[1-9]\d*)$/;function q(e,n){let i={sdkVersion:a$1,sourceTag:Wi,chainId:e};return n?.chain.registryAddress!==void 0&&(i.registryAddress=n.chain.registryAddress),i}function l(e,n=0,i,t){throw new A.ValidationError({message:e,diagnostics:q(n,i),...t!==void 0?{cause:t}:{}})}function g(e,n,i){throw new A.IdentityMismatchError({message:e,diagnostics:q(n,i)})}function Ce(e,n,i,t){return new A.AbortError({message:e,diagnostics:q(n,i),...t!==void 0?{cause:t}:{}})}function Le(e,n,i,t){return new A.TimeoutError({message:e,diagnostics:q(n,i),...t!==void 0?{cause:t}:{}})}function R(e,n){let i=a.DomfiTrading.find(t=>{let r=t;return r.type==="event"&&r.name===e&&(n===void 0||n(r))});return i===void 0?l(`DomfiTrading ABI is missing ${e} event`):i}var I={marketOpen:R("MarketOpenOrderInitiated"),marketClose:R("MarketCloseOrderInitiated"),removeCollateral:R("RemoveCollateralInitiated"),openTriggerPlaced:R("OpenLimitPlaced",e=>e.inputs.some(n=>n.name==="order")),tpUpdated:R("TpUpdated"),slUpdated:R("SlUpdated"),topUpCollateral:R("TopUpCollateralExecuted"),openLimitUpdated:R("OpenLimitUpdated"),openLimitCanceled:R("OpenLimitCanceled"),marketOpenTimeout:R("MarketOpenTimeoutExecuted"),marketCloseTimeout:R("MarketCloseTimeoutExecuted")},De={openMarket:I.marketOpen,closeMarket:I.marketClose,removeCollateral:I.removeCollateral},re={updateTakeProfit:[I.tpUpdated],updateStopLoss:[I.slUpdated],topUpCollateral:[I.topUpCollateral],updateOpenLimitOrder:[I.openLimitUpdated],cancelOpenLimitOrder:[I.openLimitCanceled],handleTradeMarketTimeout:[I.marketOpenTimeout,I.marketCloseTimeout]},Pe={updateTakeProfit:{wallet:["trader",1],pairIndex:["pairIndex",2],tradeId:["tradeId",0],index:["index",3]},updateStopLoss:{wallet:["trader",1],pairIndex:["pairIndex",2],tradeId:["tradeId",0],index:["index",3]},topUpCollateral:{wallet:["trader",1],pairIndex:["pairIndex",2],tradeId:["tradeId",0]},updateOpenLimitOrder:{wallet:["trader",0],pairIndex:["pairIndex",1],index:["index",2]},cancelOpenLimitOrder:{wallet:["trader",0],pairIndex:["pairIndex",1],index:["index",2]}};function Fi(e){return e==="openMarket"||e==="closeMarket"||e==="removeCollateral"}function Ni(e){return e==="updateTakeProfit"||e==="updateStopLoss"||e==="topUpCollateral"||e==="updateOpenLimitOrder"||e==="cancelOpenLimitOrder"||e==="handleTradeMarketTimeout"}function Vi(e){return toEventSelector(e).toLowerCase()}function Si(e){return e.topics[0]?.toLowerCase()}function _i(e){if(e===a$3.chainId)return a$3.contracts.DomfiTrading;if(e===b$2.chainId)return b$2.contracts.DomfiTrading}function ae(e){return e.chain.contracts.DomfiTrading}function w(e){let n=ae(e);return {chainId:e.chain.chainId,...n!==void 0?{expectedTradingAddress:n}:{},deps:e}}function $i(e,n,i){if(Si(e)!==Vi(n))return false;if(i===void 0)return true;let t=P(e.address);return t!==void 0&&B(t,i)}function ji(e,n,i,t){let r=d$1(e.data,"receipt log data",(d,a)=>l(d,i,t,a));try{return decodeEventLog({abi:[n],data:r,topics:e.topics,strict:!0}).args}catch(d){return l(`receipt log for ${n.name} could not be decoded`,i,t,d)}}function D(e,n,i){for(let t of e.logs)if($i(t,n,i.expectedTradingAddress))return {log:t,args:ji(t,n,i.chainId,i.deps)}}function Bi(e,n,i,t){let r=D(e,n,t);return r!==void 0?r:l(i,t.chainId,t.deps)}function p(e,n,i){if(Array.isArray(e))return e[i];if(typeof e=="object"&&e!==null&&n in e)return e[n]}function y(e){if(typeof e=="number"&&Number.isInteger(e))return e;if(typeof e=="bigint"&&e>=0n&&e<=BigInt(Number.MAX_SAFE_INTEGER))return Number(e)}function H(e){if(typeof e=="bigint")return e;if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return BigInt(e)}function P(e){return a$2(e)?e:void 0}function B(e,n){return e.toLowerCase()===n.toLowerCase()}function E(e,n){return p(e,n[0],n[1])}function Ui(e,n,i,t){typeof i.logIndex!="number"&&l(`${e.name} logIndex is missing from receipt evidence`,t.chain.chainId,t);let r=i.blockNumber??n.blockNumber;return r!==void 0&&typeof r!="bigint"&&l(`${e.name} blockNumber is malformed in receipt evidence`,t.chain.chainId,t),{eventName:e.name,transactionHash:z(n,i,t.chain.chainId,t),logIndex:i.logIndex,...r!==void 0?{blockNumber:r}:{}}}function Me(e,n,i,t,r){e!==void 0&&B(e,n)||g(i,t,r);}function U(e,n,i,t,r){e!==n&&g(i,t,r);}function j(e,n,i,t,r){let d=e$1.toString(n);Ln.test(d)||l("receipt tradeId evidence cannot prove non-decimal TradeId",t,r),!(e!==void 0&&e.toString()===d)&&g(i,t,r);}function qi(e){return Ln.test(e$1.toString(e))}function zi(e,n){return b$1.toNumber(e)===b$1.toNumber(n)}function Mn(e,n){return e$1.toString(e)===e$1.toString(n)}function Ee(e,n){return l(`tracking ${n} conflicts with the recovered transaction identity`,e.chain.chainId,e)}function Cn(e,n,i){if(n===void 0)return i;let t={...i??{}};if(n.pairIndex!==void 0){let r=i?.pairIndex;r!==void 0&&!zi(r,n.pairIndex)&&Ee(e,"pairIndex"),t.pairIndex=n.pairIndex;}if(n.initiatedTradeId!==void 0){let r=i?.initiatedTradeId;r!==void 0&&!Mn(r,n.initiatedTradeId)&&Ee(e,"initiatedTradeId"),t.initiatedTradeId=n.initiatedTradeId;}if(n.terminalTradeId!==void 0){let r=i?.terminalTradeId;r!==void 0&&!Mn(r,n.terminalTradeId)&&Ee(e,"terminalTradeId"),t.terminalTradeId=n.terminalTradeId;}return t}function Ki(e){if(!(e.pairIndex===void 0&&e.initiatedTradeId===void 0&&e.terminalTradeId===void 0))return {...e.pairIndex!==void 0?{pairIndex:e.pairIndex}:{},...e.initiatedTradeId!==void 0?{initiatedTradeId:e.initiatedTradeId}:{},...e.terminalTradeId!==void 0?{terminalTradeId:e.terminalTradeId}:{}}}function He(e,n,i){if(i!==void 0){if(n==="closeMarket"||n==="removeCollateral"){if(qi(i))return i;if(e.api!==void 0)return}if(e.api===void 0)return l(`${n} receipt recovery cannot prove initiatedTradeId without API tracking evidence`,e.chain.chainId,e)}}function de(e,n,i){n!==void 0&&(e.api!==void 0&&i==="async_order"||l(`${i} receipt recovery cannot prove terminalTradeId`,e.chain.chainId,e));}function z(e$1,n,i=0,t){let r=e$1.transactionHash??n?.transactionHash;return e(r,"receipt transactionHash",(d,a)=>l(d,i,t,a))}function Yi(e,n,i,t){let r=n.blockNumber??e.blockNumber,d=n.transactionIndex??e.transactionIndex,a=n.logIndex;return typeof r!="bigint"||typeof d!="number"||typeof a!="number"?l("trigger placement receipt log is missing log coordinates",i,t):{blockNumber:r,transactionIndex:d,logIndex:a}}function Gi(e){if(e===1)return "limit";if(e===2)return "stop"}function Xi(e,n,i){let t=H(e);return t===void 0?l("receipt log is missing orderId",n,i):f.parse(t.toString())}function Zi(e,n,i){try{return b$1.from(e)}catch(t){return l("receipt log pairIndex is out of range",n,i,t)}}function Ji(e,n,i){try{return d.from(e)}catch(t){return l("receipt log trigger index is out of range",n,i,t)}}async function $(e$1,n,i,t){Z(i,t);let r=e(n,"transaction hash",(u,s)=>l(u,t?.chainId??0,void 0,s));typeof e$1.waitForTransactionReceipt!="function"&&l("public client is missing waitForTransactionReceipt",t?.chainId??0);let d=e$1.waitForTransactionReceipt,a=Ge(t,i?.pollingIntervalMs),c=i?.timeoutMs===0?0:X(i?.timeoutMs,t),o=Date.now();return Ze(e$1,r,({queued:u})=>{let s=c;if(u&&c!==void 0&&c>0){let f=c-(Date.now()-o);if(f<=0)throw new WaitForTransactionReceiptTimeoutError({hash:r});s=f;}return d({hash:r,pollingInterval:a,...i?.confirmations!==void 0?{confirmations:i.confirmations}:{},...s!==void 0?{timeout:s}:{},...i?.signal!==void 0?{signal:i.signal}:{}})},i?.signal)}function We(e,n={}){let i=n.chainId??n.deps?.chain.chainId??0,t=n.verb===void 0?Object.values(De):Fi(n.verb)?[De[n.verb]]:[];for(let r of t){let d=D(e,r,{chainId:i,...n.expectedTradingAddress!==void 0?{expectedTradingAddress:n.expectedTradingAddress}:{},...n.deps!==void 0?{deps:n.deps}:{}});if(d!==void 0){if(n.expectedTrader!==void 0){let a=P(p(d.args,"trader",1));if(a===void 0)return l("async order log is missing trader",i,n.deps);if(!B(a,n.expectedTrader))return g("async order trader does not match expected trader",i,n.deps)}if(n.expectedPairIndex!==void 0){let a=y(p(d.args,"pairIndex",2));U(a,b$1.toNumber(n.expectedPairIndex),"async order pairIndex does not match expected pair",i,n.deps);}if(n.expectedTradeId!==void 0){let a=H(p(d.args,"tradeId",1));if(a===void 0)return l("async order log does not expose a tradeId",i,n.deps);j(a,n.expectedTradeId,"async order tradeId does not match expected trade",i,n.deps);}return Xi(p(d.args,"orderId",0),i,n.deps)}}return l("receipt does not contain an async order initiation log",i,n.deps)}function Fe(e,n){let i=n.expectedTradingAddress??_i(n.chainId),t=Bi(e,I.openTriggerPlaced,"receipt does not contain an open trigger placement log",{chainId:n.chainId,...i!==void 0?{expectedTradingAddress:i}:{},...n.deps!==void 0?{deps:n.deps}:{}}),r=P(p(t.args,"trader",0)),d=y(p(t.args,"pairIndex",1)),a=y(p(t.args,"index",2)),c=p(t.args,"order",3),o=P(p(c,"trader",0)),u=y(p(c,"pairIndex",8)),s=y(p(c,"index",9)),f=y(p(c,"orderType",11));if(r===void 0||r===Pn||d===void 0||a===void 0||o===void 0||o===Pn||u===void 0||s===void 0||f===void 0)return l("trigger placement log is missing required identity proof",n.chainId);if(!B(r,o))return g("trigger placement log does not prove wallet identity",n.chainId);if(d!==u)return g("trigger placement log does not prove pair identity",n.chainId);if(a!==s)return g("trigger placement log does not prove index identity",n.chainId);if(n.expectedWallet!==void 0&&!B(r,n.expectedWallet))return g("trigger placement wallet does not match expected wallet",n.chainId);let m=Gi(f);return m===void 0?g("trigger placement log does not prove a limit or stop order type",n.chainId):n.expectedOrderType!==void 0&&m!==n.expectedOrderType?g("trigger placement order type does not match expected order type",n.chainId):n.expectedPairIndex!==void 0&&d!==b$1.toNumber(n.expectedPairIndex)?g("trigger placement pairIndex does not match expected pair",n.chainId):{wallet:r,pairIndex:Zi(d,n.chainId),index:Ji(a,n.chainId),chainId:n.chainId,orderType:m,initiatedTxHash:z(e,t.log,n.chainId,n.deps),initiatedLog:Yi(e,t.log,n.chainId),source:"receipt"}}function Ne(e){return e.publicClient!==void 0?e.publicClient:l("recovered transaction handles require a public client",e.chain.chainId,e)}function Hn(e,n,i){let t=z(n,void 0,e.chain.chainId,e);return mn({hash:t,initialReceipt:n,...i!==void 0?{initialReceiptConfirmations:i}:{},wait:(r,d)=>$(Ne(e),r,d,e.chain),mapAbort:r=>Ce("receipt wait was aborted",e.chain.chainId,e,r),mapTimeout:r=>Le("receipt wait timed out",e.chain.chainId,e,r)})}function Wn(e,n,i,t,r,d={}){let a=z(n,void 0,e.chain.chainId,e),c=He(e,i,d.initiatedTradeId),o=s=>We(s,{verb:i,...w(e),...r!==void 0?{expectedTrader:r}:{},...d.pairIndex!==void 0?{expectedPairIndex:d.pairIndex}:{},...c!==void 0?{expectedTradeId:c}:{}}),u=Ki(d);return pn({hash:a,verb:i,initialReceipt:n,...t!==void 0?{initialReceiptConfirmations:t}:{},wait:(s,f)=>$(Ne(e),s,f,e.chain),mapAbort:s=>Ce("receipt wait was aborted",e.chain.chainId,e,s),mapTimeout:s=>Le("receipt wait timed out",e.chain.chainId,e,s),orderIdFromReceipt:o,...e.api===void 0?{}:{lifecycle:{diagnostics:()=>q(e.chain.chainId,e),...r!==void 0?{expectedTrader:r}:{},track:async(s,f)=>Ae(e,s,Cn(e,u,f)),trackOnce:async(s,f)=>En(e,s,Cn(e,u,f))}}})}function Fn(e,n,i,t,r,d){let a=z(n,void 0,e.chain.chainId,e);return gn({hash:a,initialReceipt:n,...r!==void 0?{initialReceiptConfirmations:r}:{},wait:(c,o)=>$(Ne(e),c,o,e.chain),mapAbort:c=>Ce("receipt wait was aborted",e.chain.chainId,e,c),mapTimeout:c=>Le("receipt wait timed out",e.chain.chainId,e,c),verifiedRefFromReceipt:c=>{let o=ae(e);return Fe(c,{chainId:e.chain.chainId,...i!==void 0?{expectedOrderType:i}:{},...t!==void 0?{expectedWallet:t}:{},...d!==void 0?{expectedPairIndex:d}:{},...o!==void 0?{expectedTradingAddress:o}:{},deps:e})}})}function Nn(e,n,i,t,r,d,a){Ni(i)||l(`receipt-only recovery does not support ${i}`,e.chain.chainId,e);let c=re[i];for(let o of c){let u=D(n,o,w(e));if(u!==void 0){if(i==="handleTradeMarketTimeout"&&(t!==void 0||r!==void 0||d!==void 0||a!==void 0)){let s=p(u.args,"order",o.name==="MarketCloseTimeoutExecuted"?2:1),f=p(s,"trade",3),m=P(p(f,"trader",4)),x=y(p(f,"pairIndex",6));t!==void 0&&Me(m,t,`${o.name} wallet does not match expected trader`,e.chain.chainId,e),r!==void 0&&U(x,b$1.toNumber(r),`${o.name} pairIndex does not match expected pair`,e.chain.chainId,e),d!==void 0&&(o.name!=="MarketCloseTimeoutExecuted"&&l(`${o.name} does not expose a tradeId`,e.chain.chainId,e),j(H(p(u.args,"tradeId",1)),d,`${o.name} tradeId does not match expected trade`,e.chain.chainId,e)),a!==void 0&&(o.name!=="MarketCloseTimeoutExecuted"&&l(`${o.name} does not expose a terminalTradeId`,e.chain.chainId,e),j(H(p(u.args,"tradeId",1)),a,`${o.name} terminalTradeId does not match expected trade`,e.chain.chainId,e));}else if(t!==void 0){let s=Pe[i],f=P(E(u.args,s.wallet));Me(f,t,`${o.name} wallet does not match expected trader`,e.chain.chainId,e);}if(i!=="handleTradeMarketTimeout"){let s=Pe[i];r!==void 0&&U(y(E(u.args,s.pairIndex)),b$1.toNumber(r),`${o.name} pairIndex does not match expected pair`,e.chain.chainId,e),d!==void 0&&(s.tradeId===void 0&&l(`${o.name} does not expose a tradeId`,e.chain.chainId,e),j(H(E(u.args,s.tradeId)),d,`${o.name} tradeId does not match expected trade`,e.chain.chainId,e)),a!==void 0&&l(`${o.name} does not expose a terminalTradeId`,e.chain.chainId,e);}return}}l(`receipt does not contain a ${i} completion log`,e.chain.chainId,e);}function jt(e,n,i){let t=i.verb;t==="handleTradeMarketTimeout"&&l("market timeout receipts are not action receipt-only evidence",e.chain.chainId,e);let r=Pe[t],d$1=re[t];for(let a of d$1){let c=D(n,a,w(e));if(c===void 0)continue;let o=c.args,u=P(E(o,r.wallet)),s=y(E(o,r.pairIndex));if(Me(u,i.expected.wallet,`${a.name} wallet does not match expected action wallet`,e.chain.chainId,e),U(s,b$1.toNumber(i.expected.pairIndex),`${a.name} pairIndex does not match expected action pair`,e.chain.chainId,e),r.tradeId!==void 0&&!("tradeId"in i.expected)&&l(`${a.name} requires expected tradeId evidence`,e.chain.chainId,e),"tradeId"in i.expected&&(r.tradeId===void 0&&g(`${a.name} does not expose a tradeId`,e.chain.chainId,e),j(H(E(o,r.tradeId)),i.expected.tradeId,`${a.name} tradeId does not match expected action trade`,e.chain.chainId,e)),r.index!==void 0&&!("index"in i.expected)&&l(`${a.name} requires expected index evidence`,e.chain.chainId,e),"index"in i.expected){r.index===void 0&&g(`${a.name} does not expose an index`,e.chain.chainId,e);let f=y(E(o,r.index)),m=typeof i.expected.index=="number"?i.expected.index:d.toNumber(i.expected.index);U(f,m,`${a.name} index does not match expected action index`,e.chain.chainId,e);}return Ui(a,n,c.log,e)}l(`receipt does not contain a ${t} completion log`,e.chain.chainId,e);}function Qi(e,n,i,t={}){for(let d of ["openMarket","closeMarket","removeCollateral"]){let a=De[d];if(D(n,a,w(e))!==void 0){de(e,t.terminalTradeId,"async_order");let c=He(e,d,t.initiatedTradeId);return We(n,{verb:d,...w(e),...t.expectedTrader!==void 0?{expectedTrader:t.expectedTrader}:{},...t.pairIndex!==void 0?{expectedPairIndex:t.pairIndex}:{},...c!==void 0?{expectedTradeId:c}:{}}),Wn(e,n,d,i,t.expectedTrader,t)}}if(D(n,I.openTriggerPlaced,w(e))!==void 0){t.initiatedTradeId!==void 0&&l("trigger placement receipt recovery cannot prove initiatedTradeId",e.chain.chainId,e),de(e,t.terminalTradeId,"trigger placement");let d=ae(e);return Fe(n,{chainId:e.chain.chainId,...t.expectedTrader!==void 0?{expectedWallet:t.expectedTrader}:{},...t.pairIndex!==void 0?{expectedPairIndex:t.pairIndex}:{},...d!==void 0?{expectedTradingAddress:d}:{},deps:e}),Fn(e,n,void 0,t.expectedTrader,i,t.pairIndex)}for(let d of Object.keys(re))if(re[d].some(c=>D(n,c,w(e))))return Nn(e,n,d,t.expectedTrader,t.pairIndex,t.initiatedTradeId,t.terminalTradeId),Hn(e,n,i);return l("receipt does not contain a supported DomFi trading event",e.chain.chainId,e)}function Dn(e,n,i={}){let t=i.expectedTrader??i.account,r={...t!==void 0?{expectedTrader:t}:{},...i.pairIndex!==void 0?{pairIndex:i.pairIndex}:{},...i.initiatedTradeId!==void 0?{initiatedTradeId:i.initiatedTradeId}:{},...i.terminalTradeId!==void 0?{terminalTradeId:i.terminalTradeId}:{}};switch(i.verb){case "openMarket":case "closeMarket":case "removeCollateral":{de(e,i.terminalTradeId,"async_order");let d=He(e,i.verb,i.initiatedTradeId);return We(n,{verb:i.verb,...w(e),...t!==void 0?{expectedTrader:t}:{},...i.pairIndex!==void 0?{expectedPairIndex:i.pairIndex}:{},...d!==void 0?{expectedTradeId:d}:{}}),Wn(e,n,i.verb,i.confirmations,t,r)}case "openLimit":case "openStop":{i.initiatedTradeId!==void 0&&l("trigger placement receipt recovery cannot prove initiatedTradeId",e.chain.chainId,e),de(e,i.terminalTradeId,"trigger placement");let d=i.verb==="openLimit"?"limit":"stop",a=ae(e);return Fe(n,{chainId:e.chain.chainId,expectedOrderType:d,...t!==void 0?{expectedWallet:t}:{},...i.pairIndex!==void 0?{expectedPairIndex:i.pairIndex}:{},...a!==void 0?{expectedTradingAddress:a}:{},deps:e}),Fn(e,n,d,t,i.confirmations,i.pairIndex)}case "updateTakeProfit":case "updateStopLoss":case "topUpCollateral":case "updateOpenLimitOrder":case "cancelOpenLimitOrder":case "handleTradeMarketTimeout":return Nn(e,n,i.verb,t,i.pairIndex,i.initiatedTradeId,i.terminalTradeId),Hn(e,n,i.confirmations);case void 0:return Qi(e,n,i.confirmations,r)}return l("receipt recovery does not support this trading verb",e.chain.chainId,e)}export{Z as a,Ge as b,Ze as c,en as d,ee as e,nn as f,rn as g,ni as h,mt as i,pt as j,oi as k,ht as l,mn as m,pn as n,gn as o,Ae as p,En as q,Mi as r,Pt as s,$ as t,We as u,Fe as v,jt as w,it as x,tt as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {d,c,b as b$1,i as i$1,e,j as j$1,h,a,f as f$1}from'./chunk-SZE5DE54.js';import {k,p,g,m,i,q,t,r,s,n}from'./chunk-C5Y2WM7C.js';import {UsdP6}from'@domfi/sdk/units';function v(e,t){return t===void 0?{status:"ok",code:e}:{status:"ok",code:e,message:t}}function U(e,t){return {status:"violation",code:e,severity:"error",message:t}}function H(e){let t=k.toRaw(e.leverage),r=k.toRaw(e.minLeverage),n=k.toRaw(e.maxLeverage);return t<r?U("leverage_below_min","leverage is below market minimum"):t>n?U("leverage_above_max","leverage is above market maximum"):v("leverage_bounds")}function J(e){let t=p.toRaw(e.notionalUsd),r=g.toRaw(e.minPositionSize);return t<r?U("position_size_below_min","position size is below market minimum"):v("minimum_position_size")}function K(e){return g.toRaw(e.collateral)>g.toRaw(e.maxAllowedCollateral)?U("collateral_above_max","collateral is above market maximum"):v("max_collateral")}function Q(e){let t=m.toRaw(e.currentSideOi)*i.toRaw(e.price)/d,r=p.toRaw(e.requestedNotional)*c,n=p.toRaw(e.oiCap)*c;return t+r>n?U("oi_cap_exceeded","open interest cap would be exceeded"):v("oi_cap")}function Y(e){return e.currentGroupCollateral===void 0?{status:"unchecked",code:"group_collateral_cap",reason:"missing_group_collateral"}:g.toRaw(e.currentGroupCollateral)+g.toRaw(e.requestedCollateral)>g.toRaw(e.groupMaxCollateral)?U("group_collateral_cap_exceeded","group collateral cap would be exceeded"):v("group_collateral_cap")}function Z(e){let t$1=q.toRaw(e.slippage),r=t.toRaw(e.maxSlP)*100n;return t$1>r?U("slippage_above_max","slippage is above market maximum"):v("slippage_bounds")}function ee(e){return r.toRaw(e.closePercent),v("close_percent_bounds")}function ae(e){let t=g.toRaw(e.collateral),r=k.toRaw(e.leverage),n=s.toRaw(e.feeP);if(t<0n)throw new Error("collateral must be non-negative");if(r<=0n)throw new Error("leverage must be positive");if(n<0n)throw new Error("feeP must be non-negative");let o=t*r/a;return g.fromRaw(o*n/b$1/100n)}function ie(e){let t=n.toRaw(e.tradeSize),r=n.toRaw(e.oiDelta),n$1=k.toRaw(e.leverage),o=s.toRaw(e.makerFeeP),i=s.toRaw(e.takerFeeP),l=k.toRaw(e.makerMaxLeverage);if(o<0n)throw new Error("makerFeeP must be non-negative");if(i<0n)throw new Error("takerFeeP must be non-negative");let g$1=0n,m=0n;return r*t<0n&&n$1<=l?r*(r+t)>=0n?g$1=i$1(t):(g$1=i$1(r),m=i$1(r+t)):m=i$1(t),g.fromRaw((o*g$1+i*m)/b$1/100n)}function pe(e$1){let t=i.toRaw(e$1.price);if(t===0n)return {priceAfterImpact:i.fromRaw(0n),priceImpactP:0n};let r=m.toRaw(e$1.oiLong)*t/d/c,n=m.toRaw(e$1.oiShort)*t/d/c,o=g.toRaw(e$1.collateral)*k.toRaw(e$1.leverage)/100n;e$1.isOpen?e$1.isLong?r=r+o:n=n+o:e$1.isLong?r=r>=o?r-o:0n:n=n>=o?n-o:0n;let i$2=r+n,l=i$2>0n?(r-n)/i$2:0n,g$1=e*((d+i$1(l)*c)/d),m$1=j$1(t,g$1,d),F=e$1.isOpen?e$1.isLong?t+m$1:t-m$1:e$1.isLong?t-m$1:t+m$1,O=i$1(t-F)*100000000000000000000n/t;return {priceAfterImpact:i.fromRaw(F),priceImpactP:O}}var A=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,B=/^(?:0|[1-9]\d*)$/;function z(e,t,r){if(e.startsWith("-")||e.startsWith("+"))throw new Error(`${r} must be unsigned`);if(!A.test(e))throw new Error(`invalid ${r}`);let[n="0",o=""]=e.split(".");if(o.length>t)throw new Error(`too many fractional digits: expected ${t}`);let i=10n**BigInt(t),l=o.length===0?0n:BigInt(o.padEnd(t,"0"));return BigInt(n)*i+l}function G(e,t){if(typeof e=="string"&&!B.test(e))throw new Error(`invalid ${t} raw integer`);let r=typeof e=="bigint"?e:BigInt(e);if(r<0n)throw new Error(`${t} must be unsigned`);return r}var R={fromRaw(e){return G(e,"percent")},fromDecimal(e){return z(e,6,"percent")},toRaw(e){return e},toRawString(e){return e.toString()}},y=UsdP6;function de(e){if(typeof e=="bigint")return R.fromRaw(e);let t=e.endsWith("%")?e.slice(0,-1):e;return R.fromDecimal(t)}function Re(e){let t=g.toRaw(e.collateral),r=k.toRaw(e.leverage);return h(r,"leverage"),y.fromRaw(t*r/a)}function xe(e){let t=y.toRaw(e.notionalUsd),r=k.toRaw(e.leverage);return h(r,"leverage"),g.fromRaw(j$1(t,a,r))}function j(e){return e<0n?-e:e}function M(e){if(e<0n)throw new Error("price underflow");return i.fromRaw(e)}function b(e){if(e<=0n)throw new Error("computed trigger price must be positive");return i.fromRaw(e)}function f(e){if(e==="long")return true;if(e==="short")return false;throw new Error("direction must be long or short")}function D(e){let t=i.toRaw(e.openPrice),r=i.toRaw(e.currentPrice),n=k.toRaw(e.leverage),o=k.toRaw(e.initialLeverage);h(t,"openPrice"),h(n,"leverage"),h(o,"initialLeverage");let i$1=n>o?n:o,l=f$1*b$1*n/i$1,m=(e.buy?r-t:t-r)*b$1*n/t;return {pRaw:m>l?l:m,maxPnlPRaw:l}}function be(e){let t=i.toRaw(e.basePrice),r=k.toRaw(e.leverage);h(t,"basePrice"),h(r,"leverage");let n=t*R.toRaw(e.pnlPercent)/b$1/r,o=f(e.direction);return b(o?t+n:n<=t?t-n:0n)}function ke(e){let t=i.toRaw(e.basePrice),r=k.toRaw(e.leverage);h(t,"basePrice"),h(r,"leverage");let n=t*R.toRaw(e.pnlPercent)/b$1/r,o=f(e.direction);return b(o?n<=t?t-n:0n:t+n)}function Se(e){let t=i.toRaw(e.basePrice);h(t,"basePrice");let r=t*R.toRaw(e.priceDeltaPercent)/(100n*b$1),n=f(e.direction);return b(n?t+r:r<=t?t-r:0n)}function ye(e){let t=i.toRaw(e.basePrice);h(t,"basePrice");let r=t*R.toRaw(e.priceDeltaPercent)/(100n*b$1),n=f(e.direction);return b(n?r<=t?t-r:0n:t+r)}function $(e){let t=i.toRaw(e.openPrice),r=k.toRaw(e.leverage),n=k.toRaw(e.initialLeverage);h(t,"openPrice"),h(r,"leverage"),h(n,"initialLeverage");let o=r>n?r:n,i$1=f$1*b$1*r/o;return i.fromRaw(t*i$1/b$1/r)}function V(e){let t$1=i.toRaw(e.openPrice),r=k.toRaw(e.leverage);return h(t$1,"openPrice"),h(r,"leverage"),i.fromRaw(t$1*t.toRaw(e.maxSlP)/r)}function De(e){let t=i.toRaw(e.openPrice),r=i.toRaw(e.takeProfit),n=k.toRaw(e.leverage),o=f(e.direction),{pRaw:i$1,maxPnlPRaw:l}=D({openPrice:e.openPrice,currentPrice:e.takeProfit,buy:o,leverage:e.leverage,initialLeverage:e.initialLeverage});if(r===0n||i$1===l){let g=t*j(l)/b$1/n;return M(o?t+g:g<=t?t-g:0n)}return e.takeProfit}function Fe(e){let t$1=i.toRaw(e.openPrice),r=t.toRaw(e.maxSlP),n=k.toRaw(e.leverage),o=i.toRaw(e.stopLoss),i$1=f(e.direction),{pRaw:l}=D({openPrice:e.openPrice,currentPrice:e.stopLoss,buy:i$1,leverage:e.leverage,initialLeverage:e.initialLeverage});if(o>0n&&l<r*b$1*-1n){let g=t$1*r/n;return M(i$1?t$1-g:t$1+g)}return e.stopLoss}function Te(e){let t$1=t.toRaw(e.maxSlP),r=i.toRaw(e.stopLoss),n=f(e.direction),{pRaw:o}=D({openPrice:e.openPrice,currentPrice:e.stopLoss,buy:n,leverage:e.leverage,initialLeverage:e.initialLeverage});return r>0n&&o<t$1*b$1*-1n?i.fromRaw(0n):e.stopLoss}function Ee(e){let t=i.toRaw(e.openPrice),r=k.toRaw(e.leverage),n=k.toRaw(e.initialLeverage);h(t,"openPrice"),h(r,"leverage"),h(n,"initialLeverage");let o=f(e.direction);if(e.takeProfit!==void 0){let i$1=i.toRaw(e.takeProfit);if(i$1!==0n){if(o?i$1<=t:i$1>=t)return {status:"violation",code:"tp_wrong_side",message:"take profit is on the wrong side of open price"};let l=i.toRaw($(e));if(o?i$1>t+l:i$1<t-l)return {status:"violation",code:"tp_exceeds_max_distance",message:"take profit exceeds max gain distance"}}}if(e.stopLoss!==void 0){let i$1=i.toRaw(e.stopLoss);if(i$1!==0n){if(o?i$1>=t:i$1<=t)return {status:"violation",code:"sl_wrong_side",message:"stop loss is on the wrong side of open price"};let l=i.toRaw(V(e));if(o?i$1<t-l:i$1>t+l)return {status:"violation",code:"sl_exceeds_max_distance",message:"stop loss exceeds max loss distance"}}}return {status:"ok"}}export{H as a,J as b,K as c,Q as d,Y as e,Z as f,ee as g,ae as h,ie as i,pe as j,R as k,y as l,de as m,Re as n,xe as o,be as p,ke as q,Se as r,ye as s,$ as t,V as u,De as v,Fe as w,Te as x,Ee as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-D5VE2O4F.js';import {ValidationError}from'@domfi/sdk/errors';var B=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|([+-])(\d{2}):(\d{2}))$/;function i(n,t){let r=n.charCodeAt(t);return r>=48&&r<=57}function s(n,t,r){return Number(n.slice(t,r))}function H(n){return n%4===0&&(n%100!==0||n%400===0)}function N(n,t){return t===2?H(n)?29:28:t===4||t===6||t===9||t===11?30:31}function L(n){return n.length===24&&n[4]==="-"&&n[7]==="-"&&n[10]==="T"&&n[13]===":"&&n[16]===":"&&n[19]==="."&&n[23]==="Z"&&i(n,0)&&i(n,1)&&i(n,2)&&i(n,3)&&i(n,5)&&i(n,6)&&i(n,8)&&i(n,9)&&i(n,11)&&i(n,12)&&i(n,14)&&i(n,15)&&i(n,17)&&i(n,18)&&i(n,20)&&i(n,21)&&i(n,22)}function S(n){if(!L(n))return false;let t=s(n,0,4),r=s(n,5,7),e=s(n,8,10),m=s(n,11,13),c=s(n,14,16),a=s(n,17,19);return r>=1&&r<=12&&e>=1&&e<=N(t,r)&&m<=23&&c<=59&&a<=59}function E(n,t){if(!Number.isSafeInteger(n)||n<0)throw new Error(`${t} invalid timestamp`);let r=new Date(n);if(!Number.isFinite(r.getTime()))throw new Error(`${t} invalid timestamp`);return n}function $(n,t){let r=B.exec(n);if(!r)throw new Error(`${t} must be an ISO timestamp`);let e=Date.parse(n);if(!Number.isFinite(e))throw new Error(`${t} must be an ISO timestamp`);let m=new Date(e).toISOString(),[,c="",a="",f="",u="",b="",d="",O="",M="Z",,g="",I=""]=r,A=Number(c),p=Number(a),T=Number(f),_=Number(u),k=Number(b),x=Number(d),C=g===""?0:Number(g),D=I===""?0:Number(I);if(!(p>=1&&p<=12&&T>=1&&T<=N(A,p)&&_<=23&&k<=59&&x<=59&&C<=23&&D<=59))throw new Error(`${t} must be an ISO timestamp`);let P=`${c}-${a}-${f}T${u}:${b}:${d}.${O.slice(0,3).padEnd(3,"0")}Z`;if(M==="Z"&&m!==P)throw new Error(`${t} must be an ISO timestamp`);return {isoTimestamp:m,millis:e}}function h(n,t){if(typeof n=="string")return S(n)?n:$(n,t).isoTimestamp;if(typeof n=="number")return new Date(E(n,t)).toISOString();throw new Error(`${t} invalid timestamp`)}function j(n,t){if(typeof n=="string")return S(n)?Date.parse(n):$(n,t).millis;if(typeof n=="number")return E(n,t);throw new Error(`${t} invalid timestamp`)}var Z=/^-?(?:0|[1-9]\d*)$/,z="serde";function o(n,t){throw new ValidationError({message:n,diagnostics:{sdkVersion:a,sourceTag:z,chainId:0},...t!==void 0?{cause:t}:{}})}function q(n){let t;try{t=JSON.stringify(n,(r,e)=>typeof e=="bigint"?e.toString():e);}catch(r){o("value must be JSON serializable",r);}return t===void 0&&o("value must be JSON serializable"),t}function G(n,t){if(typeof n=="bigint")return n;if(typeof n=="number")return Number.isSafeInteger(n)||o(`${t} must be a safe integer; unsafe integer values are rejected`),BigInt(n);if(typeof n=="string")return Z.test(n)||o(`${t} must be an integer string`),BigInt(n);o(`${t} must be an integer`);}function K(n,t){try{return h(n,t)}catch(r){if(r instanceof ValidationError)throw r;let e=r instanceof Error?r.message:`${t} invalid timestamp`;o(e,r);}}function Q(n,t){if(n!=null)return G(n,t)}export{j as a,q as b,G as c,K as d,Q as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var S=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,T=/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/,P=/^(?:0|[1-9]\d*)$/,y=/^-?(?:0|[1-9]\d*)$/;function A(e){return l(e,true),e}function l(e,r){if(!(r?T:S).test(e))throw new Error(`invalid decimal string: ${e}`);let n=e.startsWith("-"),s=n?e.slice(1):e,[i="0",a=""]=s.split(".");return {negative:n,whole:i,fraction:a}}function w(e,r){if(!(r?y:P).test(e))throw new Error(`invalid raw integer: ${e}`);return BigInt(e)}function B(e,r){return r===void 0?e.toString():new Intl.NumberFormat(r).format(e)}function h(e){return e===void 0?".":new Intl.NumberFormat(e).formatToParts(1.1).find(r=>r.type==="decimal")?.value??"."}function R(e,r,o,n){let s=n?.decimals??o;if(!Number.isInteger(s)||s<0)throw new Error("decimals must be a non-negative integer");let i=e<0n,a=i?-e:e,c=a/r,g=o===0?"":(a%r).toString().padStart(o,"0"),d=s<=o?g.slice(0,s):g.padEnd(s,"0");n?.trimTrailingZeros!==false&&(d=d.replace(/0+$/,""));let b=B(c,n?.locale),f=d.length===0?b:`${b}${h(n?.locale)}${d}`;return `${i?"-":""}${n?.symbol??""}${f}`}function m(e,r,o){return {from(n){if(!Number.isInteger(n)||n<r||n>o)throw new Error(`${e} out of range`);return n},toNumber(n){return n}}}function _(e){return {parse(r){if(r.length===0)throw new Error(`${e} cannot be empty`);return r},toString(r){return r}}}function t(e,r,o=0n,n){let s=i=>{let a=typeof i=="bigint"?i:w(i,o<0n);if(a<o)throw new Error("value below minimum");if(n!==void 0&&a>n)throw new Error("value above maximum");return a};return {fromDecimal(i){let{negative:a,whole:c,fraction:g}=l(i,o<0n);if(g.length>r)throw new Error(`too many fractional digits: expected ${r}`);let d=BigInt(c)*e+BigInt(g.padEnd(r,"0")||"0");return s(a?-d:d)},fromRaw:s,toRaw(i){return i},toRawString(i){return i.toString()},format(i,a){return R(i,e,r,a)}}}var I=2n**32n-1n,N=2n**192n-1n,p=2n**256n-1n,x=-(2n**255n),u=2n**255n-1n,U=m("PairIndex",0,65535),F=m("TradeIndex",0,255),C=Object.assign(m("TriggerOrderIndex",0,255),{parseApi(e){if(!P.test(e))throw new Error("TriggerOrderIndex out of range");return C.from(Number(e))}}),M=_("TradeId"),V=_("OrderId"),v=t(1000000n,6,0n,p),D=t(1000000n,6,x,u),W=t(1000000000000000000n,18,0n,N),L=t(1000000000000000000n,18),j=t(100n,2,0n,I),G=t(1000000000000000000n,18,x,u),X=t(1000000000000000000n,18,0n,p),k=t(1000000n,6,x,u),Z=t(100n,2,0n,I),E=Object.assign(t(1000000n,6,0n,p),{fromDollar(e){return E.fromDecimal(e.startsWith("$")?e.slice(1):e)}}),O=Object.assign(t(100n,2,1n,9999n),{fromBps(e){return O.fromRaw(e)}}),$=Object.assign(t(100n,2,1n,10000n),{full(){return $.fromRaw(10000n)}}),H=t(1000000n,6),q=t(1n,0,0n,100n),z=t(100n,2),J=t(1n,0),K=t(1000000n,6,0n,p),Q=t(1000000n,6,0n,p),Y=t(1000000000000000000n,18),ee={fromDecimal(e){return l(e,true),e},fromRaw(e){if(!T.test(e))throw new Error("invalid ratio");return e},toRawString(e){return e},format(e){return e}};export{A as a,U as b,F as c,C as d,M as e,V as f,v as g,D as h,W as i,L as j,j as k,G as l,X as m,k as n,Z as o,E as p,O as q,$ as r,H as s,q as t,z as u,J as v,K as w,Q as x,Y as y,ee as z};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e={id:"base",chainId:8453,name:"Base",registryAddress:"0xe438360464EaDa40b7921C993322bD4dA8881103",contracts:{DomfiTrading:"0x7447cb5350a096364A13bEAf77916dfB35db9445",DomfiTradingStorage:"0x608ff95777F419040a3b1E42ed73dD3EFf42Cc24",DomfiPairsStorage:"0x444079DDCaFd4feE3812E2fF79c5F74a1F4f9Be1",DomfiPairInfos:"0x256fD248cDc91A6B098eEE2580f313fdCaFa2059",DomfiOracle:"0x1aB9c3A2E1A09f2D06bf4A75d1721c7e113B8D4D",DomfiVault:"0xA194082Aabb75Dd1Ca9Dc1BA573A5528BeB8c2Fb",DomfiLockedDepositNft:"0x11765119eC66fb434447fd56e9041746c8eCbF85"},collateral:{symbol:"USDC",decimals:6,tokenAddress:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",tradingStorageSpender:"0x608ff95777F419040a3b1E42ed73dD3EFf42Cc24",vaultSpender:"0xA194082Aabb75Dd1Ca9Dc1BA573A5528BeB8c2Fb"},oracleStaleThresholdMs:6e4,blockTimeMs:2e3,apiBaseUrl:"https://api.domination.finance"},a={id:"base-sepolia",chainId:84532,name:"Base Sepolia",registryAddress:"0xa518Cb338f71E9BB2EB9bBb6E02b2B0cC5C29840",contracts:{DomfiTrading:"0x40478F0B348837EFdd07dac83073016da409ea93",DomfiTradingStorage:"0xd62c446636e49C70acf7E47b2907381C829BC412",DomfiPairsStorage:"0x3D5EE28985F8C382cCB112B9054f89d054b6f23E",DomfiPairInfos:"0xAB619663B87ddAD53f4c23A34cfb79AFA06A1EcA",DomfiOracle:"0x47959A2f92335587cf2956dA450b956dA6ca3A84",DomfiVault:"0x0f6171b19f02989485c168536aDE0d9CE5e804fb",DomfiLockedDepositNft:"0x5F78d9A47fdcd0A2c1a23cdB08544f4577c6DFde"},collateral:{symbol:"MockCollateral",decimals:6,tokenAddress:"0xE0843F149471c2e90E995BaEFA5EF94DC82bF809",tradingStorageSpender:"0xd62c446636e49C70acf7E47b2907381C829BC412",vaultSpender:"0x0f6171b19f02989485c168536aDE0d9CE5e804fb"},oracleStaleThresholdMs:6e4,blockTimeMs:2e3,apiBaseUrl:"https://testnet-api.domination.finance"},i={mainnet:e,testnet:a};
|
|
2
|
+
export{e as a,a as b,i as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {d,a}from'./chunk-SZE5DE54.js';import {l,g,k}from'./chunk-C5Y2WM7C.js';function v(e){let d$1=l.toRaw(e.initialAccFunding),s=l.toRaw(e.endAccFunding),t=g.toRaw(e.collateral),i=k.toRaw(e.leverage);if(t<0n)throw new Error("collateral must be non-negative");if(i<=0n)throw new Error("leverage must be positive");let o=s-d$1,a$1=o*(t*i)/d/a;return a$1!==0n?a$1:o>0n?1n:0n}export{v as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {s,p,y as y$1,x as x$1,r as r$1,i,g as g$1,e,m as m$1,t,h as h$1,j as j$1,n as n$3,q as q$2,u,o as o$1,v}from'./chunk-77XMXAXE.js';import {a}from'./chunk-D5VE2O4F.js';import {p as p$1,q,r,s as s$1,g,o,k,l,a as a$2,n,b as b$2,c as c$1,f as f$1,d as d$1,e as e$1,i as i$2,j as j$2}from'./chunk-7OVWNPZQ.js';import {j as j$3,g as g$3,n as n$2}from'./chunk-SZE5DE54.js';import {r as r$2,i as i$1,k as k$1,q as q$1,b as b$1,g as g$2,d,f,c,p as p$2,n as n$1,t as t$1,e as e$2}from'./chunk-C5Y2WM7C.js';import {a as a$1}from'./chunk-YU5DN3PI.js';import {MissingPublicClientError,MissingWalletClientError,MissingAccountError,WalletChainMismatchError,WalletAccountMismatchError,ValidationError,IdentityMismatchError,ReadModelNotReadyError,AbortError,ContractRevertError,TimeoutError,TransportError,ApiError,OracleFeeCapExceededError}from'@domfi/sdk/errors';import {encodeFunctionData,decodeFunctionData}from'viem';var Pr=[68,77,70,82],Tr=20,wr=8,Ar=0xffffffffffffffffn,hr=2197175160,yr=Rr();function ve(e,t,n){throw new ValidationError({message:e,diagnostics:{sdkVersion:a,sourceTag:"referrals",chainId:n?.chainId??0},...{}})}function Rr(){let e=new Uint32Array(256);for(let t=0;t<e.length;t+=1){let n=t;for(let r=0;r<8;r+=1)n=(n&1)===1?n>>>1^hr:n>>>1;e[t]=n>>>0;}return e}function xr(e){let t=4294967295;for(let n of e){let r=yr[(t^n)&255];if(r===void 0)throw new Error("invalid CRC32C table index");t=t>>>8^r;}return (t^4294967295)>>>0}function Or(e){return `0x${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`}function kr(e,t){let n;return typeof e=="bigint"?n=e:typeof e=="number"?(Number.isSafeInteger(e)||ve("referralCodeId must be a safe integer",void 0,t),n=BigInt(e)):typeof e=="string"?(/^(?:0|[1-9]\d*)$/.test(e)||ve("referralCodeId must be an unsigned integer string",void 0,t),n=BigInt(e)):ve("referralCodeId must be a bigint, number, or string",void 0,t),(n<0n||n>Ar)&&ve("referralCodeId must fit in uint64",void 0,t),n}function tn(e,t){let n=kr(e,t),r=new Uint8Array(Tr);r.set(Pr,0),r[4]=1,r[5]=0,r[6]=0,r[7]=wr;let i=new DataView(r.buffer,r.byteOffset,r.byteLength);return i.setBigUint64(8,n,false),i.setUint32(16,xr(r.subarray(0,16)),false),Or(r)}var nn=1n;function Y(e,t,n,r){if(t===void 0)return r(`${n} is required`);try{if(typeof t=="string")return e.toRaw(e.fromDecimal(t));if(typeof t=="bigint")return e.toRaw(e.fromRaw(t))}catch(i){return r(`${n} is invalid`,i instanceof Error?i.message:void 0)}return r(`${n} is invalid`)}function Be(e,t,n){return Number.isInteger(e)?e:n(`${t} must be an integer`)}function H(e,t,n){return Y(i$1,e,t,n)}function Se(e,t,n){return Y(g$2,e,t,n)}function br(e,t,n){let r=Y(k$1,e,t,n);return r>BigInt(Number.MAX_SAFE_INTEGER)?n(`${t} is too large`):Number(r)}function De(e,t){try{return b$1.toNumber(b$1.from(Be(e,"pairIndex",t)))}catch(n){return t("pairIndex is invalid",n instanceof Error?n.message:void 0)}}function on(e,t){try{return c.toNumber(c.from(Be(e,"index",t)))}catch(n){return t("index is invalid",n instanceof Error?n.message:void 0)}}function sn(e,t){try{return d.toNumber(d.from(Be(e,"index",t)))}catch(n){return t("index is invalid",n instanceof Error?n.message:void 0)}}function rn(e,t,n){return e===void 0?0n:H(e,t,n)}function Cr(e,t){return e==="long"?true:e==="short"?false:t("direction must be long or short")}function an(e,t,n,r,i){e===0n||(t==="takeProfit"?r?e>n:e<n:r?e<n:e>n)||i(`${t} is on the wrong side of the open price`);}function Ve(e,t){an(e.takeProfitRaw,"takeProfit",e.openPriceRaw,e.buy,t),an(e.stopLossRaw,"stopLoss",e.openPriceRaw,e.buy,t);}function de(e,t,n,r={}){if(e===void 0)return r.optional===true?{status:"omitted"}:n(`${t} is required`);if(typeof e=="object"&&e!==null&&"clear"in e)return e.clear===true?{status:"provided",value:0n}:n(`${t} clear must be true`);let i=H(e,t,n);return i===0n?n(`${t} must use { clear: true } to clear an existing trigger`):{status:"provided",value:i}}function Ie(e,t,n,r){for(let i of t)e[i]!==void 0&&r(`${n} cannot include ${i}`);}function dn(e,t){let n=De(e.pairIndex,t),r=Cr(e.direction,t),i={pairIndex:n,buy:r,collateral:Se(e.collateral,"collateral",t),leverage:br(e.leverage,"leverage",t),tp:rn(e.takeProfit,"takeProfit",t),sl:rn(e.stopLoss,"stopLoss",t),...e.referralCodeId!==void 0?{referralCodeId:e.referralCodeId}:{}};if(e.orderKind==="market"){Ie(e,["entryPrice","triggerPrice","executionSlippage"],"market open",t);let o=e.wantedPrice!==void 0?H(e.wantedPrice,"wantedPrice",t):void 0;return o!==void 0&&Ve({takeProfitRaw:i.tp,stopLossRaw:i.sl,openPriceRaw:o,buy:r},t),{...i,verb:"openMarket",orderType:0,slippageP:Y(q$1,e.slippage,"slippage",t),warnings:[],...o!==void 0?{requestedOpenPrice:o}:{}}}Ie(e,["wantedPrice","slippage","executionSlippage"],`${e.orderKind} open`,t);let a={code:"TRIGGER_ORDER_SLIPPAGE_COMPATIBILITY",message:"limit/stop open orders use a protocol-required slippage placeholder; it is not an execution guard",severity:"warning"};return e.orderKind==="limit"?(Ie(e,["triggerPrice"],"limit open",t),{...i,verb:"openLimit",orderType:1,slippageP:nn,warnings:[a],requestedOpenPrice:H(e.entryPrice,"entryPrice",t)}):(Ie(e,["entryPrice"],"stop open",t),{...i,verb:"openStop",orderType:2,slippageP:nn,warnings:[a],requestedOpenPrice:H(e.triggerPrice,"triggerPrice",t)})}function cn(e,t,n,r){let i=Y(r$2,e.closePercent??r$2.full(),"closePercent",r);return {pairIndex:t,index:n,closePercent:Number(i),slippageP:Y(q$1,e.slippage,"slippage",r),...e.wantedPrice!==void 0?{wantedPrice:H(e.wantedPrice,"wantedPrice",r)}:{}}}function ln(e,t){return H(e.targetPrice,"targetPrice",t)}var vr=["8ca43d9286c58d302725cc047270fc78f60b56599bbe3999c50e10ec10136ae3"];function Ge(e){return vr.includes(e)}function un(e){let t=e.apiSchemaHash??void 0;return t===void 0||t.length===0?{status:"unsupported",reason:"missing"}:Ge(t)?{status:"supported",hash:t}:{status:"unsupported",reason:"unknown",hash:t}}function pn(e,t){let n=fn(t.schema);return n!==void 0?n:e.rawState===void 0?{status:"unchecked",reason:"missing_raw_state"}:{status:"ok",input:{rawState:e.rawState}}}function Ia(e,t){let n=fn(t.schema);return n!==void 0?n:e.initialAccFundingRaw===void 0?{status:"unchecked",reason:"missing_initial_acc_funding"}:{status:"ok",input:{initialAccFundingRaw:e.initialAccFundingRaw}}}function fn(e){if(!(e.status==="supported"&&Ge(e.hash)))return {status:"unchecked",reason:"api_schema_unsupported",compatibility:e}}function S(e,t,n){return n===void 0?{status:"unchecked",code:e,reason:t}:{status:"unchecked",code:e,reason:t,message:n}}function ce(e){return {checks:[S("api_schema",e),S("market_constraints",e),S("market_raw_state",e),S("max_trades_per_pair","account_order_count_unavailable")]}}function gn(e){return e instanceof ReadModelNotReadyError||e instanceof TimeoutError||e instanceof TransportError||e instanceof ApiError&&(e.transient||e.httpStatus===404)||e instanceof Error&&e.name==="TimeoutError"}function Mr(e){for(let t of e)if(t.status==="rejected"&&!gn(t.reason))return t.reason}function Nr(e,t){let n=e.rawState;if(n!==void 0)return t==="long"?n.groupCollateralLong:n.groupCollateralShort}function Fr(e,t,n){let r=n.pairIndex;if(b$1.toNumber(e.pairIndex)!==r||b$1.toNumber(t.pairIndex)!==r)throw new ValidationError({message:"preflight API pair mismatch",diagnostics:{sdkVersion:a,sourceTag:"trading-preflight",chainId:0}})}function Er(e,t){let n=p$2.toRaw(e);return n$1.fromRaw(t?n:-n)}function Ur(e,t){if(t===void 0||e.verb!=="openMarket")return;let n=e.slippageP,r=10000n;return e.buy?{max:i$1.fromRaw(j$3(t,r+n,r))}:{min:i$1.fromRaw(t*(r-n)/r)}}function Le(e){return {value:e,source:"computed",parityTarget:g$3}}function Wr(e){try{return k$1.fromRaw(e)}catch{return}}function _r(e){try{return i$1.fromRaw(n$2(e))}catch{return}}async function mn(e,t,n={}){if(e.api===void 0)return ce("api_unavailable");try{let r=await e.api.status.get(),i=un(r.data);if(i.status!=="supported")return ce("api_schema_unsupported");let[a,o]=await Promise.allSettled([e.api.markets.get(b$1.from(t.pairIndex)),e.api.markets.state(b$1.from(t.pairIndex))]),s=Mr([a,o]);if(s!==void 0)throw s;return a.status==="rejected"||o.status==="rejected"?ce("api_unavailable"):qr(i,a.value.data,o.value.data,t,n.openPriceRaw===void 0?{}:{openPriceRaw:n.openPriceRaw})}catch(r){if(gn(r))return ce("api_unavailable");throw r}}function qr(e,t,n$2,r,i={}){if(e.status!=="supported")return ce("api_schema_unsupported");Fr(t,n$2,r);let a=[],o=r.buy?"long":"short",s=g$2.fromRaw(r.collateral),d=k$1.fromRaw(BigInt(r.leverage));a.push(S("max_trades_per_pair","account_order_count_unavailable"));let c=a$2({leverage:d,minLeverage:t.constraints.minLeverage,maxLeverage:t.constraints.maxLeverage});a.push(c);let l=k$1.toRaw(d),p=l>0n?n({collateral:s,leverage:d}):void 0;p===void 0?a.push(S("minimum_position_size","invalid_leverage")):a.push(b$2({notionalUsd:p,minPositionSize:t.constraints.minLevPosition}));let u=t.constraints.maxAllowedCollateral;u===void 0?a.push(S("max_collateral","missing_max_allowed_collateral")):a.push(c$1({collateral:s,maxAllowedCollateral:u}));let f=t.constraints.maxSlP;f===void 0?a.push(S("slippage_bounds","missing_max_sl_p")):r.verb==="openMarket"?a.push(f$1({slippage:q$1.fromRaw(r.slippageP),maxSlP:f})):a.push(S("slippage_bounds","trigger_order_slippage_not_execution_guard"));let P=pn(n$2,{schema:e});if(P.status==="ok"){let xe=P.input.rawState;p===void 0?a.push(S("oi_cap","invalid_leverage")):a.push(d$1({currentSideOi:o==="long"?xe.oiLong:xe.oiShort,price:xe.lastTradePrice,requestedNotional:p,oiCap:xe.oiCap}));let xt=Nr(n$2,o);a.push(e$1({requestedCollateral:s,groupMaxCollateral:t.constraints.groupMaxCollateral,...xt!==void 0?{currentGroupCollateral:xt}:{}}));}else a.push(S("market_raw_state",P.reason));let g=Ur(r,i.openPriceRaw),v=P.status==="ok"?P.input.rawState:void 0;if(p===void 0||v===void 0)return {checks:a,...g!==void 0?{executionPriceBounds:g}:{}};let ae=i$2({tradeSize:Er(p,r.buy),oiDelta:v.lastOiDelta,leverage:d,makerFeeP:t.fees.opening.makerFeeP,takerFeeP:t.fees.opening.takerFeeP,makerMaxLeverage:t.fees.opening.makerMaxLeverage}),ye=g$2.toRaw(ae),Tt=g$2.toRaw(s);if(ye>=Tt)return {checks:a,estimatedOpeningFee:Le(ae),...g!==void 0?{executionPriceBounds:g}:{}};let Re=g$2.fromRaw(Tt-ye),wt=n({collateral:Re,leverage:d}),At=r.buy?p$2.toRaw(wt):-p$2.toRaw(wt),pr=n$1.fromRaw(n$1.toRaw(v.lastOiDelta)+At),fr=i$2({tradeSize:n$1.fromRaw(-At),oiDelta:pr,leverage:d,makerFeeP:t.fees.closing.makerFeeP,takerFeeP:t.fees.closing.takerFeeP,makerMaxLeverage:t.fees.closing.makerMaxLeverage}),gr=p$2.toRaw(p)*100n/g$2.toRaw(Re),ht=Wr(gr),yt=i.openPriceRaw===void 0?void 0:j$2({price:i$1.fromRaw(i.openPriceRaw),oiLong:v.oiLong,oiShort:v.oiShort,collateral:Re,leverage:d,isOpen:true,isLong:r.buy}).priceAfterImpact,Rt=yt!==void 0&&t.constraints.liqMarginThresholdP!==void 0?_r({openPriceRaw:i$1.toRaw(yt),buy:r.buy,collateralRaw:g$2.toRaw(Re),leverageRaw:l,fundingFeeRaw:0n,maxLeverageRaw:k$1.toRaw(t.constraints.maxLeverage),liqMarginThresholdP:Number(t$1.toRaw(t.constraints.liqMarginThresholdP))}):void 0;return {checks:a,estimatedOpeningFee:Le(ae),estimatedClosingFee:Le(fr),...ht!==void 0?{resultingLeverage:Le(ht)}:{},...g!==void 0?{executionPriceBounds:g}:{},...Rt!==void 0?{estimatedLiquidationPrice:Rt}:{}}}var Jr="trading-send",Ye="0x0000000000000000000000000000000000000000",Qr=130n;function hn(e){let t={sdkVersion:a,sourceTag:Jr,chainId:e.chain.chainId};return e.chain.registryAddress!==void 0&&(t.registryAddress=e.chain.registryAddress),t}function C(e,t,n,r){return {message:t,diagnostics:hn(e),...n!==void 0?{hint:n}:{},...r!==void 0?{cause:r}:{}}}function h(e,t,n,r){throw new ValidationError(C(e,t,n,r))}function b(e,t){throw new IdentityMismatchError(C(e,t))}function ei(e,t,n){throw new OracleFeeCapExceededError(C(e,`fresh oracle fee ${t} exceeds maxOracleFeeWei ${n}`,"Increase maxOracleFeeWei or re-prepare after oracle fees settle."))}function Me(e,t,n){throw new ContractRevertError(C(e,t,void 0,n))}function L(e,t,n){throw Ee(e,t,n)}function Ee(e,t,n){return new AbortError(C(e,t,void 0,n))}function Ze(e,t,n){return new TimeoutError(C(e,t,void 0,n))}function F(e){return e instanceof AbortError||e instanceof Error&&e.name==="AbortError"?true:typeof e=="object"&&e!==null&&"code"in e&&e.code==="ABORTED"}function J(e,t,n){t?.aborted===true&&L(e,n,t.reason);}function Z(e,t){return t===void 0?e:{...e,signal:t}}function le(e){return typeof e=="object"&&e!==null&&"code"in e&&"kind"in e&&"diagnostics"in e}function ti(e,t){return typeof t.estimateContractGas=="function"?t.estimateContractGas:()=>h(e,"public client is missing estimateContractGas")}function ni(e,t){return typeof t.estimateGas=="function"?t.estimateGas:()=>h(e,"public client is missing estimateGas")}function ri(e,t){return typeof t.sendTransaction=="function"?t.sendTransaction:()=>h(e,"wallet client is missing sendTransaction")}function ii(e,t){let n=t.simulateContract;return typeof n=="function"?r=>n.call(t,r):()=>h(e,"public client is missing simulateContract")}function yn(e,t){let n=t.writeContract;return typeof n=="function"?r=>n.call(t,r):()=>h(e,"wallet client is missing writeContract")}function Pn(e){return e*Qr/100n}function Je(e,t){if(e.publicClient!==void 0)return e.publicClient;throw new MissingPublicClientError(C(e,`${t} requires a public client`,"Pass publicClient to createDomfiClient."))}function Rn(e,t,n){if(t!==void 0)return e.wrapWalletClient?.(t)??t;let r=e.walletClient;if(r!==void 0)return r;throw new MissingWalletClientError(C(e,`${n} requires a wallet client`,"Pass walletClient to createDomfiClient or prepared.send()."))}function xn(e){let t=e?.account;if(t!==void 0){if(typeof t=="string")return t;if(typeof t=="object"&&"address"in t&&typeof t.address=="string")return t.address}}function ai(e,t,n,r,i,a){let o=r?.account??n??e.account??xn(t);if(o!==void 0)return o;throw new MissingAccountError(C(e,`${i} requires an account`,"Pass account to createDomfiClient, pass opts.account, or use a connected wallet client."))}function On(e,t){let n=t.chain?.id;if(!(n===void 0||n===e.chain.chainId))throw new WalletChainMismatchError(C(e,`wallet client chain ${n} does not match DomFi chain ${e.chain.chainId}`,"Use a wallet client connected to the same chain as createDomfiClient."))}function kn(e,t,n){let r=xn(t);if(!(r===void 0||r.toLowerCase()===n.toLowerCase()))throw new WalletAccountMismatchError(C(e,`wallet client account ${r} does not match requested account ${n}`,"Use the connected wallet account or pass the matching account option."))}function bn(e,t){let n=e.account;return typeof n=="object"&&n!==null&&"address"in n&&typeof n.address=="string"&&n.address.toLowerCase()===t.toLowerCase()?n:t}function oi(e$1,t,n){let r=n.positionRef??n.triggerRef;r!==void 0&&(r.chainId!==e$1.chain.chainId&&b(e$1,`verified ref chain ${r.chainId} does not match SDK chain ${e$1.chain.chainId}`),e(r.wallet,t)||b(e$1,`trader ${t} does not match verified ref wallet ${r.wallet}`));}function M(e,t){let n=e.chain.contracts[t];return n!==void 0?n:h(e,`chain profile is missing ${t} contract address`)}function Ne(e,t){return typeof t.readContract!="function"&&h(e,"public client is missing readContract"),t.readContract}function si(e,t){return typeof t.getBlock!="function"&&h(e,"public client is missing getBlock"),t.getBlock}function di(e){return typeof e.multicall=="function"?e.multicall:void 0}function x(e,t,n){if(Array.isArray(e))return e[n];if(typeof e=="object"&&e!==null&&t in e)return e[t]}function Cn(e){return decodeFunctionData({abi:a$1.DomfiTrading,data:e.data})}function vn(e,t$1,n){return m$1({hash:n,wait:(r,i)=>t(t$1,r,i,e.chain),mapAbort:r=>Ee(e,"receipt wait was aborted",r),mapTimeout:r=>Ze(e,"receipt wait timed out",r)})}function ci(e,t$1,n,r,i){return n$3({hash:r,verb:n,wait:(o,s)=>t(t$1,o,s,e.chain),mapAbort:o=>Ee(e,"receipt wait was aborted",o),mapTimeout:o=>Ze(e,"receipt wait timed out",o),orderIdFromReceipt:o=>u(o,{verb:n,chainId:e.chain.chainId,expectedTradingAddress:M(e,"DomfiTrading"),...i!==void 0?{expectedTrader:i}:{}}),...e.api===void 0?{}:{lifecycle:{diagnostics:()=>hn(e),...i!==void 0?{expectedTrader:i}:{},track:async(o,s)=>p(e,o,s),trackOnce:async(o,s)=>q$2(e,o,s)}}})}function li(e,t$1,n,r,i){return o$1({hash:r,wait:(a,o)=>t(t$1,a,o,e.chain),mapAbort:a=>Ee(e,"receipt wait was aborted",a),mapTimeout:a=>Ze(e,"receipt wait timed out",a),verifiedRefFromReceipt:a=>v(a,{chainId:e.chain.chainId,expectedWallet:i,expectedOrderType:n==="openLimit"?"limit":"stop",expectedTradingAddress:M(e,"DomfiTrading")})})}function Tn(e,t,n,r,i){return n==="openMarket"||n==="closeMarket"||n==="removeCollateral"?ci(e,t,n,r,i):n==="openLimit"||n==="openStop"?li(e,t,n,r,i):vn(e,t,r)}function ui(e,t){return {address:M(e,"DomfiPairsStorage"),abi:a$1.DomfiPairsStorage,functionName:"pairOracleFee",args:[t]}}function In(e,t){return {key:"oracleFee",call:ui(e,t),assign:(n,r)=>{n.oracleFee=r;}}}function pi(e,t,n){let r=b$1.toNumber(n.pairIndex),i=c.toNumber(n.index);t.push({key:"positionTrade",call:{address:M(e,"DomfiTradingStorage"),abi:a$1.DomfiTradingStorage,functionName:"openTrades",args:[n.wallet,r,i]},assign:(a,o)=>{a.positionTrade=o;}},{key:"positionInfo",call:{address:M(e,"DomfiTradingStorage"),abi:a$1.DomfiTradingStorage,functionName:"openTradesInfo",args:[n.wallet,r,i]},assign:(a,o)=>{a.positionInfo=o;}});}function fi(e,t,n){t.push({key:"triggerSlot",call:{address:M(e,"DomfiTradingStorage"),abi:a$1.DomfiTradingStorage,functionName:"getOpenLimitOrder",args:[n.wallet,b$1.toNumber(n.pairIndex),d.toNumber(n.index)]},assign:(r,i)=>{r.triggerSlot=i;},onError:(r,i)=>(F(i)&&L(r,"prepared trading send was aborted",i),b(r,"trigger slot does not match verified trigger ref"))});}function gi(e,t,n){t.push({key:"balance",call:{address:e.chain.collateral.tokenAddress,abi:a$1.IERC20,functionName:"balanceOf",args:[n]},assign:(r,i)=>{r.balance=i;}},{key:"allowance",call:{address:e.chain.collateral.tokenAddress,abi:a$1.IERC20,functionName:"allowance",args:[n,e.chain.collateral.tradingStorageSpender]},assign:(r,i)=>{r.allowance=i;}});}function Sn(e,t,n){if(le(n)&&n.code==="VALIDATION_ERROR"||t.onError===void 0)return n;try{t.onError(e,n);}catch(r){return r}}async function Ke(e,t,n,r){try{return {status:"fulfilled",value:await Ne(e,t)(Z(n.call,r))}}catch(i){return {status:"rejected",reason:Sn(e,n,i)}}}function mi(e,t,n){if(typeof n!="object"||n===null||!("status"in n))return {status:"fulfilled",value:n};let r=n;return r.status==="success"?{status:"fulfilled",value:r.result}:r.status==="failure"?{status:"rejected",reason:Sn(e,t,r.error)}:{status:"fulfilled",value:n}}function Fe(e,t,n){if(n.status==="fulfilled"){t.assign(e,n.value);return}e.errors={...e.errors,[t.key]:n.reason};}function Pi(e,t,n){e.pending={...e.pending,[t.key]:n.then(r=>{Fe(e,t,r);})};}async function Q(e,t){await e.pending?.[t];}function ee(e,t){return e.errors?.[t]}function Dn(e,t,n,r){if(n.feeCharging)return t.estimatedOracleFeeWei===void 0&&r?.maxOracleFeeWei===void 0?h(e,"fee-charging prepared transaction is missing a prepare-time oracle fee estimate","Pass maxOracleFeeWei explicitly or re-prepare the transaction."):n.feePairIndex===void 0?h(e,"fee-charging prepared transaction is missing pair index"):{pairIndex:n.feePairIndex,cap:r?.maxOracleFeeWei??t.estimatedOracleFeeWei}}async function Ti(e,t,n,r,i,a,o){let s=[];if(n.positionRef!==void 0&&pi(e,s,n.positionRef),n.triggerRef!==void 0&&fi(e,s,n.triggerRef),i!==void 0&&s.push(In(e,i.pairIndex)),a!==void 0&&gi(e,s,r),s.length===0)return {};if(s.length===1){let u=s[0],f=await Ke(e,t,u,o),P={};return Fe(P,u,f),P}let d=s.map(u=>u.call),c=di(t);if(c===void 0){let u={};for(let f of s)Pi(u,f,Ke(e,t,f,o));return u}let l=(await c(Z({contracts:d,allowFailure:true},o))).map((u,f)=>mi(e,s[f],u)),p={};for(let[u,f]of l.entries())Fe(p,s[u],f);return p}async function Qe(e$1,t,n,r,i){let a=await Ne(e$1,t)(Z({address:M(e$1,"DomfiTrading"),abi:a$1.DomfiTrading,functionName:"delegations",args:[n]},i));if(!(typeof a=="string"&&e(a,r)))return h(e$1,`account ${r} is not delegate for trader ${n}`)}async function wi(e,t,n){await Q(n,"balance"),await Q(n,"allowance");let r=ee(n,"balance");if(r!==void 0)throw r;let i=ee(n,"allowance");if(i!==void 0)throw i;let{balance:a,allowance:o}=n;(typeof a!="bigint"||typeof o!="bigint")&&h(e,"collateral balance or allowance read returned invalid data"),a<t&&h(e,"collateral balance is below the amount required for this prepared transaction"),o<t&&h(e,"collateral allowance is below the amount required for this prepared transaction");}async function Ai(e,t,n){await Q(n,"positionTrade"),await Q(n,"positionInfo");let r=ee(n,"positionTrade");if(r!==void 0)throw r;let i=ee(n,"positionInfo");if(i!==void 0)throw i;let a=b$1.toNumber(t.pairIndex),o=c.toNumber(t.index),s=n.positionTrade,d=n.positionInfo,c$1=x(s,"trader",4),l=x(s,"pairIndex",6),p=x(s,"index",7),u=x(d,"tradeId",0),f=x(d,"beingMarketClosed",6);(c$1===void 0||c$1===Ye||c$1.toLowerCase()!==t.wallet.toLowerCase())&&b(e,"open trade slot wallet does not match verified position ref"),l!==a&&b(e,"open trade slot pairIndex does not match verified position ref"),p!==o&&b(e,"open trade slot index does not match verified position ref"),(u===void 0||u.toString()!==e$2.toString(t.tradeId))&&b(e,"open trade slot tradeId does not match verified position ref"),f===true&&b(e,"open trade slot has a detectable pending market mutation");}async function hi(e,t,n,r){await Q(n,"triggerSlot");let i=ee(n,"triggerSlot");if(i!==void 0)throw i;let a=b$1.toNumber(t.pairIndex),o=d.toNumber(t.index),s=t.orderType==="limit"?1:2,d$1=n.triggerSlot,c=x(d$1,"trader",0),l=x(d$1,"pairIndex",8),p=x(d$1,"index",9),u=x(d$1,"orderType",11);(c===void 0||c===Ye||c.toLowerCase()!==t.wallet.toLowerCase()||l!==a||p!==o||u!==s)&&b(e,"trigger slot does not match verified trigger ref");let f=x(d$1,"tp",5),P=x(d$1,"sl",6);r?.tp!==void 0&&f!==r.tp&&b(e,"trigger slot TP changed after prepare"),r?.sl!==void 0&&P!==r.sl&&b(e,"trigger slot SL changed after prepare");}async function yi(e,t,n){t.positionRef!==void 0&&await Ai(e,t.positionRef,n),t.triggerRef!==void 0&&await hi(e,t.triggerRef,n,t.preservedTrigger);}async function Vn(e,t,n){if(t===void 0)return;await Q(n,"oracleFee");let r=ee(n,"oracleFee");if(r!==void 0)throw r;let i=n.oracleFee;return typeof i!="bigint"?h(e,"pair oracle fee read returned invalid data"):t.cap!==void 0&&i>t.cap?ei(e,i,t.cap):i}async function Ri(e,t,n,r,i){if(!r.feeCharging)return n.value;let a=Dn(e,n,r,i);if(a===void 0)return;let o=In(e,a.pairIndex),s={};return Fe(s,o,await Ke(e,t,o,i?.signal)),Vn(e,a,s)}async function Ln(e$1,t,n,r){J(e$1,r?.signal,"prepared trading simulation was aborted"),g$1(e$1,r,"prepared trading simulation"),h$1(e$1,r,"prepared trading simulation");let i=Je(e$1,"prepared trading simulation"),a=n.preparedSender??t.preparedAccount;if(a!==void 0&&r?.account!==void 0&&!e(r.account,a))throw new WalletAccountMismatchError(C(e$1,`requested account ${r.account} does not match prepared sender ${a}`,"Simulate with the same account used to prepare the transaction."));let o=a??r?.account??e$1.account;if(o===void 0)throw new MissingAccountError(C(e$1,"prepared trading simulation requires an account","Pass opts.account or prepare with an account."));if(n.executionMode==="delegated"){n.preparedTrader===void 0&&h(e$1,"delegated prepared transaction is missing trader metadata");try{await Qe(e$1,i,n.preparedTrader,o,r?.signal);}catch(l){throw (r?.signal?.aborted===true||F(l))&&L(e$1,"prepared trading simulation was aborted",l),l}}let s=Cn(t),d;try{d=await Ri(e$1,i,t,n,r),J(e$1,r?.signal,"prepared trading simulation was aborted");}catch(l){throw (r?.signal?.aborted===true||F(l))&&L(e$1,"prepared trading simulation was aborted",l),l}let c={address:t.to,abi:a$1.DomfiTrading,functionName:s.functionName,args:s.args,account:o,...d!==void 0?{value:d}:{},...n.dataSuffix!==void 0?{dataSuffix:n.dataSuffix}:{},...r?.signal!==void 0?{signal:r.signal}:{}};try{let l=await ii(e$1,i)(c);return {request:{to:t.to,data:t.data,account:o,...d!==void 0?{value:d}:{}},...l.result!==void 0?{result:l.result}:{},warnings:n.warnings}}catch(l){if((r?.signal?.aborted===true||F(l))&&L(e$1,"prepared trading simulation was aborted",l),le(l))throw l;return Me(e$1,"prepared trading simulation reverted",l)}}async function Mn(e,t,n,r,i){J(e,i?.signal,"prepared trading send was aborted"),g$1(e,i,"prepared trading send"),h$1(e,i,"prepared trading send");let a=Je(e,"prepared trading send"),o=Rn(e,r,"prepared trading send"),s=j$1(e,n.preparedTrader===void 0?void 0:{mode:n.executionMode??"direct",trader:n.preparedTrader,...n.preparedSender!==void 0?{sender:n.preparedSender}:{}},n.preparedSender??t.preparedAccount,i,o,"prepared trading send"),d=s.sender;On(e,o),kn(e,o,d),oi(e,s.trader,n);let c=bn(o,d),l,p;try{l=Dn(e,t,n,i);}catch(g){p=g;}let u=p===void 0&&n.approvalAmountRaw!==void 0&&i?.skipApprovalCheck!==true?n.approvalAmountRaw:void 0,f;try{s.mode==="delegated"&&await Qe(e,a,s.trader,s.sender,i?.signal);let g=await Ti(e,a,n,s.trader,l,u,i?.signal);if(await yi(e,n,g),p!==void 0)throw p;f=await Vn(e,l,g),u!==void 0&&await wi(e,u,g),J(e,i?.signal,"prepared trading send was aborted");}catch(g){throw (i?.signal?.aborted===true||F(g))&&L(e,"prepared trading send was aborted",g),g}if(n.hasReferralTrailer===true)try{let g=i?.gas??Pn(await ni(e,a)({to:t.to,data:t.data,account:d,...f!==void 0?{value:f}:{},...i?.nonce!==void 0?{nonce:i.nonce}:{},...i?.maxFeePerGas!==void 0?{maxFeePerGas:i.maxFeePerGas}:{},...i?.signal!==void 0?{signal:i.signal}:{}})),v=await ri(e,o)({to:t.to,data:t.data,account:c,chain:null,...f!==void 0?{value:f}:{},gas:g,...i?.nonce!==void 0?{nonce:i.nonce}:{},...i?.maxFeePerGas!==void 0?{maxFeePerGas:i.maxFeePerGas}:{},...i?.signal!==void 0?{signal:i.signal}:{}});return Tn(e,a,t.verb,v,s.trader)}catch(g){if((i?.signal?.aborted===true||F(g))&&L(e,"prepared trading send was aborted",g),le(g))throw g;return Me(e,"prepared trading raw send reverted",g)}let P=Cn(t);try{let g=i?.gas??Pn(await ti(e,a)({address:t.to,abi:a$1.DomfiTrading,functionName:P.functionName,args:P.args,account:d,...f!==void 0?{value:f}:{},...i?.nonce!==void 0?{nonce:i.nonce}:{},...i?.maxFeePerGas!==void 0?{maxFeePerGas:i.maxFeePerGas}:{},...i?.signal!==void 0?{signal:i.signal}:{}})),v=await yn(e,o)({address:t.to,abi:a$1.DomfiTrading,functionName:P.functionName,args:P.args,account:c,chain:null,...f!==void 0?{value:f}:{},gas:g,...i?.nonce!==void 0?{nonce:i.nonce}:{},...i?.maxFeePerGas!==void 0?{maxFeePerGas:i.maxFeePerGas}:{},...i?.signal!==void 0?{signal:i.signal}:{}});return Tn(e,a,t.verb,v,s.trader)}catch(g){if((i?.signal?.aborted===true||F(g))&&L(e,"prepared trading send was aborted",g),le(g))throw g;return Me(e,"prepared trading write reverted",g)}}function xi(e,t){try{return BigInt(f.toString(t))}catch(n){return h(e,"market timeout orderId must be an integer string",void 0,n)}}async function Oi(e,t,n,r,i){let a=await Ne(e,t)(Z({address:M(e,"DomfiTradingStorage"),abi:a$1.DomfiTradingStorage,functionName:"pendingMarketOrders",args:[r]},i)),o=x(a,"blockNumber",0),s=x(a,"trade",3),d=x(s,"trader",4),c=x(s,"pairIndex",6),l=x(s,"collateral",0),p=b$1.toNumber(n.pairIndex);if(o===void 0||o<=0n||d===void 0||d===Ye||d.toLowerCase()!==n.wallet.toLowerCase()||c!==p||l===void 0||l<=0n)return b(e,"pending market order slot does not prove timeout identity");let u=await Ne(e,t)(Z({address:M(e,"DomfiTrading"),abi:a$1.DomfiTrading,functionName:"marketOrdersTimeout"},i)),f;if(typeof u=="bigint"&&u>=0n&&u<=65535n)f=u;else if(typeof u=="number"&&Number.isSafeInteger(u)&&u>=0&&u<=65535)f=BigInt(u);else return h(e,"market timeout read returned invalid data");let P=await si(e,t)(Z({},i));if(P.number===void 0||P.number<=o+f)return b(e,"pending market order is not yet eligible for timeout handling")}async function Nn(e$1,t,n){J(e$1,n?.signal,"market timeout send was aborted"),g$1(e$1,n,"trading.handleTradeMarketTimeout");let r=Je(e$1,"trading.handleTradeMarketTimeout"),i=Rn(e$1,void 0,"trading.handleTradeMarketTimeout"),a=ai(e$1,i,void 0,n,"trading.handleTradeMarketTimeout"),o=n?.delegation===void 0?{mode:"direct",trader:t.wallet,sender:a}:{mode:"delegated",trader:n.delegation.trader,sender:a};On(e$1,i),kn(e$1,i,a);let s=bn(i,a);if(!e(o.trader,t.wallet))return b(e$1,`trader ${o.trader} does not match timeout ref wallet ${t.wallet}`);if(o.mode==="direct"&&!e(a,t.wallet))return b(e$1,`send account ${a} does not match timeout ref wallet ${t.wallet}`);let d=xi(e$1,t.orderId);try{o.mode==="delegated"&&await Qe(e$1,r,o.trader,o.sender,n?.signal),await Oi(e$1,r,t,d,n?.signal),J(e$1,n?.signal,"market timeout send was aborted");}catch(c){throw (n?.signal?.aborted===true||F(c))&&L(e$1,"market timeout send was aborted",c),c}try{let c=encodeFunctionData({abi:a$1.DomfiTrading,functionName:"handleTradeMarketTimeout",args:[d]}),l=await yn(e$1,i)({address:M(e$1,"DomfiTrading"),abi:a$1.DomfiTrading,functionName:o.mode==="delegated"?"delegatedAction":"handleTradeMarketTimeout",args:o.mode==="delegated"?[o.trader,c]:[d],account:s,chain:null,...n?.gas!==void 0?{gas:n.gas}:{},...n?.nonce!==void 0?{nonce:n.nonce}:{},...n?.maxFeePerGas!==void 0?{maxFeePerGas:n.maxFeePerGas}:{},...n?.signal!==void 0?{signal:n.signal}:{}});return vn(e$1,r,l)}catch(c){if((n?.signal?.aborted===true||F(c))&&L(e$1,"market timeout send was aborted",c),le(c))throw c;return Me(e$1,"market timeout write reverted",c)}}var Ci="trading-prepare",vi="0x0000000000000000000000000000000000000000",pe=`0x${"00".repeat(32)}`,Ii=6e4;function Si(e){let t={sdkVersion:a,sourceTag:Ci,chainId:e.chain.chainId};return e.chain.registryAddress!==void 0&&(t.registryAddress=e.chain.registryAddress),t}function Wn(e,t,n,r){return {message:t,diagnostics:Si(e),...n!==void 0?{hint:n}:{},...r!==void 0?{cause:r}:{}}}function m(e,t,n,r){throw new ValidationError(Wn(e,t,n,r))}function E(e,t){if(e.publicClient!==void 0)return e.publicClient;throw new MissingPublicClientError(Wn(e,`${t} requires a public client`,"Pass publicClient to createDomfiClient."))}function fe(e,t){let n=e.chain.contracts[t];return n!==void 0?n:m(e,`chain profile is missing ${t} contract address`)}function ne(e,t){return typeof t.readContract!="function"&&m(e,"public client is missing readContract"),t.readContract}function Di(e,t){return typeof t.getBlock!="function"&&m(e,"public client is missing getBlock"),t.getBlock}function Vi(e){let t=e.multicall;return typeof t=="function"?t:void 0}function te(e){return e.catch(()=>{}),e}async function tt(e,t,n){let r=Vi(e);if(r===void 0)return t();let i=await n(),a=await r({contracts:i.calls,allowFailure:false});return i.decode(a)}function et(e){return typeof e=="string"&&/^0x[0-9a-fA-F]{64}$/.test(e)}function Li(e,t){let n=e.marketFeedByPair?.get(t);if(!(n===void 0||n.expiresAt<=Date.now()))return n.value}function Mi(e,t,n){let r=Li(e,t);if(r!==void 0)return r;e.marketFeedByPair??=new Map;let i=e.marketFeedByPair,a=n().then(o=>(o===pe&&i.get(t)?.value===a&&i.delete(t),o),o=>{throw i.get(t)?.value===a&&i.delete(t),o});return i.set(t,{value:a,expiresAt:Date.now()+Ii}),a}function _n(e){let t=e.chain?.contracts?.multicall3?.address;if(!(typeof t!="string"||!t.startsWith("0x")))return {address:t,abi:a$1.Multicall3,functionName:"getCurrentBlockTimestamp"}}async function ue(e,t){let n=await Di(e,t)();return BigInt(n.timestamp)*1000n}function qn(e,t){return typeof t=="bigint"?t*1000n:m(e,"multicall block timestamp read returned invalid data")}function U(e,t){return encodeFunctionData({abi:a$1.DomfiTrading,functionName:e,args:t})}function W(e,t){return e.mode==="direct"?t:U("delegatedAction",[e.trader,t])}function j(e,t,n,r){let i$1=t?.delegation===void 0?i(e,{...t,account:n}):i(e,t);return i$1.trader===void 0||i$1.trader.toLowerCase()!==n.toLowerCase()?m(e,`${r} wallet ${n} does not match trader ${i$1.trader}`):i$1}function Ni(e,t){return t===void 0?void 0:tn(t,{chainId:e.chain.chainId})}function Fi(e,t){return t===void 0?e:`${e}${t.slice(2)}`}function Ue(e){return Object.freeze(e.slice())}function D(e){return Object.freeze(e===void 0?{status:"unchecked"}:{status:"checked",approvals:Ue(e)})}function Ei(e){return e==="openMarket"||e==="openLimit"||e==="openStop"||e==="closeMarket"||e==="updateTakeProfit"||e==="updateStopLoss"||e==="removeCollateral"}function Ui(e){return Object.freeze({...e})}function Wi(e){return Object.freeze({...e,...e.initiatedLog!==void 0?{initiatedLog:Object.freeze({...e.initiatedLog})}:{}})}function _i(e){return e.status==="checked"?e.approvals.slice():[]}function qi(e){return e.verb!=="openMarket"?void 0:{kind:"openMarket",params:{orderKind:"market",pairIndex:b$1.from(e.pairIndex),direction:e.buy?"long":"short",collateral:g$2.fromRaw(e.collateral),leverage:k$1.fromRaw(BigInt(e.leverage)),slippage:q$1.fromRaw(e.slippageP),...e.requestedOpenPrice!==void 0?{wantedPrice:i$1.fromRaw(e.requestedOpenPrice)}:{},...e.tp>0n?{takeProfit:i$1.fromRaw(e.tp)}:{},...e.sl>0n?{stopLoss:i$1.fromRaw(e.sl)}:{},...e.referralCodeId!==void 0?{referralCodeId:e.referralCodeId}:{}}}}function Hi(e){return typeof e=="object"&&e!==null&&("writeContract"in e&&typeof e.writeContract=="function"||"sendTransaction"in e&&typeof e.sendTransaction=="function")}function zi(e){let[t,n]=e;return Hi(t)?n===void 0?{walletClient:t}:{walletClient:t,opts:n}:t===void 0?n===void 0?{}:{opts:n}:{opts:t}}function _(e,t){let n=fe(e,"DomfiTrading"),r=Ue(t.warnings??[]),i=Ue(_i(t.requiredApprovals)),a=Object.freeze({warnings:r,feeCharging:Ei(t.verb),...t.metadata?.approvalAmountRaw!==void 0?{approvalAmountRaw:t.metadata.approvalAmountRaw}:{},...t.metadata?.feePairIndex!==void 0?{feePairIndex:t.metadata.feePairIndex}:{},...t.metadata?.positionRef!==void 0?{positionRef:Ui(t.metadata.positionRef)}:{},...t.metadata?.triggerRef!==void 0?{triggerRef:Wi(t.metadata.triggerRef)}:{},...t.metadata?.preservedTrigger!==void 0?{preservedTrigger:Object.freeze({...t.metadata.preservedTrigger})}:{},...t.metadata?.hasReferralTrailer===true?{hasReferralTrailer:true}:{},...t.metadata?.dataSuffix!==void 0?{dataSuffix:t.metadata.dataSuffix}:{},...t.metadata?.executionMode!==void 0?{executionMode:t.metadata.executionMode}:{},...t.metadata?.preparedTrader!==void 0?{preparedTrader:t.metadata.preparedTrader}:{},...t.metadata?.preparedSender!==void 0?{preparedSender:t.metadata.preparedSender}:{}}),o=Object.freeze({approvals:i,warnings:r,...t.normalizedParams!==void 0?{normalizedParams:t.normalizedParams}:{},...t.estimatedOracleFeeWei!==void 0?{oracleFeeWei:t.estimatedOracleFeeWei}:{},...t.preflight?.checks!==void 0?{checks:Ue(t.preflight.checks)}:{},...t.preflight?.estimatedOpeningFee!==void 0?{estimatedOpeningFee:Object.freeze({...t.preflight.estimatedOpeningFee})}:{},...t.preflight?.estimatedClosingFee!==void 0?{estimatedClosingFee:Object.freeze({...t.preflight.estimatedClosingFee})}:{},...t.preflight?.resultingLeverage!==void 0?{resultingLeverage:Object.freeze({...t.preflight.resultingLeverage})}:{},...t.preflight?.executionPriceBounds!==void 0?{executionPriceBounds:Object.freeze({...t.preflight.executionPriceBounds})}:{},...t.preflight?.estimatedLiquidationPrice!==void 0?{estimatedLiquidationPrice:t.preflight.estimatedLiquidationPrice}:{}}),s=Object.freeze({verb:t.verb,to:n,data:t.data,requiredApprovals:t.requiredApprovals,summary:async()=>o,simulate:async d=>Ln(e,s,a,d),send:async(...d)=>{let{walletClient:c,opts:l}=zi(d);return Mn(e,s,a,c,l)},...t.preparedAccount!==void 0?{preparedAccount:t.preparedAccount}:{},...t.estimatedOracleFeeWei!==void 0?{estimatedOracleFeeWei:t.estimatedOracleFeeWei,value:t.estimatedOracleFeeWei}:{}});return s}async function $(e,t,n){let r=await ne(e,t)(We(e,n));return _e(e,r)}function We(e,t){return {address:fe(e,"DomfiPairsStorage"),abi:a$1.DomfiPairsStorage,functionName:"pairOracleFee",args:[t]}}function nt(e,t){return {address:e.chain.collateral.tokenAddress,abi:a$1.IERC20,functionName:"allowance",args:[t,e.chain.collateral.tradingStorageSpender]}}function rt(e,t){return {address:fe(e,"DomfiOracle"),abi:a$1.DomfiOracle,functionName:"getValue",args:[t]}}function _e(e,t){return typeof t=="bigint"?t:m(e,"pair oracle fee read returned invalid data")}function it(e,t){return typeof t=="bigint"?t:m(e,"allowance read returned invalid data")}function at(e,t,n,r){if(t===void 0)return D();if(n===void 0)return D([]);let i=g$2.fromRaw(r??0n),a=g$2.fromRaw(n);return D([{owner:t,token:e.chain.collateral.tokenAddress,spender:e.chain.collateral.tradingStorageSpender,currentAllowance:i,requiredAllowance:a,action:(r??0n)>=n?"none":"approve"}])}async function ot(e,t,n,r){if(n===void 0)return D();if(r===void 0)return D([]);let i=it(e,await ne(e,t)(nt(e,n)));return at(e,n,r,i)}async function st(e,t,n){return Mi(e,n,async()=>{let r=await $i(e,n);return r!==void 0?r:ji(e,t,n)})}async function ji(e,t,n){let r=fe(e,"DomfiPairsStorage"),i;try{let a=await ne(e,t)({address:r,abi:a$1.DomfiPairsStorage,functionName:"pairFeed",args:[n]});return et(a)?a:m(e,"pair oracle feed read returned invalid data")}catch(a){i=a;}try{let a=await ne(e,t)({address:r,abi:a$1.DomfiPairsStorage,functionName:"getFeedInfo",args:[n]}),o=Array.isArray(a)?a[0]:void 0;return et(o)?o:m(e,"pair oracle feed read returned invalid data")}catch(a){throw a instanceof ValidationError?a:i??a}}async function $i(e,t){if(e.api!==void 0)try{let n=await e.api.markets.get(b$1.from(t));if(n.freshness.isStale)return;let r=n.data.feedId;if(b$1.toNumber(n.data.pairIndex)===t&&et(r)&&r!==pe)return r}catch{return}}async function Hn(e,t,n){let r=await st(e,t,n);if(r===pe)return m(e,"pair oracle feed is not configured");let i=await ne(e,t)(rt(e,r)),a=dt(e,i),o=await ue(e,t);return ct(e,a,o)}function dt(e,t){if(!Array.isArray(t)||t.length<2)return m(e,"oracle value read returned invalid data");let[n,r]=t;if(typeof n!="bigint"||n<=0n)return m(e,"oracle value must be positive");if(typeof r!="bigint"&&typeof r!="number")return m(e,"oracle timestamp read returned invalid data");try{return {priceRaw:i$1.toRaw(i$1.fromRaw(n)),oracleTimestampMs:BigInt(r)}}catch(i){return m(e,"oracle value is outside the supported price range",i instanceof Error?i.message:void 0,i)}}function ct(e,t,n){let r=BigInt(e.chain.oracleStaleThresholdMs??6e4);return t.oracleTimestampMs<=0n||n-t.oracleTimestampMs>r?m(e,"oracle value is stale"):t.priceRaw}async function Bi(e,t,n,r,i){return tt(t,async()=>{let a=$(e,t,n),o=ot(e,t,r,i);te(o);let s=await a,d=await o;return {estimatedOracleFeeWei:s,requiredApprovals:d}},()=>{let a=[We(e,n)],o=r!==void 0&&i!==void 0;return o&&a.push(nt(e,r)),{calls:a,decode:s=>{let d=_e(e,s[0]),c=o?it(e,s[1]):void 0;return {estimatedOracleFeeWei:d,requiredApprovals:at(e,r,i,c)}}}})}async function Gi(e,t,n,r,i){return tt(t,async()=>{let a=Hn(e,t,n),o=$(e,t,n),s=ot(e,t,r,i);te(o),te(s);let d=await a,c=await o,l=await s;return {priceRaw:d,estimatedOracleFeeWei:c,requiredApprovals:l}},async()=>{let a=await st(e,t,n);if(a===pe)return m(e,"pair oracle feed is not configured");let o=[rt(e,a),We(e,n)],s=r!==void 0&&i!==void 0;s&&o.push(nt(e,r));let d=_n(t),c=d===void 0?void 0:o.length;d!==void 0&&o.push(d);let l=c===void 0?ue(e,t):void 0;return l!==void 0&&te(l),{calls:o,decode:async p=>{let u=dt(e,p[0]),f=c===void 0?await(l??ue(e,t)):qn(e,p[c]),P=ct(e,u,f),g=_e(e,p[1]),v=s?it(e,p[2]):void 0;return {priceRaw:P,estimatedOracleFeeWei:g,requiredApprovals:at(e,r,i,v)}}}})}async function Ki(e,t,n){return tt(t,async()=>{let r=Hn(e,t,n),i=$(e,t,n);te(i);let a=await r,o=await i;return {priceRaw:a,estimatedOracleFeeWei:o}},async()=>{let r=await st(e,t,n);if(r===pe)return m(e,"pair oracle feed is not configured");let i=[rt(e,r),We(e,n)],a=_n(t),o=a===void 0?void 0:i.length;a!==void 0&&i.push(a);let s=o===void 0?ue(e,t):void 0;return s!==void 0&&te(s),{calls:i,decode:async d=>{let c=dt(e,d[0]),l=o===void 0?await(s??ue(e,t)):qn(e,d[o]);return {priceRaw:ct(e,c,l),estimatedOracleFeeWei:_e(e,d[1])}}}})}function ge(e,t){return {pairIndex:De(t.pairIndex,(n,r)=>m(e,n,r)),index:on(t.index,(n,r)=>m(e,n,r))}}function lt(e,t){return {pairIndex:De(t.pairIndex,(n,r)=>m(e,n,r)),index:sn(t.index,(n,r)=>m(e,n,r))}}async function Xi(e,t,n,r,i,a){let o=a==="limit"?1:2,s;try{s=await ne(e,t)({address:fe(e,"DomfiTradingStorage"),abi:a$1.DomfiTradingStorage,functionName:"getOpenLimitOrder",args:[i,n,r]});}catch(u){return m(e,"open trigger order slot was not found",void 0,u)}if(typeof s!="object"||s===null)return m(e,"open trigger order slot read returned invalid data");let d=z(s,"trader",0),c=z(s,"pairIndex",8),l=z(s,"index",9),p=z(s,"orderType",11);return d!==void 0&&d.toLowerCase()===i.toLowerCase()&&c===n&&l===r&&p===o?s:m(e,"open trigger order slot was not found")}function Fn(e){return e===void 0||e===0n?void 0:i$1.fromRaw(e)}function Yi(e,t){return typeof t=="boolean"?t:m(e,"open trigger order slot has invalid buy value")}function Zi(e,t){let n;if(typeof t=="bigint")n=t;else if(typeof t=="number"&&Number.isSafeInteger(t))n=BigInt(t);else return m(e,"open trigger order slot has invalid leverage value");try{return k$1.fromRaw(n)}catch(r){return m(e,"open trigger order slot has invalid leverage value",r instanceof Error?r.message:void 0,r)}}function Ji(e,t){if(typeof t!="bigint")return m(e,"open trigger order slot has invalid target price");try{return i$1.fromRaw(t)}catch(n){return m(e,"open trigger order slot has invalid target price",n instanceof Error?n.message:void 0,n)}}async function ut(e,t){let n=E(e,"trading.readOpenTriggerSlotContext"),{pairIndex:r,index:i}=lt(e,t),a=await Xi(e,n,r,i,t.wallet,t.orderType),o=z(a,"buy",10),s=z(a,"leverage",7),d=z(a,"targetPrice",4),c=En(a,"tp",5),l=En(a,"sl",6);(o===void 0||s===void 0||d===void 0)&&m(e,"open trigger order slot is missing action context");let p=Yi(e,o),u=Zi(e,s),f=Ji(e,d);return {wallet:t.wallet,pairIndex:t.pairIndex,index:t.index,orderType:t.orderType,direction:p?"long":"short",leverage:u,targetPrice:f,currentTp:Fn(c),currentSl:Fn(l),currentTpRaw:c,currentSlRaw:l}}function z(e,t,n){if(Array.isArray(e))return e[n];if(typeof e=="object"&&e!==null&&t in e)return e[t]}function En(e,t,n){if(e===void 0)return;if(Array.isArray(e)){let i=e[n];return typeof i=="bigint"?i:void 0}let r=e[t];return typeof r=="bigint"?r:void 0}async function zn(e,t,n){let r=i(e,n),i$1=E(e,"trading.prepareOpenTrade"),a=(P,g)=>m(e,P,g),o=dn(t,a),s=r.trader,d=o.requestedOpenPrice===void 0?await Gi(e,i$1,o.pairIndex,s,o.collateral):{priceRaw:o.requestedOpenPrice,...await Bi(e,i$1,o.pairIndex,s,o.collateral)};Ve({takeProfitRaw:o.tp,stopLossRaw:o.sl,openPriceRaw:d.priceRaw,buy:o.buy},a);let c={collateral:o.collateral,openPrice:d.priceRaw,tp:o.tp,sl:o.sl,trader:r.trader??vi,leverage:o.leverage,pairIndex:o.pairIndex,index:0,buy:o.buy},l=await mn(e,o,{openPriceRaw:d.priceRaw}),p=U("openTrade",[c,o.orderType,o.slippageP]),u=Ni(e,o.referralCodeId),f=Fi(p,u);return _(e,{verb:o.verb,data:W(r,f),requiredApprovals:d.requiredApprovals,estimatedOracleFeeWei:d.estimatedOracleFeeWei,warnings:o.warnings,normalizedParams:qi(o),preflight:l,metadata:{approvalAmountRaw:o.collateral,feePairIndex:o.pairIndex,executionMode:r.mode,...r.trader!==void 0?{preparedTrader:r.trader}:{},...r.sender!==void 0?{preparedSender:r.sender}:{},...u!==void 0?{hasReferralTrailer:true}:{},...r.mode==="direct"&&u!==void 0?{dataSuffix:u}:{}},...r.sender!==void 0?{preparedAccount:r.sender}:{}})}async function jn(e,t,n,r){let i=j(e,r,t.wallet,"position"),a=E(e,"trading.prepareClosePosition"),{pairIndex:o,index:s}=ge(e,t),d=cn(n,o,s,(p,u)=>m(e,p,u)),c=d.wantedPrice===void 0?await Ki(e,a,d.pairIndex):{priceRaw:d.wantedPrice,estimatedOracleFeeWei:await $(e,a,o)},l=U("closeTradeMarket",[d.pairIndex,d.index,d.closePercent,d.slippageP,c.priceRaw]);return _(e,{verb:"closeMarket",data:W(i,l),requiredApprovals:D([]),estimatedOracleFeeWei:c.estimatedOracleFeeWei,...i.sender!==void 0?{preparedAccount:i.sender}:{},preflight:{checks:[g({closePercent:r$2.fromRaw(BigInt(d.closePercent))})]},metadata:{feePairIndex:o,positionRef:t,executionMode:i.mode,preparedTrader:i.trader,...i.sender!==void 0?{preparedSender:i.sender}:{}}})}async function $n(e,t,n,r){let i=j(e,r,t.wallet,"position"),a=E(e,"trading.prepareUpdateTakeProfit"),{pairIndex:o,index:s}=ge(e,t),d=de(n.takeProfit,"takeProfit",(p,u)=>m(e,p,u)),c=await $(e,a,o),l=U("updateTp",[o,s,d.value]);return _(e,{verb:"updateTakeProfit",data:W(i,l),requiredApprovals:D([]),estimatedOracleFeeWei:c,...i.sender!==void 0?{preparedAccount:i.sender}:{},metadata:{feePairIndex:o,positionRef:t,executionMode:i.mode,preparedTrader:i.trader,...i.sender!==void 0?{preparedSender:i.sender}:{}}})}async function Bn(e,t,n,r){let i=j(e,r,t.wallet,"position"),a=E(e,"trading.prepareUpdateStopLoss"),{pairIndex:o,index:s}=ge(e,t),d=de(n.stopLoss,"stopLoss",(p,u)=>m(e,p,u)),c=await $(e,a,o),l=U("updateSl",[o,s,d.value]);return _(e,{verb:"updateStopLoss",data:W(i,l),requiredApprovals:D([]),estimatedOracleFeeWei:c,...i.sender!==void 0?{preparedAccount:i.sender}:{},metadata:{feePairIndex:o,positionRef:t,executionMode:i.mode,preparedTrader:i.trader,...i.sender!==void 0?{preparedSender:i.sender}:{}}})}async function Gn(e,t,n,r){let i=j(e,r,t.wallet,"position"),a=E(e,"trading.prepareTopUpCollateral"),{pairIndex:o,index:s}=ge(e,t),d=Se(n.collateral,"collateral",(p,u)=>m(e,p,u)),c=await ot(e,a,i.trader,d),l=U("topUpCollateral",[o,s,d]);return _(e,{verb:"topUpCollateral",data:W(i,l),requiredApprovals:c,...i.sender!==void 0?{preparedAccount:i.sender}:{},metadata:{approvalAmountRaw:d,positionRef:t,executionMode:i.mode,preparedTrader:i.trader,...i.sender!==void 0?{preparedSender:i.sender}:{}}})}async function Kn(e,t,n,r){let i=j(e,r,t.wallet,"position"),a=E(e,"trading.prepareRemoveCollateral"),{pairIndex:o,index:s}=ge(e,t),d=Se(n.collateral,"collateral",(p,u)=>m(e,p,u)),c=await $(e,a,o),l=U("removeCollateral",[o,s,d]);return _(e,{verb:"removeCollateral",data:W(i,l),requiredApprovals:D([]),estimatedOracleFeeWei:c,...i.sender!==void 0?{preparedAccount:i.sender}:{},metadata:{feePairIndex:o,positionRef:t,executionMode:i.mode,preparedTrader:i.trader,...i.sender!==void 0?{preparedSender:i.sender}:{}}})}async function Xn(e,t,n,r){let i=j(e,r,t.wallet,"trigger order");E(e,"trading.prepareUpdateOpenLimitOrder");let{pairIndex:a,index:o}=lt(e,t),s=(ae,ye)=>m(e,ae,ye),d=ln(n,s),c=de(n.takeProfit,"takeProfit",s,{optional:true}),l=de(n.stopLoss,"stopLoss",s,{optional:true}),p=c.status==="provided"&&c.value!==0n||l.status==="provided"&&l.value!==0n,u=c.status==="omitted"||l.status==="omitted"||p?await ut(e,t):void 0,f=c.status==="provided"?c.value:u?.currentTpRaw,P=l.status==="provided"?l.value:u?.currentSlRaw;if(f===void 0||P===void 0)return m(e,"open trigger slot is missing TP/SL");u!==void 0&&Ve({takeProfitRaw:f,stopLossRaw:P,openPriceRaw:d,buy:u.direction==="long"},s);let g=u===void 0?void 0:{...c.status==="omitted"?{tp:f}:{},...l.status==="omitted"?{sl:P}:{}},v=U("updateOpenLimitOrder",[a,o,d,f,P]);return _(e,{verb:"updateOpenLimitOrder",data:W(i,v),requiredApprovals:D([]),...i.sender!==void 0?{preparedAccount:i.sender}:{},metadata:{triggerRef:t,...g!==void 0?{preservedTrigger:g}:{},executionMode:i.mode,preparedTrader:i.trader,...i.sender!==void 0?{preparedSender:i.sender}:{}}})}async function Yn(e,t,n){let r=j(e,n,t.wallet,"trigger order");E(e,"trading.prepareCancelOpenLimitOrder");let{pairIndex:i,index:a}=lt(e,t),o=U("cancelOpenLimitOrder",[i,a]);return _(e,{verb:"cancelOpenLimitOrder",data:W(r,o),requiredApprovals:D([]),...r.sender!==void 0?{preparedAccount:r.sender}:{},metadata:{triggerRef:t,executionMode:r.mode,preparedTrader:r.trader,...r.sender!==void 0?{preparedSender:r.sender}:{}}})}var ia="runtime-guards";function V(e){let t={sdkVersion:a,sourceTag:ia,chainId:e.chain.chainId};return e.chain.registryAddress!==void 0&&(t.registryAddress=e.chain.registryAddress),t}function me(e,t,n){let r={message:t,diagnostics:V(e)};return n===void 0?r:{...r,hint:n}}function ho(e,t="this operation"){if(e.publicClient!==void 0)return e.publicClient;throw new MissingPublicClientError(me(e,`${t} requires a public client`,"Pass publicClient to createDomfiClient."))}function aa(e,t="this operation"){if(e.walletClient!==void 0)return e.walletClient;throw new MissingWalletClientError(me(e,`${t} requires a wallet client`,"Pass walletClient to createDomfiClient."))}function Zn(e){let t=e?.account;if(t!==void 0){if(typeof t=="string")return t;if(typeof t=="object"&&"address"in t&&typeof t.address=="string")return t.address}}function yo(e,t,n="this operation"){let r=t??e.account??Zn(e.walletClient);if(r!==void 0)return r;throw new MissingAccountError(me(e,`${n} requires an account`,"Pass account to createDomfiClient, pass opts.account, or use a connected wallet client."))}function Ro(e,t){let n=aa(e),r=n.chain?.id;if(r!==void 0&&r!==e.chain.chainId)throw new WalletChainMismatchError(me(e,`wallet client chain ${r} does not match DomFi chain ${e.chain.chainId}`,"Use a wallet client connected to the same chain as createDomfiClient."));let i=Zn(n);if(i!==void 0&&i.toLowerCase()!==t.toLowerCase())throw new WalletAccountMismatchError(me(e,`wallet client account ${i} does not match requested account ${t}`,"Use the connected wallet account or pass the matching account option."))}function oa(e){return(async(t,n)=>r$1(e,t,n))}function sa(e){return (t,n)=>Nn(e,t,n)}function xo(e){let t={prepareOpenTrade:((r,i)=>zn(e,r,i)),prepareClosePosition:(r,i,a)=>jn(e,r,i,a),prepareUpdateTakeProfit:(r,i,a)=>$n(e,r,i,a),prepareUpdateStopLoss:(r,i,a)=>Bn(e,r,i,a),prepareTopUpCollateral:(r,i,a)=>Gn(e,r,i,a),prepareRemoveCollateral:(r,i,a)=>Kn(e,r,i,a),prepareUpdateOpenLimitOrder:(r,i,a)=>Xn(e,r,i,a),prepareCancelOpenLimitOrder:(r,i)=>Yn(e,r,i),handleTradeMarketTimeout:sa(e),recoverTransaction:oa(e)};return e.api===void 0?t:{...t,trackOrder:(r,i)=>p(e,r,i),trackTransaction:(r,i)=>s(e,r,i)}}function y(e,t,n){throw new ValidationError({message:t,diagnostics:V(e),...n!==void 0?{cause:n}:{}})}function R(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ca(e,t,n,r,i){let a=R(t,n),o=R(t,r);a===o&&y(e,`${i} requires exactly one of ${n} or ${r}`);}function qe(e,t,n,r){for(let i of n)R(t,i)&&y(e,`${r} cannot include ${i}`);}function ie(e,t,n,r){typeof r!="bigint"&&y(e,`${n} is invalid`);try{return t.fromRaw(r)}catch(i){return y(e,`${n} is invalid`,i)}}function Jn(e,t,n){typeof n!="bigint"&&y(e,`${t} is invalid`);try{return k.fromRaw(n)}catch(r){return y(e,`${t} is invalid`,r)}}function B(e,t,n){return ie(e,i$1,t,n)}function ir(e,t,n){i$1.toRaw(n)===0n&&y(e,`${t} cannot be zero; zero is reserved as a trigger omission sentinel`);}function Te(e,t,n,r,i){let a=i$1.toRaw(n);ir(e,t,n);let o=i$1.toRaw(r);(t==="takeProfit"?i==="long"?a>o:a<o:i==="long"?a<o:a>o)||y(e,`${t} is on the wrong side of the trigger price`);}function mt(e,t){if(t==="long"||t==="short")return t;y(e,"direction must be long or short");}function la(e){return Ae(e)&&R(e,"clear")&&e.clear===true}function ua(e,t){return ie(e,k$1,"leverage",t)}function ar(e,t){return ie(e,q$1,"slippage",t)}function pa(e,t){return ie(e,r$2,"closePercent",t)}function or(e,t){return ie(e,g$2,"collateral",t)}function fa(e,t){return ie(e,l,"notionalUsd",t)}function ga(e,t,n){try{return o({notionalUsd:fa(e,t),leverage:n})}catch(r){return y(e,"notional sizing is invalid",r)}}function sr(e){let t=e.walletClient?.account;if(t!==void 0){if(typeof t=="string")return t;if(typeof t=="object"&&"address"in t&&typeof t.address=="string")return t.address}}function re(e,t){let n;for(let r of t)if(r.wallet!==void 0){if(n===void 0){n={label:r.label,wallet:r.wallet};continue}if(n.wallet.toLowerCase()!==r.wallet.toLowerCase())throw new WalletAccountMismatchError({message:`${r.label} ${r.wallet} does not match ${n.label} ${n.wallet}`,diagnostics:V(e)})}return n?.wallet}function ma(e,t,n){let r=t?.account!==void 0?re(e,[{label:"options account",wallet:t.account},{label:"position input wallet",wallet:n}]):re(e,[{label:"configured account",wallet:e.account},{label:"wallet client account",wallet:sr(e)},{label:"position input wallet",wallet:n}]);if(r!==void 0)return r;throw new MissingAccountError({message:"position ref resolution requires an account or explicit wallet",diagnostics:V(e)})}function Pa(e,t,n){return t?.delegation!==void 0?(re(e,[{label:"delegation trader",wallet:t.delegation.trader},{label:"position input wallet",wallet:n}]),t.delegation.trader):ma(e,t,n)}function Ta(e,t,n,r="resolved position wallet"){if(t?.account!==void 0){re(e,[{label:"options account",wallet:t.account},{label:r,wallet:n}]);return}re(e,[{label:"configured account",wallet:e.account},{label:"wallet client account",wallet:sr(e)},{label:r,wallet:n}]);}function we(e,t,n,r="resolved position wallet"){if(t?.delegation!==void 0){re(e,[{label:"delegation trader",wallet:t.delegation.trader},{label:r,wallet:n}]);return}Ta(e,t,n,r);}function dr(e,t){return e.toLowerCase()===t.toLowerCase()}function wa(e,t){return dr(e.wallet,t.wallet)&&e.pairIndex===t.pairIndex&&e.index===t.index&&e.chainId===t.chainId&&e.orderType===t.orderType&&e.initiatedTxHash.toLowerCase()===t.initiatedTxHash.toLowerCase()&&e.initiatedLog.blockNumber===t.initiatedLog.blockNumber&&e.initiatedLog.transactionIndex===t.initiatedLog.transactionIndex&&e.initiatedLog.logIndex===t.initiatedLog.logIndex&&e.lifecycleKey===t.lifecycleKey&&e.orderId===t.orderId}function Aa(e,t){return dr(e.wallet,t.wallet)&&e.pairIndex===t.pairIndex&&e.index===t.index&&e.chainId===t.chainId&&e.orderType===t.orderType&&e.lifecycleKey===t.lifecycleKey&&e.orderId===t.orderId&&e.initiatedTxHash.toLowerCase()===t.initiatedTxHash.toLowerCase()&&e.initiatedEventType===t.initiatedEventType&&e.initiatedLog?.blockNumber===t.initiatedLog?.blockNumber&&e.initiatedLog?.transactionIndex===t.initiatedLog?.transactionIndex&&e.initiatedLog?.logIndex===t.initiatedLog?.logIndex}function ha(e,t){return e.source!==t.source?false:e.source==="api"?t.source!=="api"?false:Aa(e,t):t.source!=="receipt"?false:wa(e,t)}function Ae(e){return typeof e=="object"&&e!==null}function ya(e){if(!Ae(e)||e.source!=="api")return false;let t=e.initiatedLog;return typeof e.wallet=="string"&&typeof e.pairIndex=="number"&&typeof e.index=="number"&&typeof e.chainId=="number"&&typeof e.lifecycleKey=="string"&&(e.orderId===void 0||typeof e.orderId=="string")&&(e.orderType==="limit"||e.orderType==="stop")&&typeof e.initiatedTxHash=="string"&&typeof e.initiatedEventType=="string"&&(t===void 0||Ae(t)&&typeof t.blockNumber=="bigint"&&typeof t.transactionIndex=="number"&&typeof t.logIndex=="number")}function Mo(e,t){try{return cr(e,t),!0}catch{return false}}function cr(e,t){let n=e.verifiedRef;if(n===void 0||typeof n!="object"||n===null)throw new ValidationError({message:"open trigger order is missing verifiedRef",diagnostics:{sdkVersion:a,sourceTag:"actions",chainId:t},hint:"For account orders, use verifiedOpenTriggerOrderRefFromAccountOrder or a fresh API order with verified identity. Pass placement receipt refs directly as TriggerOrderInput."});if(!ya(n))throw new IdentityMismatchError({message:"open trigger account order verifiedRef must be API-derived",diagnostics:{sdkVersion:a,sourceTag:"actions",chainId:t}});let r;try{r=y$1(e,t);}catch(i){throw new IdentityMismatchError({message:"open trigger order verifiedRef does not match order identity fields",diagnostics:{sdkVersion:a,sourceTag:"actions",chainId:t},cause:i})}if(!ha(n,r))throw new IdentityMismatchError({message:"open trigger order verifiedRef does not match order identity fields",diagnostics:{sdkVersion:a,sourceTag:"actions",chainId:t}})}function pt(e,t,n){if(t.wallet.toLowerCase()!==n.wallet.toLowerCase())throw new WalletAccountMismatchError({message:`resolved position wallet ${t.wallet} does not match requested wallet ${n.wallet}`,diagnostics:V(e)});if(t.pairIndex!==n.pairIndex||t.index!==n.index)throw new IdentityMismatchError({message:"resolved position pair/index does not match requested position ref",diagnostics:V(e)});if(n.tradeId!==void 0&&t.tradeId!==n.tradeId)throw new IdentityMismatchError({message:"resolved position trade id does not match requested position ref",diagnostics:V(e)})}function lr(e,t){if(t.status==="pending")throw new ReadModelNotReadyError({message:"position read model is not ready",diagnostics:V(e)});return (t.status!=="found"||t.position?.kind!=="open_position")&&y(e,"position was not found"),t.position}function Qn(e,t,n){if(typeof n=="object"&&n!==null)throw new ValidationError({message:`openMarket ${t} must be a concrete price; percent inputs are only supported by position trigger updates`,diagnostics:V(e)});let r=B(e,t,n);return ir(e,t,r),r}function he(e,t,n,r$1){let i;if(typeof n!="object"||n===null)return i=B(e,t,n),Te(e,t,i,r$1.basePrice,r$1.direction),i;qe(e,n,["clear"],t);let a=R(n,"pnlPercent"),o=R(n,"priceDeltaPercent");a===o&&y(e,`${t} requires exactly one percent input`);let s=a?n.pnlPercent:void 0,d=o?n.priceDeltaPercent:void 0;try{if(a){let l={basePrice:r$1.basePrice,pnlPercent:Jn(e,`${t} pnlPercent`,s),leverage:r$1.leverage,direction:r$1.direction};return i=t==="takeProfit"?p$1(l):q(l),Te(e,t,i,r$1.basePrice,r$1.direction),i}let c={basePrice:r$1.basePrice,priceDeltaPercent:Jn(e,`${t} priceDeltaPercent`,d),direction:r$1.direction};return i=t==="takeProfit"?r(c):s$1(c),Te(e,t,i,r$1.basePrice,r$1.direction),i}catch(c){return y(e,`${t} percent trigger is invalid`,c)}}function er(e){return !Ae(e)||!R(e,"clear")}function ft(e,t,n,r){if(Ae(n)&&R(n,"clear"))return (!la(n)||R(n,"pnlPercent")||R(n,"priceDeltaPercent"))&&y(e,`${t} clear cannot be combined with percent inputs`),{clear:true};if(r===void 0&&y(e,`${t} update requires trigger context`),typeof n=="object"&&n!==null)return he(e,t,n,r);let i=B(e,t,n);return Te(e,t,i,r.basePrice,r.direction),i}function Pt(e,t,n){ca(e,t,"notionalUsd","collateral",n);let r=R(t,"collateral"),i=r?"collateral":"notionalUsd";(r?t.collateral:t.notionalUsd)===void 0&&y(e,`${n} ${i} is invalid`);let o=ua(e,t.leverage);return {collateral:r?or(e,t.collateral):ga(e,t.notionalUsd,o),leverage:o}}function No(e,t){let n=t;qe(e,n,["entryPrice","triggerPrice","wantedPrice"],"openMarket");let{collateral:r,leverage:i}=Pt(e,n,"openMarket"),a=mt(e,n.direction);return {orderKind:"market",pairIndex:t.pairIndex,direction:a,collateral:r,leverage:i,slippage:ar(e,t.slippage),...n.referralCodeId!==void 0?{referralCodeId:n.referralCodeId}:{},...n.takeProfit!==void 0?{takeProfit:Qn(e,"takeProfit",n.takeProfit)}:{},...n.stopLoss!==void 0?{stopLoss:Qn(e,"stopLoss",n.stopLoss)}:{}}}function Fo(e,t){let n=t;qe(e,n,["slippage","triggerPrice"],"openLimit");let{collateral:r,leverage:i}=Pt(e,n,"openLimit"),a=B(e,"entryPrice",t.entryPrice),o=mt(e,n.direction),s={basePrice:a,direction:o,leverage:i};return {orderKind:"limit",pairIndex:t.pairIndex,direction:o,collateral:r,leverage:i,entryPrice:a,...n.referralCodeId!==void 0?{referralCodeId:n.referralCodeId}:{},...R(n,"takeProfit")?{takeProfit:he(e,"takeProfit",n.takeProfit,s)}:{},...R(n,"stopLoss")?{stopLoss:he(e,"stopLoss",n.stopLoss,s)}:{}}}function Eo(e,t){let n=t;qe(e,n,["slippage","entryPrice"],"openStop");let{collateral:r,leverage:i}=Pt(e,n,"openStop"),a=B(e,"triggerPrice",t.triggerPrice),o=mt(e,n.direction),s={basePrice:a,direction:o,leverage:i};return {orderKind:"stop",pairIndex:t.pairIndex,direction:o,collateral:r,leverage:i,triggerPrice:a,...n.referralCodeId!==void 0?{referralCodeId:n.referralCodeId}:{},...R(n,"takeProfit")?{takeProfit:he(e,"takeProfit",n.takeProfit,s)}:{},...R(n,"stopLoss")?{stopLoss:he(e,"stopLoss",n.stopLoss,s)}:{}}}function Uo(e,t){return {...t.closePercent!==void 0?{closePercent:pa(e,t.closePercent)}:{},slippage:ar(e,t.slippage),...t.wantedPrice!==void 0?{wantedPrice:B(e,"wantedPrice",t.wantedPrice)}:{}}}async function Wo(e,t,n){if("source"in t)return t.chainId!==e.chain.chainId&&y(e,"position ref chain does not match client chain"),we(e,n,t.wallet),{ref:t};if("kind"in t){if(t.kind!=="open_position")throw new ReadModelNotReadyError({message:"position is not open yet",diagnostics:V(e)});return we(e,n,t.wallet),{ref:x$1(t,e.chain.chainId),position:t}}let r=Pa(e,n,t.wallet),i=await e.api.account.position(r,{pairIndex:t.pairIndex,index:t.tradeIndex},n),a=lr(e,i.data);return pt(e,a,{wallet:r,pairIndex:t.pairIndex,index:t.tradeIndex}),{ref:x$1(a,e.chain.chainId),position:a}}function _o(e,t,n){let r="verifiedRef"in t?t.verifiedRef:t;return "verifiedRef"in t&&cr(t,e.chain.chainId),r.chainId!==e.chain.chainId&&y(e,"trigger order ref chain does not match client chain"),we(e,n,r.wallet,"resolved trigger order ref wallet"),r}async function qo(e,t,n){if(t.position!==void 0)return we(e,n,t.position.wallet),pt(e,t.position,{wallet:t.ref.wallet,pairIndex:t.ref.pairIndex,index:t.ref.index,tradeId:t.ref.tradeId}),t.position;we(e,n,t.ref.wallet);let r=await e.api.account.position(t.ref.wallet,{pairIndex:t.ref.pairIndex,index:t.ref.index,tradeId:t.ref.tradeId},n),i=lr(e,r.data);return pt(e,i,{wallet:t.ref.wallet,pairIndex:t.ref.pairIndex,index:t.ref.index,tradeId:t.ref.tradeId}),i}function ur(e,t,n,r){return ft(e,n,r,{basePrice:t.openPrice,direction:t.side,leverage:t.leverage})}function Ho(e,t,n){return ur(e,t,"takeProfit",n)}function zo(e,t,n){return ur(e,t,"stopLoss",n)}function jo(e,t){return {collateral:or(e,t.collateral)}}function tr(e,t,n,r){n!==void 0&&Te(e,t,n,r.basePrice,r.direction);}async function $o(e,t,n){let r=n,i=B(e,"targetPrice",n.targetPrice),a=R(r,"takeProfit"),o=R(r,"stopLoss"),d=!a||!o||a&&er(r.takeProfit)||o&&er(r.stopLoss)?await ut(e,t):void 0,c=d===void 0?void 0:{basePrice:i,direction:d.direction,leverage:d.leverage};return d!==void 0&&c!==void 0&&(a||tr(e,"takeProfit",d.currentTp,c),o||tr(e,"stopLoss",d.currentSl,c)),{targetPrice:i,...a?{takeProfit:ft(e,"takeProfit",r.takeProfit,c)}:{},...o?{stopLoss:ft(e,"stopLoss",r.stopLoss,c)}:{}}}var Go={RequireExisting:"requireExisting",AutoExact:"autoExact",UnsafeMaxUint256:"unsafeMaxUint256"},Ko={Required:"required",Skip:"skip"};export{tn as a,un as b,pn as c,Ia as d,V as e,ho as f,aa as g,yo as h,Ro as i,xo as j,Mo as k,cr as l,No as m,Fo as n,Eo as o,Uo as p,Wo as q,_o as r,qo as s,Ho as t,zo as u,jo as v,$o as w,Go as x,Ko as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var o="0.1.0";export{o as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-D5VE2O4F.js';import {ValidationError}from'@domfi/sdk/errors';var T=/^0x[0-9a-fA-F]{40}$/,M=/^0x(?:[0-9a-fA-F]{2})*$/;function k(n){return typeof n=="string"&&T.test(n)}function D(n,e){return typeof n!="string"||!M.test(n)||e?.allowEmpty===false&&n==="0x"?false:e?.bytes===void 0||n.length===2+e.bytes*2}function N(n,e,t){return k(n)?n:t(`${e} must be a 20-byte hex address`)}function v(n,e,t,i){if(D(n,i))return n;let r=i?.bytes===void 0?"hex string":`${i.bytes}-byte hex string`;return t(`${e} must be a ${r}`)}function O(n,e,t){return v(n,e,t,{bytes:32,allowEmpty:false})}function V(n,e,t){return v(n,e,t,{bytes:32,allowEmpty:false})}var I=1e3,E={sdkVersion:a,sourceTag:"internal-polling",chainId:0};function h(n,e,t,i){return new ValidationError({message:`${n} must be ${e}`,diagnostics:i??E,cause:t})}function S(n,e,t){if(n!==void 0&&!(Number.isFinite(n)&&n>0))throw h(e,"a finite positive number",n,t)}function q(n,e,t){if(n!==void 0&&!(Number.isInteger(n)&&n>=0))throw h(e,"a finite non-negative integer",n,t)}function F(n,e){if(n!==void 0)return S(n,e),Math.max(1,Math.floor(n))}function H(n,e){return new ValidationError({message:"intervalMs must be a finite positive number",diagnostics:e??E,hint:"Omit intervalMs to use the default polling interval, or pass a value greater than 0.",cause:n})}function $(n,e){return C(n,e),n===void 0?I:Math.max(1,Math.floor(n))}function C(n,e){if(n!==void 0&&(!Number.isFinite(n)||n<=0))throw H(n,e)}function c(n){return n?.reason}function x(n){return n instanceof Error&&n.name==="AbortError"?true:typeof n=="object"&&n!==null&&"code"in n&&n.code==="ABORTED"}function j(n,e,t,i){try{return n(e).catch(r=>{throw t?.aborted===!0||x(r)?i(r):r})}catch(r){return t?.aborted===true||x(r)?Promise.reject(i(r)):Promise.reject(r)}}function L(n){return n.catch(()=>{}),n}function z(n={}){let e=n.signal,t=F(n.timeoutMs,"timeoutMs"),i=$(n.intervalMs,n.diagnostics),r={...e!==void 0?{signal:e}:{},...t!==void 0?{timeoutMs:t}:{},intervalMs:i,throwIfAborted(s){if(e?.aborted===true)throw s(c(e))},async waitInterval(s){if(r.throwIfAborted(s),i<=0)return;let o;await new Promise((d,a)=>{let l=setTimeout(d,i);o=()=>{clearTimeout(l),a(s(c(e)));},e?.addEventListener("abort",o,{once:true});}).finally(()=>{o!==void 0&&e?.removeEventListener("abort",o);});},runAttempt(s,o,d){return L((async()=>{r.throwIfAborted(o);let a=t===void 0?void 0:new AbortController,l=a?.signal??e,m,A=new Promise((u,b)=>{m=b;}),g=()=>{let u=c(e);m?.(o(u)),a?.abort(u);},f;try{e?.addEventListener("abort",g,{once:!0});let u=[j(s,l,e,o),A];return t!==void 0&&a!==void 0&&u.push(new Promise((b,P)=>{f=setTimeout(()=>{let p=new Error("attempt timed out");P(d(p)),a.abort(p);},t);})),await Promise.race(u)}finally{f!==void 0&&clearTimeout(f),e?.removeEventListener("abort",g);}})())}};return r}export{k as a,D as b,N as c,v as d,O as e,V as f,S as g,q as h,$ as i,C as j,z as k};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-YU5DN3PI.js';var i={manifestTag:"g5-base-base-sepolia-2026-06-07",abiKeys:["DomfiLockedDepositNft","DomfiTrading","DomfiTradingStorage","DomfiPairsStorage","DomfiPairInfos","DomfiOracle","DomfiVault","IERC20"],chains:{base:{chainId:8453,name:"Base",registryAddress:"0xe438360464EaDa40b7921C993322bD4dA8881103",contracts:{DomfiTrading:"0x7447cb5350a096364A13bEAf77916dfB35db9445",DomfiTradingStorage:"0x608ff95777F419040a3b1E42ed73dD3EFf42Cc24",DomfiPairsStorage:"0x444079DDCaFd4feE3812E2fF79c5F74a1F4f9Be1",DomfiPairInfos:"0x256fD248cDc91A6B098eEE2580f313fdCaFa2059",DomfiOracle:"0x1aB9c3A2E1A09f2D06bf4A75d1721c7e113B8D4D",DomfiVault:"0xA194082Aabb75Dd1Ca9Dc1BA573A5528BeB8c2Fb",DomfiLockedDepositNft:"0x11765119eC66fb434447fd56e9041746c8eCbF85",IERC20:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"},collateral:{symbol:"USDC",decimals:6,tokenAddress:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",tradingStorageSpender:"0x608ff95777F419040a3b1E42ed73dD3EFf42Cc24",vaultSpender:"0xA194082Aabb75Dd1Ca9Dc1BA573A5528BeB8c2Fb"},oracleStaleThresholdMs:6e4,compatibility:{triggerOrderSlippageP:"1"}},"base-sepolia":{chainId:84532,name:"Base Sepolia",registryAddress:"0xa518Cb338f71E9BB2EB9bBb6E02b2B0cC5C29840",contracts:{DomfiTrading:"0x40478F0B348837EFdd07dac83073016da409ea93",DomfiTradingStorage:"0xd62c446636e49C70acf7E47b2907381C829BC412",DomfiPairsStorage:"0x3D5EE28985F8C382cCB112B9054f89d054b6f23E",DomfiPairInfos:"0xAB619663B87ddAD53f4c23A34cfb79AFA06A1EcA",DomfiOracle:"0x47959A2f92335587cf2956dA450b956dA6ca3A84",DomfiVault:"0x0f6171b19f02989485c168536aDE0d9CE5e804fb",DomfiLockedDepositNft:"0x5F78d9A47fdcd0A2c1a23cdB08544f4577c6DFde",IERC20:"0xE0843F149471c2e90E995BaEFA5EF94DC82bF809"},collateral:{symbol:"MockCollateral",decimals:6,tokenAddress:"0xE0843F149471c2e90E995BaEFA5EF94DC82bF809",tradingStorageSpender:"0xd62c446636e49C70acf7E47b2907381C829BC412",vaultSpender:"0x0f6171b19f02989485c168536aDE0d9CE5e804fb"},oracleStaleThresholdMs:6e4,compatibility:{triggerOrderSlippageP:"1"}}}};var e=i;var t={DomfiLockedDepositNft:{address:{8453:"0x11765119eC66fb434447fd56e9041746c8eCbF85",84532:"0x5F78d9A47fdcd0A2c1a23cdB08544f4577c6DFde"},abi:a.DomfiLockedDepositNft},DomfiTrading:{address:{8453:"0x7447cb5350a096364A13bEAf77916dfB35db9445",84532:"0x40478F0B348837EFdd07dac83073016da409ea93"},abi:a.DomfiTrading},DomfiTradingStorage:{address:{8453:"0x608ff95777F419040a3b1E42ed73dD3EFf42Cc24",84532:"0xd62c446636e49C70acf7E47b2907381C829BC412"},abi:a.DomfiTradingStorage},DomfiPairsStorage:{address:{8453:"0x444079DDCaFd4feE3812E2fF79c5F74a1F4f9Be1",84532:"0x3D5EE28985F8C382cCB112B9054f89d054b6f23E"},abi:a.DomfiPairsStorage},DomfiPairInfos:{address:{8453:"0x256fD248cDc91A6B098eEE2580f313fdCaFa2059",84532:"0xAB619663B87ddAD53f4c23A34cfb79AFA06A1EcA"},abi:a.DomfiPairInfos},DomfiOracle:{address:{8453:"0x1aB9c3A2E1A09f2D06bf4A75d1721c7e113B8D4D",84532:"0x47959A2f92335587cf2956dA450b956dA6ca3A84"},abi:a.DomfiOracle},DomfiVault:{address:{8453:"0xA194082Aabb75Dd1Ca9Dc1BA573A5528BeB8c2Fb",84532:"0x0f6171b19f02989485c168536aDE0d9CE5e804fb"},abi:a.DomfiVault},IERC20:{address:{8453:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",84532:"0xE0843F149471c2e90E995BaEFA5EF94DC82bF809"},abi:a.IERC20}};function D(){return {status:"unchecked",manifestTag:e.manifestTag,checks:[{name:"contract-compatibility-check",status:"unchecked"}]}}export{e as a,t as b,D as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var s=100n,i=1000000n,u=1000000000000n,f=1000000000000000000n,m=10000000000000n,R=900n,p="domfi-core@a8bba32d92af1f44ae625e839e4ca420aefe89c2";function c(e,r){if(e<=0n)throw new Error(`${r} must be positive`)}function d(e){return e<0n?-e:e}function b(e,r,n){if(n<=0n)throw new Error("denominator must be positive");let t=e*r,a=t/n,o=t%n;return t>0n&&o!==0n?a+1n:a}function w(e,r){if(typeof e=="bigint")return e;if(!Number.isSafeInteger(e))throw new Error(`${r} must be a safe integer`);return BigInt(e)}function l(e,r){let n=w(e,r);if(n<0n)throw new Error(`${r} must be non-negative`);return n}function h(e){if(e.openPriceRaw<=0n)throw new Error("openPriceRaw must be positive");let r=w(e.leverageRaw,"leverageRaw"),n=w(e.initialLeverageRaw,"initialLeverageRaw");c(r,"leverageRaw"),c(n,"initialLeverageRaw");let t=r>n?r:n,a=R*i*r/t,g=(e.buy?e.markPriceRaw-e.openPriceRaw:e.openPriceRaw-e.markPriceRaw)*i*r/e.openPriceRaw;return g>a?a:g}function E(e){let r=e.collateralRaw,n=r+r*e.percentProfitRaw/i/100n-e.fundingFeeRaw;return n<=e.liquidationMarginRaw?0n:n}function P(e){if(e.collateralRaw<0n)throw new Error("collateralRaw must be non-negative");let r=l(e.leverageRaw,"leverageRaw"),n=l(e.maxLeverageRaw,"maxLeverageRaw"),t=l(e.liqMarginThresholdP,"liqMarginThresholdP");if(n===0n)throw new Error("maxLeverageRaw must be positive");let a=t*r*i/n;return e.collateralRaw*a/(100n*i)}function L(e){let r=l(e.leverageRaw,"leverageRaw");if(e.openPriceRaw<0n)throw new Error("openPriceRaw must be non-negative");if(e.collateralRaw<=0n)throw new Error("collateralRaw must be positive");if(r===0n)throw new Error("leverageRaw must be positive");let n=P(e),t=e.collateralRaw-n-e.fundingFeeRaw;if(t<0n)throw new Error("targetCollateralAfterFees must be non-negative");let a=b(e.openPriceRaw,t*s,e.collateralRaw*r),o=e.buy?e.openPriceRaw-a:e.openPriceRaw+a;return o>0n?o:0n}function q(e){return e.markValueRaw-e.collateralRaw}function M(e){if(e.collateralRaw<=0n)throw new Error("collateralRaw must be positive");let r=e.markValueRaw-e.collateralRaw,n=-100n*i,t=r*i*100n/e.collateralRaw;return t<n?n:t}export{s as a,i as b,u as c,f as d,m as e,R as f,p as g,c as h,d as i,b as j,h as k,E as l,P as m,L as n,q as o,M as p};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {e,d}from'./chunk-BMYMNNJK.js';import {e as e$1,j,g as g$1,h as h$1,i}from'./chunk-LDE3JHVE.js';import {a}from'./chunk-D5VE2O4F.js';import {a as a$1,z,w as w$1,x as x$1,y as y$1}from'./chunk-C5Y2WM7C.js';import {ReadModelNotReadyError,TimeoutError,ValidationError,AbortError}from'@domfi/sdk/errors';var qe={"markets.list":{maxLagBlocks:30n},"markets.get":{maxLagBlocks:30n},"markets.state":{maxLagBlocks:30n},"prices.head":{maxLagBlocks:30n},"prices.candles":{maxLagBlocks:30n},"prices.ticks":{maxLagBlocks:30n},"account.positions":{maxLagBlocks:30n},"account.position":{maxLagBlocks:30n},"account.positionsBatch":{maxLagBlocks:30n},"account.orders":{maxLagBlocks:30n},"account.trades":{maxLagBlocks:30n},"orders.get":{maxLagBlocks:30n},"trades.events":{maxLagBlocks:30n},"status.get":{maxLagBlocks:30n}},ue="read-plane";function Ke(e$1,n={}){let t=e(e$1.indexed_block,"indexed_block"),a=e(e$1.chain_head_block,"chain_head_block"),i=e(e$1.lag_blocks,"lag_blocks"),s=t!==void 0&&a!==void 0&&a>=t?a-t:void 0,o=i??s,r=e(e$1.cache_age_seconds,"cache_age_seconds"),c=e(n.maxLagBlocks,"maxLagBlocks"),u={source:e$1.source,generatedAt:d(e$1.generated_at,"generated_at"),isStale:o!==void 0&&c!==void 0&&o>c};return t!==void 0&&(u.indexedBlock=t),a!==void 0&&(u.chainHeadBlock=a),o!==void 0&&(u.lagBlocks=o),e$1.cache_status!==void 0&&e$1.cache_status!==null&&(u.cacheStatus=e$1.cache_status),r!==void 0&&(u.cacheAgeSeconds=r),u}function q(e){let n=e.policy??"strict";if(n==="ignore")return;let t=e.unsafeReasons??[],a=e.degradedReasons??[],i=t.length>0?t:a;if(i.length===0)return;let s=ce(e);if(n==="warn"){e.onEvent?.({type:"warning",code:"READ_MODEL_NOT_READY",message:"Read model is degraded for this route",diagnostics:s,degradedReasons:i});return}if(t.length!==0)throw new ReadModelNotReadyError({message:"Read model is not ready for this route",diagnostics:s})}function ce(e){return {sdkVersion:a,sourceTag:ue,...e.diagnostics,chainId:e.chainId}}function P(e){let n={hasNext:e.has_next,limit:e.limit};return e.cursor!==void 0&&e.cursor!==null&&(n.cursor=e.cursor),e.next_cursor!==void 0&&e.next_cursor!==null&&(n.nextCursor=e.next_cursor),n}async function*de(e,n){let t=await e(n);for(;;){yield t;let a=t.pagination.nextCursor;if(!t.pagination.hasNext||a===void 0)return;t=await e({...n,cursor:a});}}async function*Ge(e,n){for await(let t of de(e,n))for(let a of t.data){if(t.diagnostics!==void 0){yield {item:a,freshness:t.freshness,pagination:t.pagination,diagnostics:t.diagnostics};continue}yield {item:a,freshness:t.freshness,pagination:t.pagination};}}function K(e){if(e!==void 0)return n=>{try{let t=e(n);le(t)&&Promise.resolve(t).catch(()=>{});}catch{}}}function le(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&"then"in e&&typeof e.then=="function"}var fe=new Set(["Deposit","DepositLocked","DepositUnlocked","WithdrawRequested","Withdraw","WithdrawCanceled","LockedDepositTransferIn","LockedDepositTransferOut"]),ge=6,me=6,pe=18,he=30n,G="vault-read";function g(e,n){throw new ValidationError({message:e,diagnostics:{sdkVersion:a,sourceTag:G,chainId:0},...n!==void 0?{cause:n}:{}})}function l(e,n){try{return n()}catch(t){if(t instanceof ValidationError&&t.diagnostics.sourceTag===G)throw t;return g(e,t)}}function _e(e){return {accPnlPerToken:xe(e.acc_pnl_per_token,"acc_pnl_per_token"),currentEpoch:e.current_epoch,currentValueLocked:I(e.current_value_locked,"current_value_locked"),epochStart:e.epoch_start,totalShares:D(e.total_shares,"total_shares"),apr:w(e.apr,"apr"),sharePrice:ve(e.share_price,"share_price"),collateralizationRatio:w(e.collateralization_ratio,"collateralization_ratio"),overCollateralization:w(e.over_collateralization,"over_collateralization")}}function f(e){let n={time:R(e,"time"),blockNumber:R(e,"block_number"),txIndex:R(e,"tx_index"),logIndex:R(e,"log_index"),opType:"unknown"},t=Te(e.tx_hash,"tx_hash");t!==void 0&&(n.txHash=t);let a=Re(T(e,"op_type"));n.opType=a.opType,a.rawOpType!==void 0&&(n.rawOpType=a.rawOpType);let i=T(e,"id");i!==void 0&&(n.id=i);let s=T(e,"assets");s!==void 0&&(n.assets=I(s,"assets"));let o=T(e,"shares");o!==void 0&&(n.shares=D(o,"shares"));let r=O(e,"current_epoch");r!==void 0&&(n.currentEpoch=r);let c=O(e,"unlock_epoch");c!==void 0&&(n.unlockEpoch=c);let u=O(e,"lock_duration_seconds");return u!==void 0&&(n.lockDurationSeconds=u),n}function ye(e){return {totalAssets:I(e.total_assets,"total_assets"),totalShares:D(e.total_shares,"total_shares"),totalLockedShares:D(e.total_locked_shares,"total_locked_shares"),lockedDeposits:e.locked_deposits.map(f),unlockedDeposits:e.unlocked_deposits.map(f),pendingWithdraws:e.pending_withdraws.map(f),history:e.history.map(f),historyPagination:P(e.history_pagination)}}function ke(e){return {history:e.history.map(f),pagination:P(e.pagination)}}function be(e){let n=Q(e.tx_hash,"tx_hash");return {txHash:n,events:e.events.map(t=>f({...t,tx_hash:t.tx_hash??n}))}}function A(e,n){let t=e.indexOf(".");if(t===-1)return e;let a=e.slice(t+1);return a.length<=n?e:`${e.slice(0,t)}.${a.slice(0,n)}`}function k(e,n){return typeof e!="string"&&g(`${n} must be a string`),e}function w(e,n){return l(`${n} must be a decimal string`,()=>a$1(k(e,n)))}function xe(e,n){return l(`${n} must be a ratio string`,()=>z.fromRaw(k(e,n)))}function I(e,n){return l(`${n} must be a vault asset decimal`,()=>w$1.fromDecimal(A(k(e,n),ge)))}function D(e,n){return l(`${n} must be a vault share decimal`,()=>x$1.fromDecimal(A(k(e,n),me)))}function ve(e,n){return l(`${n} must be a vault share price decimal`,()=>y$1.fromDecimal(A(k(e,n),pe)))}function rn(e){function n(t,a,i){J(e,t,a,i);}return {stats:async t=>{let a=await e.raw.vault.stats(t),i=y(a.freshness);return n(a,i,t),V(a,{data:_e(a.data),freshness:i})},account:async(t,a)=>{let i=await e.raw.vault.account(t,a),s=y(i.freshness);return n(i,s,a),V(i,{data:ye(i.data),freshness:s})},accountHistory:async(t,a)=>{let i=await e.raw.vault.accountHistory(t,a),s=y(i.freshness);return n(i,s,a),V(i,{data:ke(i.data),freshness:s})},transactionEvents:async(t,a)=>{let i=await e.raw.vault.transactionEvents(t,a),s=y(i.freshness);return n(i,s,a),V(i,{data:be(i.data),freshness:s})},accountHistoryIterator:(t,a)=>Ve(e,t,a)}}async function*Ve(e,n,t={}){let a=t;for(;;){let i=await e.raw.vault.accountHistory(n,a);J(e,i,y(i.freshness),a);for(let o of i.data.history)yield f(o);let s=i.data.pagination.next_cursor;if(s==null)return;a={...t,cursor:s};}}function J(e,n,t,a){let i=K(e.onEvent),s=n.readiness;if(s===void 0||s.status==="ready")return;let o=s.unsafe_reasons??[],r=s.degraded_reasons??[],c=s.status==="unsafe"?o.length>0?o:r.length>0?r:[s.status]:o,u=r.length>0?r:s.status==="degraded"?[s.status]:[];q({policy:a?.readinessPolicy??"strict",chainId:e.chainId??0,degradedReasons:u,unsafeReasons:c,diagnostics:{apiFreshness:t},...i!==void 0?{onEvent:i}:{}});}function Re(e){return e===void 0?{opType:"unknown"}:fe.has(e)?{opType:e}:{opType:"unknown",rawOpType:e}}function Q(e,n){return typeof e!="string"&&g(`vault event ${n} is required for domain mapping`),e$1(e,n,g)}function Te(e,n){if(e!=null)return Q(e,n)}function V(e,n){let t=e.diagnostics;return t===void 0?n:{...n,diagnostics:t}}function y(e$1){let n=l("indexed_block must be an integer",()=>e(e$1.indexed_block,"indexed_block")),t=l("chain_head_block must be an integer",()=>e(e$1.chain_head_block,"chain_head_block")),a=l("lag_blocks must be an integer",()=>e(e$1.lag_blocks,"lag_blocks")),i=l("cache_age_seconds must be an integer",()=>e(e$1.cache_age_seconds,"cache_age_seconds")),s={source:e$1.source,generatedAt:l("generated_at must be an ISO timestamp",()=>d(e$1.generated_at,"generated_at")),isStale:a!==void 0&&a>he};return n!==void 0&&(s.indexedBlock=n),t!==void 0&&(s.chainHeadBlock=t),a!==void 0&&(s.lagBlocks=a),e$1.cache_status!==void 0&&e$1.cache_status!==null&&(s.cacheStatus=e$1.cache_status),i!==void 0&&(s.cacheAgeSeconds=i),s}function R(e,n){let t=e[n];return (typeof t!="number"||!Number.isInteger(t))&&g(`${n} must be an integer`),t}function O(e,n){let t=e[n];if(t!=null)return (typeof t!="number"||!Number.isInteger(t))&&g(`${n} must be an integer`),t}function T(e,n){let t=e[n];if(t!=null)return typeof t!="string"&&g(`${n} must be a string`),t}var De="vault-track",Ee=25;function H(e){let n={sdkVersion:a,sourceTag:De,chainId:e.chain.chainId};return e.chain.registryAddress!==void 0&&(n.registryAddress=e.chain.registryAddress),n}function L(e,n,t){return {message:n,diagnostics:H(e),...t!==void 0?{cause:t}:{}}}function ee(e,n){throw new AbortError(L(e,"vault tracking was aborted",n))}function h(e){throw new TimeoutError(L(e,"vault tracking timed out"))}function ne(e){return e instanceof AbortError||e instanceof Error&&e.name==="AbortError"?true:typeof e=="object"&&e!==null&&"code"in e&&e.code==="ABORTED"}function Pe(e){if(e instanceof TimeoutError||ne(e)||typeof e!="object"||e===null)return false;let n=e.status??e.httpStatus;if(n===404||n===405||n===501)return true;let t=e.code;if(typeof t!="string")return false;let a=t.toUpperCase();return a.includes("NOT_FOUND")||a.includes("UNSUPPORTED")||a.includes("NOT_IMPLEMENTED")||a.includes("METHOD_NOT_ALLOWED")}function b(e,n){n?.aborted===true&&ee(e,n.reason);}function te(e){return [e?.timeoutMs,e?.maxDurationMs].filter(n=>typeof n=="number"&&Number.isFinite(n)&&n>0)}function we(e){let n=te(e);if(n.length!==0)return Date.now()+Math.min(...n)}function x(e){if(e!==void 0)return e-Date.now()}function Oe(e){return e?.maxAttempts!==void 0?Math.max(0,e.maxAttempts):te(e).length>0?Number.POSITIVE_INFINITY:1}function ae(e,n){let t=H(e);j(n?.intervalMs,t),g$1(n?.timeoutMs,"timeoutMs",t),g$1(n?.maxDurationMs,"maxDurationMs",t),h$1(n?.maxAttempts,"maxAttempts",t);}function Ae(e,n){return i(n?.intervalMs,H(e))}function se(e,n){let t=[];e?.timeoutMs!==void 0&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0&&t.push(e.timeoutMs);let a=x(n);if(a!==void 0&&a>0&&t.push(a),t.length!==0)return Math.max(1,Math.floor(Math.min(...t)))}function Ie(e,n,t){let a={limit:e?.limit??Ee};return e?.signal!==void 0&&(a.signal=e.signal),t!==void 0&&(a.timeoutMs=t),e?.readinessPolicy!==void 0&&(a.readinessPolicy=e.readinessPolicy),n!==void 0&&(a.cursor=n),a}function Se(e,n){let t={};return e?.signal!==void 0&&(t.signal=e.signal),n!==void 0&&(t.timeoutMs=n),e?.readinessPolicy!==void 0&&(t.readinessPolicy=e.readinessPolicy),t}async function Fe(e,n,t){if(b(e,t),n<=0)return;let a;await new Promise((i,s)=>{let o=setTimeout(i,n);a=()=>{clearTimeout(o),s(new AbortError(L(e,"vault tracking was aborted",t?.reason)));},t?.addEventListener("abort",a,{once:true});}).finally(()=>{a!==void 0&&t?.removeEventListener("abort",a);});}function He(e){switch(e){case "deposit":case "mint":return "Deposit";case "depositWithDiscountAndLock":case "mintWithDiscountAndLock":return "DepositLocked";case "makeWithdrawRequest":return "WithdrawRequested";case "cancelWithdrawRequest":return "WithdrawCanceled";case "withdraw":case "redeem":return "Withdraw";case "unlockDeposit":return "DepositUnlocked"}}function Le(e,n){let t=n;return t.blockNumber===void 0||t.txIndex===void 0||t.logIndex===void 0?true:BigInt(e.blockNumber)===t.blockNumber&&e.txIndex===t.txIndex&&e.logIndex===t.logIndex}function Be(e,n){return e!==void 0&&e.toLowerCase()===n.toLowerCase()}function ie(e,n){return Be(e.txHash,n.txHash)&&e.opType===He(n.verb)&&Le(e,n)}async function Ne(e,n,t,a,i){try{let s=Ie(t,a,se(t,i));if(e.vault.accountHistory!==void 0)return await e.vault.accountHistory(n.owner,s);let o=await e.vault.account(n.owner,s);return {...o,data:{history:o.data.history,pagination:o.data.historyPagination}}}catch(s){throw s instanceof TimeoutError||(ne(s)||t?.signal?.aborted===true)&&ee(e,s),s}}function Ce(e){return `${String(e.freshness?.generatedAt)}:${String(e.freshness?.indexedBlock)}`}function Me(e,n){return e.some(t=>BigInt(t.blockNumber)<n.blockNumber)}function X(e,n,t){n===void 0||t===void 0||(e.exhaustedFirstPage={freshnessKey:n,nextCursor:t});}async function Z(e,n,t,a,i){let s,o,r;for(;;){b(e,t?.signal);let c=x(a);c!==void 0&&c<=0&&h(e);let u=await Ne(e,n,t,s,a),m=u.data.history.find(oe=>ie(oe,n));if(m!==void 0)return m;let _=u.data.pagination.nextCursor;if(s===void 0&&(o=Ce(u),r=_,_!==void 0&&i.exhaustedFirstPage?.nextCursor===_&&i.exhaustedFirstPage.freshnessKey===o))return;if(Me(u.data.history,n)){X(i,o,r);return}if(_===void 0){X(i,o,r);return}s=_;}}async function We(e,n,t,a,i){if(e.vault.transactionEvents!==void 0&&!i.transactionEventsUnavailable){b(e,t?.signal);let s=x(a);s!==void 0&&s<=0&&h(e);let o;try{o=await e.vault.transactionEvents(n.txHash,Se(t,se(t,a)));}catch(r){if(!Pe(r))throw r;return i.transactionEventsUnavailable=true,Z(e,n,t,a,i.accountHistory)}return o.data.events.find(r=>ie(r,n))}return Z(e,n,t,a,i.accountHistory)}async function je(e,n,t){ae(e,t);let a=we(t),i=Oe(t),s=Ae(e,t),o={transactionEventsUnavailable:false,accountHistory:{}},r=0;for(b(e,t?.signal),i<=0&&h(e);;){b(e,t?.signal);let c=x(a);c!==void 0&&c<=0&&h(e),r+=1;let u=await We(e,n,t,a,o);if(u!==void 0)return {outcome:n,event:u};r>=i&&h(e);let m=x(a);m!==void 0&&m<=0&&h(e),await Fe(e,Math.min(s,m??s),t?.signal);}}async function fn(e,n,t){ae(e,t);let a=await n.waitReceipt(t),i=await n.outcome(t),s=await je(e,i,t);return {receipt:a,outcome:i,indexed:s}}export{K as a,qe as b,Ke as c,q as d,P as e,de as f,Ge as g,_e as h,f as i,ye as j,ke as k,be as l,rn as m,Pe as n,ae as o,He as p,ie as q,je as r,fn as s};
|