@defdone/annon 0.1.0-alpha.0 → 0.1.0-alpha.2

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.
Files changed (59) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/CLI.md +116 -10
  3. package/README.md +57 -15
  4. package/dist/api/annon-types.d.ts +2 -1
  5. package/dist/api/annon.js +9 -2
  6. package/dist/browser/index.d.ts +1 -1
  7. package/dist/browser/login-bundle.js +113 -77
  8. package/dist/browser/login-dom.d.ts +13 -0
  9. package/dist/browser/login-dom.js +67 -0
  10. package/dist/browser/login-dropdown.d.ts +32 -0
  11. package/dist/browser/login-dropdown.js +129 -0
  12. package/dist/browser/login-format.d.ts +16 -0
  13. package/dist/browser/login-format.js +52 -0
  14. package/dist/browser/login-status.d.ts +70 -0
  15. package/dist/browser/login-status.js +85 -0
  16. package/dist/browser/login-terms.d.ts +10 -0
  17. package/dist/browser/login-terms.js +69 -0
  18. package/dist/browser/login-view.d.ts +34 -0
  19. package/dist/browser/login-view.js +227 -0
  20. package/dist/browser/login-wallet.d.ts +28 -0
  21. package/dist/browser/login-wallet.js +179 -0
  22. package/dist/browser/login.js +115 -101
  23. package/dist/browser/purchase-bundle.js +45 -45
  24. package/dist/browser/purchases.d.ts +4 -0
  25. package/dist/browser/purchases.js +14 -0
  26. package/dist/browser/reconcile.d.ts +41 -0
  27. package/dist/browser/reconcile.js +77 -0
  28. package/dist/node/adapter.js +5 -3
  29. package/dist/node/approval-status.d.ts +34 -0
  30. package/dist/node/approval-status.js +71 -0
  31. package/dist/node/backup-secret-init.d.ts +9 -0
  32. package/dist/node/backup-secret-init.js +103 -0
  33. package/dist/node/backup-secret.d.ts +35 -0
  34. package/dist/node/backup-secret.js +104 -0
  35. package/dist/node/browser-login.d.ts +9 -0
  36. package/dist/node/browser-login.js +75 -14
  37. package/dist/node/buy-commands.js +9 -2
  38. package/dist/node/cli.js +23 -7
  39. package/dist/node/command-context.js +1 -1
  40. package/dist/node/config.d.ts +2 -0
  41. package/dist/node/config.js +3 -1
  42. package/dist/node/login-page.d.ts +7 -0
  43. package/dist/node/login-page.js +71 -0
  44. package/dist/node/purchase-commands.d.ts +2 -2
  45. package/dist/node/purchase-commands.js +10 -6
  46. package/dist/node/saved-state.d.ts +4 -0
  47. package/dist/node/saved-state.js +50 -0
  48. package/dist/node/signer-wallet.js +3 -1
  49. package/dist/node/version.d.ts +1 -0
  50. package/dist/node/version.js +3 -0
  51. package/dist/node/wallets.d.ts +1 -1
  52. package/dist/node/wallets.js +2 -10
  53. package/dist/pay/base.js +36 -43
  54. package/dist/pay/purchase.d.ts +2 -1
  55. package/dist/wallet/account-only.d.ts +1 -1
  56. package/dist/wallet/account-only.js +1 -1
  57. package/dist/wallet/uncertain.d.ts +6 -3
  58. package/dist/wallet/uncertain.js +4 -1
  59. package/package.json +3 -2
@@ -1,60 +1,60 @@
1
- var K5=Object.defineProperty;var C=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var Iy=(e,t)=>{for(var r in t)K5(e,r,{get:t[r],enumerable:!0})};var Cw,Uw=C(()=>{Cw="1.2.3"});var nt,ls=C(()=>{Uw();nt=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,i=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...o?[`Docs: https://abitype.dev${o}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${Cw}`].join(`
2
- `);super(i),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=o,this.metaMessages=r.metaMessages,this.shortMessage=t}}});function Kt(e,t){return e.exec(t)?.groups}var am,cm,Of,wc=C(()=>{am=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,cm=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,Of=/^\(.+?\).*?$/});function Cf(e){let t=e.type;if(Nw.test(e.type)&&"components"in e){t="(";let r=e.components.length;for(let o=0;o<r;o++){let i=e.components[o];t+=Cf(i),o<r-1&&(t+=", ")}let n=Kt(Nw,e.type);return t+=`)${n?.array||""}`,Cf({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}var Nw,Fw=C(()=>{wc();Nw=/^tuple(?<array>(\[(\d*)\])*)$/});function ps(e){let t="",r=e.length;for(let n=0;n<r;n++){let o=e[n];t+=Cf(o),n!==r-1&&(t+=", ")}return t}var Mw=C(()=>{Fw()});function dm(e){return e.type==="function"?`function ${e.name}(${ps(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${ps(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${ps(e.inputs)})`:e.type==="error"?`error ${e.name}(${ps(e.inputs)})`:e.type==="constructor"?`constructor(${ps(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}var zw=C(()=>{Mw()});function $w(e){return Hw.test(e)}function Lw(e){return Kt(Hw,e)}function qw(e){return Dw.test(e)}function jw(e){return Kt(Dw,e)}function Vw(e){return Gw.test(e)}function Kw(e){return Kt(Gw,e)}function Uf(e){return Ww.test(e)}function Zw(e){return Kt(Ww,e)}function Xw(e){return Yw.test(e)}function Jw(e){return Kt(Yw,e)}function e1(e){return Qw.test(e)}function t1(e){return Kt(Qw,e)}function r1(e){return ZS.test(e)}var Hw,Dw,Gw,Ww,Yw,Qw,ZS,n1,Nf,Ff=C(()=>{wc();Hw=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;Dw=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;Gw=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;Ww=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;Yw=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;Qw=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;ZS=/^receive\(\) external payable$/;n1=new Set(["indexed"]),Nf=new Set(["calldata","memory","storage"])});var Mf,zf,fm=C(()=>{ls();Mf=class extends nt{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}},zf=class extends nt{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}});var Hf,$f,Lf,Df,qf,um=C(()=>{ls();Hf=class extends nt{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}},$f=class extends nt{constructor({param:t,name:r}){super("Invalid ABI parameter.",{details:t,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}},Lf=class extends nt{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}},Df=class extends nt{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}},qf=class extends nt{constructor({abiParameter:t}){super("Invalid ABI parameter.",{details:JSON.stringify(t,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}});var Gr,jf,Gf,lm=C(()=>{ls();Gr=class extends nt{constructor({signature:t,type:r}){super(`Invalid ${r} signature.`,{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}},jf=class extends nt{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}},Gf=class extends nt{constructor({signature:t}){super("Invalid struct signature.",{details:t,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}});var Vf,o1=C(()=>{ls();Vf=class extends nt{constructor({type:t}){super("Circular reference detected.",{metaMessages:[`Struct "${t}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}});var Kf,i1=C(()=>{ls();Kf=class extends nt{constructor({current:t,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${t.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}}});function s1(e,t,r){let n="";if(r)for(let o of Object.entries(r)){if(!o)continue;let i="";for(let s of o[1])i+=`[${s.type}${s.name?`:${s.name}`:""}]`;n+=`(${o[0]}{${i}})`}return t?`${t}:${e}${n}`:`${e}${n}`}var Wf,a1=C(()=>{Wf=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]])});function c1(e,t={}){if(Vw(e))return YS(e,t);if(qw(e))return XS(e,t);if($w(e))return JS(e,t);if(Xw(e))return QS(e,t);if(e1(e))return eE(e);if(r1(e))return{type:"receive",stateMutability:"payable"};throw new jf({signature:e})}function YS(e,t={}){let r=Kw(e);if(!r)throw new Gr({signature:e,type:"function"});let n=wr(r.parameters),o=[],i=n.length;for(let a=0;a<i;a++)o.push(ho(n[a],{modifiers:Nf,structs:t,type:"function"}));let s=[];if(r.returns){let a=wr(r.returns),c=a.length;for(let d=0;d<c;d++)s.push(ho(a[d],{modifiers:Nf,structs:t,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:o,outputs:s}}function XS(e,t={}){let r=jw(e);if(!r)throw new Gr({signature:e,type:"event"});let n=wr(r.parameters),o=[],i=n.length;for(let s=0;s<i;s++)o.push(ho(n[s],{modifiers:n1,structs:t,type:"event"}));return{name:r.name,type:"event",inputs:o}}function JS(e,t={}){let r=Lw(e);if(!r)throw new Gr({signature:e,type:"error"});let n=wr(r.parameters),o=[],i=n.length;for(let s=0;s<i;s++)o.push(ho(n[s],{structs:t,type:"error"}));return{name:r.name,type:"error",inputs:o}}function QS(e,t={}){let r=Jw(e);if(!r)throw new Gr({signature:e,type:"constructor"});let n=wr(r.parameters),o=[],i=n.length;for(let s=0;s<i;s++)o.push(ho(n[s],{structs:t,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:o}}function eE(e){let t=t1(e);if(!t)throw new Gr({signature:e,type:"fallback"});return{type:"fallback",stateMutability:t.stateMutability??"nonpayable"}}function ho(e,t){let r=s1(e,t?.type,t?.structs);if(Wf.has(r))return Wf.get(r);let n=Of.test(e),o=Kt(n?rE:tE,e);if(!o)throw new Hf({param:e});if(o.name&&iE(o.name))throw new $f({param:e,name:o.name});let i=o.name?{name:o.name}:{},s=o.modifier==="indexed"?{indexed:!0}:{},a=t?.structs??{},c,d={};if(n){c="tuple";let u=wr(o.type),l=[],p=u.length;for(let m=0;m<p;m++)l.push(ho(u[m],{structs:a}));d={components:l}}else if(o.type in a)c="tuple",d={components:a[o.type]};else if(nE.test(o.type))c=`${o.type}256`;else if(o.type==="address payable")c="address";else if(c=o.type,t?.type!=="struct"&&!pm(c))throw new zf({type:c});if(o.modifier){if(!t?.modifiers?.has?.(o.modifier))throw new Lf({param:e,type:t?.type,modifier:o.modifier});if(Nf.has(o.modifier)&&!sE(c,!!o.array))throw new Df({param:e,type:t?.type,modifier:o.modifier})}let f={type:`${c}${o.array??""}`,...i,...s,...d};return Wf.set(r,f),f}function wr(e,t=[],r="",n=0){let o=e.trim().length;for(let i=0;i<o;i++){let s=e[i],a=e.slice(i+1);switch(s){case",":return n===0?wr(a,[...t,r.trim()]):wr(a,t,`${r}${s}`,n);case"(":return wr(a,t,`${r}${s}`,n+1);case")":return wr(a,t,`${r}${s}`,n-1);default:return wr(a,t,`${r}${s}`,n)}}if(r==="")return t;if(n!==0)throw new Kf({current:r,depth:n});return t.push(r.trim()),t}function pm(e){return e==="address"||e==="bool"||e==="function"||e==="string"||am.test(e)||cm.test(e)}function iE(e){return e==="address"||e==="bool"||e==="function"||e==="string"||e==="tuple"||am.test(e)||cm.test(e)||oE.test(e)}function sE(e,t){return t||e==="bytes"||e==="string"||e==="tuple"}var tE,rE,nE,oE,mm=C(()=>{wc();fm();um();lm();i1();a1();Ff();tE=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,rE=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,nE=/^u?int$/;oE=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/});function d1(e){let t={},r=e.length;for(let s=0;s<r;s++){let a=e[s];if(!Uf(a))continue;let c=Zw(a);if(!c)throw new Gr({signature:a,type:"struct"});let d=c.properties.split(";"),f=[],u=d.length;for(let l=0;l<u;l++){let m=d[l].trim();if(!m)continue;let h=ho(m,{type:"struct"});f.push(h)}if(!f.length)throw new Gf({signature:a});t[c.name]=f}let n={},o=Object.entries(t),i=o.length;for(let s=0;s<i;s++){let[a,c]=o[s];n[a]=f1(c,t)}return n}function f1(e=[],t={},r=new Set){let n=[],o=e.length;for(let i=0;i<o;i++){let s=e[i];if(Of.test(s.type))n.push(s);else{let c=Kt(aE,s.type);if(!c?.type)throw new qf({abiParameter:s});let{array:d,type:f}=c;if(f in t){if(r.has(f))throw new Vf({type:f});n.push({...s,type:`tuple${d??""}`,components:f1(t[f],t,new Set([...r,f]))})}else if(pm(f))n.push(s);else throw new Mf({type:f})}}return n}var aE,u1=C(()=>{wc();fm();um();lm();o1();Ff();mm();aE=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/});function Zf(e){let t=d1(e),r=[],n=e.length;for(let o=0;o<n;o++){let i=e[o];Uf(i)||r.push(c1(i,t))}return r}var l1=C(()=>{Ff();u1();mm()});var hm=C(()=>{zw();l1()});function ce(e){return typeof e=="string"?{address:e,type:"json-rpc"}:e}var Ye=C(()=>{});var ym,p1=C(()=>{ym="2.57.10"});function m1(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?m1(e.cause,t):t?null:e}var bm,L,le=C(()=>{p1();bm={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${ym}`},L=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,i=bm.getDocsUrl?.({...r,docsPath:o}),s=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...n?[`Details: ${n}`]:[],...bm.version?[`Version: ${bm.version}`]:[]].join(`
3
- `);super(s,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=o,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=t,this.version=ym}walk(t){return m1(this,t)}}});var Ce,Vr=C(()=>{le();Ce=class extends L{constructor({address:t}){super(`Address "${t}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}});function ct(e,{strict:t=!0}={}){return!e||typeof e!="string"?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}var vn=C(()=>{});var xc,vc,Sc,Yf=C(()=>{le();xc=class extends L{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${t}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},vc=class extends L{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${t}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}},Sc=class extends L{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${r} ${n} long, but is ${t} ${n} long.`,{name:"InvalidBytesLengthError"})}}});function yo(e,{dir:t,size:r=32}={}){return typeof e=="string"?Sn(e,{dir:t,size:r}):cE(e,{dir:t,size:r})}function Sn(e,{dir:t,size:r=32}={}){if(r===null)return e;let n=e.replace("0x","");if(n.length>r*2)throw new vc({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function cE(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new vc({size:e.length,targetSize:r,type:"bytes"});let n=new Uint8Array(r);for(let o=0;o<r;o++){let i=t==="right";n[i?o:r-o-1]=e[i?o:e.length-o-1]}return n}var Xf=C(()=>{Yf()});var bo,Jf,Qf,Ec=C(()=>{le();bo=class extends L{constructor({max:t,min:r,signed:n,size:o,value:i}){super(`Number "${i}" is not in safe ${o?`${o*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${t?`(${r} to ${t})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}},Jf=class extends L{constructor(t){super(`Bytes value "${t}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}},Qf=class extends L{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}}});function ge(e){return ct(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}var xr=C(()=>{vn()});function Kr(e,{dir:t="left"}={}){let r=typeof e=="string"?e.replace("0x",""):e,n=0;for(let o=0;o<r.length-1&&r[t==="left"?o:r.length-o-1].toString()==="0";o++)n++;return r=t==="left"?r.slice(n):r.slice(0,r.length-n),typeof e=="string"?(r.length===1&&t==="right"&&(r=`${r}0`),`0x${r.length%2===1?`0${r}`:r}`):r}var eu=C(()=>{});function Wt(e,{size:t}){if(ge(e)>t)throw new Qf({givenSize:ge(e),maxSize:t})}function De(e,t={}){let{signed:r}=t;t.size&&Wt(e,{size:t.size});let n=BigInt(e);if(!r)return n;let o=Math.ceil((e.length-2)/2),i=(1n<<BigInt(o)*8n-1n)-1n;return n<=i?n:n-BigInt(`0x${"f".padStart(o*2,"f")}`)-1n}function Xe(e,t={}){let r=De(e,t),n=Number(r);if(!Number.isSafeInteger(n))throw new bo({max:`${Number.MAX_SAFE_INTEGER}`,min:`${Number.MIN_SAFE_INTEGER}`,signed:t.signed,size:t.size,value:`${r}n`});return n}var Pt=C(()=>{Ec();xr()});function ht(e,t={}){return typeof e=="number"||typeof e=="bigint"?V(e,t):typeof e=="string"?_c(e,t):typeof e=="boolean"?gm(e,t):Me(e,t)}function gm(e,t={}){let r=`0x${Number(e)}`;return typeof t.size=="number"?(Wt(r,{size:t.size}),yo(r,{size:t.size})):r}function Me(e,t={}){let r="";for(let o=0;o<e.length;o++)r+=dE[e[o]];let n=`0x${r}`;return typeof t.size=="number"?(Wt(n,{size:t.size}),yo(n,{dir:"right",size:t.size})):n}function V(e,t={}){let{signed:r,size:n}=t,o=BigInt(e),i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));let s=typeof i=="bigint"&&r?-i-1n:0;if(i&&o>i||o<s){let c=typeof e=="bigint"?"n":"";throw new bo({max:i?`${i}${c}`:void 0,min:`${s}${c}`,signed:r,size:n,value:`${e}${c}`})}let a=`0x${(r&&o<0?(1n<<BigInt(n*8))+BigInt(o):o).toString(16)}`;return n?yo(a,{size:n}):a}function _c(e,t={}){let r=fE.encode(e);return Me(r,t)}var dE,fE,xe=C(()=>{Ec();Xf();Pt();dE=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));fE=new TextEncoder});function go(e,t={}){return typeof e=="number"||typeof e=="bigint"?pE(e,t):typeof e=="boolean"?lE(e,t):ct(e)?Rt(e,t):Ac(e,t)}function lE(e,t={}){let r=new Uint8Array(1);return r[0]=Number(e),typeof t.size=="number"?(Wt(r,{size:t.size}),yo(r,{size:t.size})):r}function h1(e){if(e>=En.zero&&e<=En.nine)return e-En.zero;if(e>=En.A&&e<=En.F)return e-(En.A-10);if(e>=En.a&&e<=En.f)return e-(En.a-10)}function Rt(e,t={}){let r=e;t.size&&(Wt(r,{size:t.size}),r=yo(r,{dir:"right",size:t.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);let o=n.length/2,i=new Uint8Array(o);for(let s=0,a=0;s<o;s++){let c=h1(n.charCodeAt(a++)),d=h1(n.charCodeAt(a++));if(c===void 0||d===void 0)throw new L(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);i[s]=c*16+d}return i}function pE(e,t){let r=V(e,t);return Rt(r)}function Ac(e,t={}){let r=uE.encode(e);return typeof t.size=="number"?(Wt(r,{size:t.size}),yo(r,{dir:"right",size:t.size})):r}var uE,En,rr=C(()=>{le();vn();Xf();Pt();xe();uE=new TextEncoder;En={zero:48,nine:57,A:65,F:70,a:97,f:102}});function mE(e,t=!1){return t?{h:Number(e&tu),l:Number(e>>y1&tu)}:{h:Number(e>>y1&tu)|0,l:Number(e&tu)|0}}function b1(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=mE(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var tu,y1,g1,w1,x1,v1,S1=C(()=>{tu=BigInt(4294967295),y1=BigInt(32);g1=(e,t,r)=>e<<r|t>>>32-r,w1=(e,t,r)=>t<<r|e>>>32-r,x1=(e,t,r)=>t<<r-32|e>>>64-r,v1=(e,t,r)=>e<<r-32|t>>>64-r});var yi,E1=C(()=>{yi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});function hE(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function bi(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Wr(e,...t){if(!hE(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function _1(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");bi(e.outputLen),bi(e.blockLen)}function _n(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function ru(e,t){Wr(e);let r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function A1(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Zr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function nu(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function vr(e,t){return e<<32-t|e>>>t}function bE(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function gE(e){for(let t=0;t<e.length;t++)e[t]=bE(e[t]);return e}function wE(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function gi(e){return typeof e=="string"&&(e=wE(e)),Wr(e),e}function T1(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];Wr(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let i=e[n];r.set(i,o),o+=i.length}return r}function ou(e){let t=n=>e().update(gi(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function iu(e=32){if(yi&&typeof yi.getRandomValues=="function")return yi.getRandomValues(new Uint8Array(e));if(yi&&typeof yi.randomBytes=="function")return Uint8Array.from(yi.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}var yE,wm,wo,xo=C(()=>{E1();yE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;wm=yE?e=>e:gE;wo=class{}});function IE(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let s=0;s<10;s++)r[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){let a=(s+8)%10,c=(s+2)%10,d=r[c],f=r[c+1],u=I1(d,f,1)^r[a],l=k1(d,f,1)^r[a+1];for(let p=0;p<50;p+=10)e[s+p]^=u,e[s+p+1]^=l}let o=e[2],i=e[3];for(let s=0;s<24;s++){let a=P1[s],c=I1(o,i,a),d=k1(o,i,a),f=B1[s];o=e[f],i=e[f+1],e[f]=c,e[f+1]=d}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)r[a]=e[s+a];for(let a=0;a<10;a++)e[s+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=AE[n],e[1]^=TE[n]}Zr(r)}var xE,Tc,vE,SE,EE,_E,B1,P1,R1,O1,AE,TE,I1,k1,xm,kE,C1,U1=C(()=>{S1();xo();xE=BigInt(0),Tc=BigInt(1),vE=BigInt(2),SE=BigInt(7),EE=BigInt(256),_E=BigInt(113),B1=[],P1=[],R1=[];for(let e=0,t=Tc,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],B1.push(2*(5*n+r)),P1.push((e+1)*(e+2)/2%64);let o=xE;for(let i=0;i<7;i++)t=(t<<Tc^(t>>SE)*_E)%EE,t&vE&&(o^=Tc<<(Tc<<BigInt(i))-Tc);R1.push(o)}O1=b1(R1,!0),AE=O1[0],TE=O1[1],I1=(e,t,r)=>r>32?x1(e,t,r):g1(e,t,r),k1=(e,t,r)=>r>32?v1(e,t,r):w1(e,t,r);xm=class e extends wo{constructor(t,r,n,o=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.rounds=i,bi(n),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=A1(this.state)}clone(){return this._cloneInto()}keccak(){wm(this.state32),IE(this.state32,this.rounds),wm(this.state32),this.posOut=0,this.pos=0}update(t){_n(this),t=gi(t),Wr(t);let{blockLen:r,state:n}=this,o=t.length;for(let i=0;i<o;){let s=Math.min(r-this.pos,o-i);for(let a=0;a<s;a++)n[this.pos++]^=t[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:t,suffix:r,pos:n,blockLen:o}=this;t[n]^=r,(r&128)!==0&&n===o-1&&this.keccak(),t[o-1]^=128,this.keccak()}writeInto(t){_n(this,!1),Wr(t),this.finish();let r=this.state,{blockLen:n}=this;for(let o=0,i=t.length;o<i;){this.posOut>=n&&this.keccak();let s=Math.min(n-this.posOut,i-o);t.set(r.subarray(this.posOut,this.posOut+s),o),this.posOut+=s,o+=s}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return bi(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(ru(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Zr(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:o,rounds:i,enableXOF:s}=this;return t||(t=new e(r,n,o,s,i)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=i,t.suffix=n,t.outputLen=o,t.enableXOF=s,t.destroyed=this.destroyed,t}},kE=(e,t,r)=>ou(()=>new xm(t,e,r)),C1=kE(1,136,256/8)});function Sr(e,t){let r=t||"hex",n=C1(ct(e,{strict:!1})?go(e):e);return r==="bytes"?n:ht(n)}var ms=C(()=>{U1();vn();rr();xe()});var zt,wi=C(()=>{zt=class extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){let r=super.get(t);return super.has(t)&&(super.delete(t),super.set(t,r)),r}set(t,r){if(super.has(t)&&super.delete(t),super.set(t,r),this.maxSize&&this.size>this.maxSize){let n=super.keys().next().value;n!==void 0&&super.delete(n)}return this}}});function pe(e,t){let{strict:r=!0}=t??{},n=`${e}.${r}`;if(vm.has(n))return vm.get(n);let o=BE.test(e)?e.toLowerCase()===e?!0:r?An(e)===e:!0:!1;return vm.set(n,o),o}var BE,vm,Zt=C(()=>{wi();hs();BE=/^0x[a-fA-F0-9]{40}$/,vm=new zt(8192)});function An(e,t){if(Sm.has(`${e}.${t}`))return Sm.get(`${e}.${t}`);let r=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),n=Sr(Ac(r),"bytes"),o=(t?r.substring(`${t}0x`.length):r).split("");for(let s=0;s<40;s+=2)n[s>>1]>>4>=8&&o[s]&&(o[s]=o[s].toUpperCase()),(n[s>>1]&15)>=8&&o[s+1]&&(o[s+1]=o[s+1].toUpperCase());let i=`0x${o.join("")}`;return Sm.set(`${e}.${t}`,i),i}function N1(e,t){if(!pe(e,{strict:!1}))throw new Ce({address:e});return An(e,t)}var Sm,hs=C(()=>{Vr();rr();ms();wi();Zt();Sm=new zt(8192)});function F1(e){let t=Sr(`0x${e.substring(4)}`).substring(26);return An(`0x${t}`)}var M1=C(()=>{hs();ms()});function dt(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new su(e.type);return`${e.name}(${Ic(e.inputs,{includeName:t})})`}function Ic(e,{includeName:t=!1}={}){return e?e.map(r=>PE(r,{includeName:t})).join(t?", ":","):""}function PE(e,{includeName:t}){return e.type.startsWith("tuple")?`(${Ic(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")}var vo=C(()=>{yt()});var au,kc,ys,So,cu,du,fu,uu,Bc,bs,lu,pu,Er,gs,mu,hu,yu,Pc,bu,gu,wu,ws,su,yt=C(()=>{vo();xr();le();au=class extends L{constructor({docsPath:t}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(`
1
+ var Q5=Object.defineProperty;var C=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var By=(e,t)=>{for(var r in t)Q5(e,r,{get:t[r],enumerable:!0})};var Hw,zw=C(()=>{Hw="1.2.3"});var nt,us=C(()=>{zw();nt=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,i=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...o?[`Docs: https://abitype.dev${o}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${Hw}`].join(`
2
+ `);super(i),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=o,this.metaMessages=r.metaMessages,this.shortMessage=t}}});function Kt(e,t){return e.exec(t)?.groups}var sm,am,Rf,wc=C(()=>{sm=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,am=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,Rf=/^\(.+?\).*?$/});function Of(e){let t=e.type;if($w.test(e.type)&&"components"in e){t="(";let r=e.components.length;for(let o=0;o<r;o++){let i=e.components[o];t+=Of(i),o<r-1&&(t+=", ")}let n=Kt($w,e.type);return t+=`)${n?.array||""}`,Of({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}var $w,Lw=C(()=>{wc();$w=/^tuple(?<array>(\[(\d*)\])*)$/});function ls(e){let t="",r=e.length;for(let n=0;n<r;n++){let o=e[n];t+=Of(o),n!==r-1&&(t+=", ")}return t}var Dw=C(()=>{Lw()});function cm(e){return e.type==="function"?`function ${e.name}(${ls(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${ls(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${ls(e.inputs)})`:e.type==="error"?`error ${e.name}(${ls(e.inputs)})`:e.type==="constructor"?`constructor(${ls(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}var qw=C(()=>{Dw()});function Gw(e){return jw.test(e)}function Vw(e){return Kt(jw,e)}function Ww(e){return Kw.test(e)}function Zw(e){return Kt(Kw,e)}function Xw(e){return Yw.test(e)}function Jw(e){return Kt(Yw,e)}function Cf(e){return Qw.test(e)}function e1(e){return Kt(Qw,e)}function r1(e){return t1.test(e)}function n1(e){return Kt(t1,e)}function i1(e){return o1.test(e)}function s1(e){return Kt(o1,e)}function a1(e){return tE.test(e)}var jw,Kw,Yw,Qw,t1,o1,tE,c1,Uf,Nf=C(()=>{wc();jw=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;Kw=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;Yw=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;Qw=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;t1=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;o1=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;tE=/^receive\(\) external payable$/;c1=new Set(["indexed"]),Uf=new Set(["calldata","memory","storage"])});var Ff,Mf,dm=C(()=>{us();Ff=class extends nt{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}},Mf=class extends nt{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}}});var Hf,zf,$f,Lf,Df,fm=C(()=>{us();Hf=class extends nt{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}},zf=class extends nt{constructor({param:t,name:r}){super("Invalid ABI parameter.",{details:t,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}},$f=class extends nt{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}},Lf=class extends nt{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}},Df=class extends nt{constructor({abiParameter:t}){super("Invalid ABI parameter.",{details:JSON.stringify(t,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}}});var jr,qf,jf,um=C(()=>{us();jr=class extends nt{constructor({signature:t,type:r}){super(`Invalid ${r} signature.`,{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}},qf=class extends nt{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}},jf=class extends nt{constructor({signature:t}){super("Invalid struct signature.",{details:t,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}}});var Gf,d1=C(()=>{us();Gf=class extends nt{constructor({type:t}){super("Circular reference detected.",{metaMessages:[`Struct "${t}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}}});var Vf,f1=C(()=>{us();Vf=class extends nt{constructor({current:t,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${t.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}}});function u1(e,t,r){let n="";if(r)for(let o of Object.entries(r)){if(!o)continue;let i="";for(let s of o[1])i+=`[${s.type}${s.name?`:${s.name}`:""}]`;n+=`(${o[0]}{${i}})`}return t?`${t}:${e}${n}`:`${e}${n}`}var Kf,l1=C(()=>{Kf=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]])});function p1(e,t={}){if(Xw(e))return rE(e,t);if(Ww(e))return nE(e,t);if(Gw(e))return oE(e,t);if(r1(e))return iE(e,t);if(i1(e))return sE(e);if(a1(e))return{type:"receive",stateMutability:"payable"};throw new qf({signature:e})}function rE(e,t={}){let r=Jw(e);if(!r)throw new jr({signature:e,type:"function"});let n=gr(r.parameters),o=[],i=n.length;for(let a=0;a<i;a++)o.push(ho(n[a],{modifiers:Uf,structs:t,type:"function"}));let s=[];if(r.returns){let a=gr(r.returns),c=a.length;for(let d=0;d<c;d++)s.push(ho(a[d],{modifiers:Uf,structs:t,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:o,outputs:s}}function nE(e,t={}){let r=Zw(e);if(!r)throw new jr({signature:e,type:"event"});let n=gr(r.parameters),o=[],i=n.length;for(let s=0;s<i;s++)o.push(ho(n[s],{modifiers:c1,structs:t,type:"event"}));return{name:r.name,type:"event",inputs:o}}function oE(e,t={}){let r=Vw(e);if(!r)throw new jr({signature:e,type:"error"});let n=gr(r.parameters),o=[],i=n.length;for(let s=0;s<i;s++)o.push(ho(n[s],{structs:t,type:"error"}));return{name:r.name,type:"error",inputs:o}}function iE(e,t={}){let r=n1(e);if(!r)throw new jr({signature:e,type:"constructor"});let n=gr(r.parameters),o=[],i=n.length;for(let s=0;s<i;s++)o.push(ho(n[s],{structs:t,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:o}}function sE(e){let t=s1(e);if(!t)throw new jr({signature:e,type:"fallback"});return{type:"fallback",stateMutability:t.stateMutability??"nonpayable"}}function ho(e,t){let r=u1(e,t?.type,t?.structs);if(Kf.has(r))return Kf.get(r);let n=Rf.test(e),o=Kt(n?cE:aE,e);if(!o)throw new Hf({param:e});if(o.name&&uE(o.name))throw new zf({param:e,name:o.name});let i=o.name?{name:o.name}:{},s=o.modifier==="indexed"?{indexed:!0}:{},a=t?.structs??{},c,d={};if(n){c="tuple";let u=gr(o.type),l=[],p=u.length;for(let m=0;m<p;m++)l.push(ho(u[m],{structs:a}));d={components:l}}else if(o.type in a)c="tuple",d={components:a[o.type]};else if(dE.test(o.type))c=`${o.type}256`;else if(o.type==="address payable")c="address";else if(c=o.type,t?.type!=="struct"&&!lm(c))throw new Mf({type:c});if(o.modifier){if(!t?.modifiers?.has?.(o.modifier))throw new $f({param:e,type:t?.type,modifier:o.modifier});if(Uf.has(o.modifier)&&!lE(c,!!o.array))throw new Lf({param:e,type:t?.type,modifier:o.modifier})}let f={type:`${c}${o.array??""}`,...i,...s,...d};return Kf.set(r,f),f}function gr(e,t=[],r="",n=0){let o=e.trim().length;for(let i=0;i<o;i++){let s=e[i],a=e.slice(i+1);switch(s){case",":return n===0?gr(a,[...t,r.trim()]):gr(a,t,`${r}${s}`,n);case"(":return gr(a,t,`${r}${s}`,n+1);case")":return gr(a,t,`${r}${s}`,n-1);default:return gr(a,t,`${r}${s}`,n)}}if(r==="")return t;if(n!==0)throw new Vf({current:r,depth:n});return t.push(r.trim()),t}function lm(e){return e==="address"||e==="bool"||e==="function"||e==="string"||sm.test(e)||am.test(e)}function uE(e){return e==="address"||e==="bool"||e==="function"||e==="string"||e==="tuple"||sm.test(e)||am.test(e)||fE.test(e)}function lE(e,t){return t||e==="bytes"||e==="string"||e==="tuple"}var aE,cE,dE,fE,pm=C(()=>{wc();dm();fm();um();f1();l1();Nf();aE=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,cE=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,dE=/^u?int$/;fE=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/});function m1(e){let t={},r=e.length;for(let s=0;s<r;s++){let a=e[s];if(!Cf(a))continue;let c=e1(a);if(!c)throw new jr({signature:a,type:"struct"});let d=c.properties.split(";"),f=[],u=d.length;for(let l=0;l<u;l++){let m=d[l].trim();if(!m)continue;let h=ho(m,{type:"struct"});f.push(h)}if(!f.length)throw new jf({signature:a});t[c.name]=f}let n={},o=Object.entries(t),i=o.length;for(let s=0;s<i;s++){let[a,c]=o[s];n[a]=h1(c,t)}return n}function h1(e=[],t={},r=new Set){let n=[],o=e.length;for(let i=0;i<o;i++){let s=e[i];if(Rf.test(s.type))n.push(s);else{let c=Kt(pE,s.type);if(!c?.type)throw new Df({abiParameter:s});let{array:d,type:f}=c;if(f in t){if(r.has(f))throw new Gf({type:f});n.push({...s,type:`tuple${d??""}`,components:h1(t[f],t,new Set([...r,f]))})}else if(lm(f))n.push(s);else throw new Ff({type:f})}}return n}var pE,y1=C(()=>{wc();dm();fm();um();d1();Nf();pm();pE=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/});function Wf(e){let t=m1(e),r=[],n=e.length;for(let o=0;o<n;o++){let i=e[o];Cf(i)||r.push(p1(i,t))}return r}var b1=C(()=>{Nf();y1();pm()});var mm=C(()=>{qw();b1()});function ce(e){return typeof e=="string"?{address:e,type:"json-rpc"}:e}var Ye=C(()=>{});var hm,g1=C(()=>{hm="2.57.10"});function w1(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?w1(e.cause,t):t?null:e}var ym,L,le=C(()=>{g1();ym={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${hm}`},L=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,i=ym.getDocsUrl?.({...r,docsPath:o}),s=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...n?[`Details: ${n}`]:[],...ym.version?[`Version: ${ym.version}`]:[]].join(`
3
+ `);super(s,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=o,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=t,this.version=hm}walk(t){return w1(this,t)}}});var Ce,Gr=C(()=>{le();Ce=class extends L{constructor({address:t}){super(`Address "${t}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}});function dt(e,{strict:t=!0}={}){return!e||typeof e!="string"?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}var xn=C(()=>{});var xc,vc,Sc,Zf=C(()=>{le();xc=class extends L{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${t}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},vc=class extends L{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${t}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}},Sc=class extends L{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${r} ${n} long, but is ${t} ${n} long.`,{name:"InvalidBytesLengthError"})}}});function yo(e,{dir:t,size:r=32}={}){return typeof e=="string"?vn(e,{dir:t,size:r}):mE(e,{dir:t,size:r})}function vn(e,{dir:t,size:r=32}={}){if(r===null)return e;let n=e.replace("0x","");if(n.length>r*2)throw new vc({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function mE(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new vc({size:e.length,targetSize:r,type:"bytes"});let n=new Uint8Array(r);for(let o=0;o<r;o++){let i=t==="right";n[i?o:r-o-1]=e[i?o:e.length-o-1]}return n}var Yf=C(()=>{Zf()});var bo,Xf,Jf,Ec=C(()=>{le();bo=class extends L{constructor({max:t,min:r,signed:n,size:o,value:i}){super(`Number "${i}" is not in safe ${o?`${o*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${t?`(${r} to ${t})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}},Xf=class extends L{constructor(t){super(`Bytes value "${t}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}},Jf=class extends L{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}}});function ge(e){return dt(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}var wr=C(()=>{xn()});function Vr(e,{dir:t="left"}={}){let r=typeof e=="string"?e.replace("0x",""):e,n=0;for(let o=0;o<r.length-1&&r[t==="left"?o:r.length-o-1].toString()==="0";o++)n++;return r=t==="left"?r.slice(n):r.slice(0,r.length-n),typeof e=="string"?(r.length===1&&t==="right"&&(r=`${r}0`),`0x${r.length%2===1?`0${r}`:r}`):r}var Qf=C(()=>{});function Wt(e,{size:t}){if(ge(e)>t)throw new Jf({givenSize:ge(e),maxSize:t})}function De(e,t={}){let{signed:r}=t;t.size&&Wt(e,{size:t.size});let n=BigInt(e);if(!r)return n;let o=Math.ceil((e.length-2)/2),i=(1n<<BigInt(o)*8n-1n)-1n;return n<=i?n:n-BigInt(`0x${"f".padStart(o*2,"f")}`)-1n}function Xe(e,t={}){let r=De(e,t),n=Number(r);if(!Number.isSafeInteger(n))throw new bo({max:`${Number.MAX_SAFE_INTEGER}`,min:`${Number.MIN_SAFE_INTEGER}`,signed:t.signed,size:t.size,value:`${r}n`});return n}var Bt=C(()=>{Ec();wr()});function ht(e,t={}){return typeof e=="number"||typeof e=="bigint"?V(e,t):typeof e=="string"?_c(e,t):typeof e=="boolean"?bm(e,t):Me(e,t)}function bm(e,t={}){let r=`0x${Number(e)}`;return typeof t.size=="number"?(Wt(r,{size:t.size}),yo(r,{size:t.size})):r}function Me(e,t={}){let r="";for(let o=0;o<e.length;o++)r+=hE[e[o]];let n=`0x${r}`;return typeof t.size=="number"?(Wt(n,{size:t.size}),yo(n,{dir:"right",size:t.size})):n}function V(e,t={}){let{signed:r,size:n}=t,o=BigInt(e),i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));let s=typeof i=="bigint"&&r?-i-1n:0;if(i&&o>i||o<s){let c=typeof e=="bigint"?"n":"";throw new bo({max:i?`${i}${c}`:void 0,min:`${s}${c}`,signed:r,size:n,value:`${e}${c}`})}let a=`0x${(r&&o<0?(1n<<BigInt(n*8))+BigInt(o):o).toString(16)}`;return n?yo(a,{size:n}):a}function _c(e,t={}){let r=yE.encode(e);return Me(r,t)}var hE,yE,xe=C(()=>{Ec();Yf();Bt();hE=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));yE=new TextEncoder});function go(e,t={}){return typeof e=="number"||typeof e=="bigint"?wE(e,t):typeof e=="boolean"?gE(e,t):dt(e)?Pt(e,t):Ac(e,t)}function gE(e,t={}){let r=new Uint8Array(1);return r[0]=Number(e),typeof t.size=="number"?(Wt(r,{size:t.size}),yo(r,{size:t.size})):r}function x1(e){if(e>=Sn.zero&&e<=Sn.nine)return e-Sn.zero;if(e>=Sn.A&&e<=Sn.F)return e-(Sn.A-10);if(e>=Sn.a&&e<=Sn.f)return e-(Sn.a-10)}function Pt(e,t={}){let r=e;t.size&&(Wt(r,{size:t.size}),r=yo(r,{dir:"right",size:t.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);let o=n.length/2,i=new Uint8Array(o);for(let s=0,a=0;s<o;s++){let c=x1(n.charCodeAt(a++)),d=x1(n.charCodeAt(a++));if(c===void 0||d===void 0)throw new L(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);i[s]=c*16+d}return i}function wE(e,t){let r=V(e,t);return Pt(r)}function Ac(e,t={}){let r=bE.encode(e);return typeof t.size=="number"?(Wt(r,{size:t.size}),yo(r,{dir:"right",size:t.size})):r}var bE,Sn,rr=C(()=>{le();xn();Yf();Bt();xe();bE=new TextEncoder;Sn={zero:48,nine:57,A:65,F:70,a:97,f:102}});function xE(e,t=!1){return t?{h:Number(e&eu),l:Number(e>>v1&eu)}:{h:Number(e>>v1&eu)|0,l:Number(e&eu)|0}}function S1(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=xE(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var eu,v1,E1,_1,A1,T1,I1=C(()=>{eu=BigInt(4294967295),v1=BigInt(32);E1=(e,t,r)=>e<<r|t>>>32-r,_1=(e,t,r)=>t<<r|e>>>32-r,A1=(e,t,r)=>t<<r-32|e>>>64-r,T1=(e,t,r)=>e<<r-32|t>>>64-r});var bi,k1=C(()=>{bi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});function vE(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function gi(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Kr(e,...t){if(!vE(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function B1(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");gi(e.outputLen),gi(e.blockLen)}function En(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function tu(e,t){Kr(e);let r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function P1(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Wr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ru(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function xr(e,t){return e<<32-t|e>>>t}function EE(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function _E(e){for(let t=0;t<e.length;t++)e[t]=EE(e[t]);return e}function AE(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function wi(e){return typeof e=="string"&&(e=AE(e)),Kr(e),e}function R1(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];Kr(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let i=e[n];r.set(i,o),o+=i.length}return r}function nu(e){let t=n=>e().update(wi(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function ou(e=32){if(bi&&typeof bi.getRandomValues=="function")return bi.getRandomValues(new Uint8Array(e));if(bi&&typeof bi.randomBytes=="function")return Uint8Array.from(bi.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}var SE,gm,wo,xo=C(()=>{k1();SE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;gm=SE?e=>e:_E;wo=class{}});function CE(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let s=0;s<10;s++)r[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){let a=(s+8)%10,c=(s+2)%10,d=r[c],f=r[c+1],u=O1(d,f,1)^r[a],l=C1(d,f,1)^r[a+1];for(let p=0;p<50;p+=10)e[s+p]^=u,e[s+p+1]^=l}let o=e[2],i=e[3];for(let s=0;s<24;s++){let a=N1[s],c=O1(o,i,a),d=C1(o,i,a),f=U1[s];o=e[f],i=e[f+1],e[f]=c,e[f+1]=d}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)r[a]=e[s+a];for(let a=0;a<10;a++)e[s+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=RE[n],e[1]^=OE[n]}Wr(r)}var TE,Tc,IE,kE,BE,PE,U1,N1,F1,M1,RE,OE,O1,C1,wm,UE,H1,z1=C(()=>{I1();xo();TE=BigInt(0),Tc=BigInt(1),IE=BigInt(2),kE=BigInt(7),BE=BigInt(256),PE=BigInt(113),U1=[],N1=[],F1=[];for(let e=0,t=Tc,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],U1.push(2*(5*n+r)),N1.push((e+1)*(e+2)/2%64);let o=TE;for(let i=0;i<7;i++)t=(t<<Tc^(t>>kE)*PE)%BE,t&IE&&(o^=Tc<<(Tc<<BigInt(i))-Tc);F1.push(o)}M1=S1(F1,!0),RE=M1[0],OE=M1[1],O1=(e,t,r)=>r>32?A1(e,t,r):E1(e,t,r),C1=(e,t,r)=>r>32?T1(e,t,r):_1(e,t,r);wm=class e extends wo{constructor(t,r,n,o=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.rounds=i,gi(n),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=P1(this.state)}clone(){return this._cloneInto()}keccak(){gm(this.state32),CE(this.state32,this.rounds),gm(this.state32),this.posOut=0,this.pos=0}update(t){En(this),t=wi(t),Kr(t);let{blockLen:r,state:n}=this,o=t.length;for(let i=0;i<o;){let s=Math.min(r-this.pos,o-i);for(let a=0;a<s;a++)n[this.pos++]^=t[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:t,suffix:r,pos:n,blockLen:o}=this;t[n]^=r,(r&128)!==0&&n===o-1&&this.keccak(),t[o-1]^=128,this.keccak()}writeInto(t){En(this,!1),Kr(t),this.finish();let r=this.state,{blockLen:n}=this;for(let o=0,i=t.length;o<i;){this.posOut>=n&&this.keccak();let s=Math.min(n-this.posOut,i-o);t.set(r.subarray(this.posOut,this.posOut+s),o),this.posOut+=s,o+=s}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return gi(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(tu(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Wr(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:o,rounds:i,enableXOF:s}=this;return t||(t=new e(r,n,o,s,i)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=i,t.suffix=n,t.outputLen=o,t.enableXOF=s,t.destroyed=this.destroyed,t}},UE=(e,t,r)=>nu(()=>new wm(t,e,r)),H1=UE(1,136,256/8)});function vr(e,t){let r=t||"hex",n=H1(dt(e,{strict:!1})?go(e):e);return r==="bytes"?n:ht(n)}var ps=C(()=>{z1();xn();rr();xe()});var Mt,xi=C(()=>{Mt=class extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){let r=super.get(t);return super.has(t)&&(super.delete(t),super.set(t,r)),r}set(t,r){if(super.has(t)&&super.delete(t),super.set(t,r),this.maxSize&&this.size>this.maxSize){let n=super.keys().next().value;n!==void 0&&super.delete(n)}return this}}});function pe(e,t){let{strict:r=!0}=t??{},n=`${e}.${r}`;if(xm.has(n))return xm.get(n);let o=NE.test(e)?e.toLowerCase()===e?!0:r?_n(e)===e:!0:!1;return xm.set(n,o),o}var NE,xm,Zt=C(()=>{xi();ms();NE=/^0x[a-fA-F0-9]{40}$/,xm=new Mt(8192)});function _n(e,t){if(vm.has(`${e}.${t}`))return vm.get(`${e}.${t}`);let r=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),n=vr(Ac(r),"bytes"),o=(t?r.substring(`${t}0x`.length):r).split("");for(let s=0;s<40;s+=2)n[s>>1]>>4>=8&&o[s]&&(o[s]=o[s].toUpperCase()),(n[s>>1]&15)>=8&&o[s+1]&&(o[s+1]=o[s+1].toUpperCase());let i=`0x${o.join("")}`;return vm.set(`${e}.${t}`,i),i}function $1(e,t){if(!pe(e,{strict:!1}))throw new Ce({address:e});return _n(e,t)}var vm,ms=C(()=>{Gr();rr();ps();xi();Zt();vm=new Mt(8192)});function L1(e){let t=vr(`0x${e.substring(4)}`).substring(26);return _n(`0x${t}`)}var D1=C(()=>{ms();ps()});function ft(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new iu(e.type);return`${e.name}(${Ic(e.inputs,{includeName:t})})`}function Ic(e,{includeName:t=!1}={}){return e?e.map(r=>FE(r,{includeName:t})).join(t?", ":","):""}function FE(e,{includeName:t}){return e.type.startsWith("tuple")?`(${Ic(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")}var vo=C(()=>{yt()});var su,kc,hs,So,au,cu,du,fu,Bc,ys,uu,lu,Sr,bs,pu,mu,hu,Pc,yu,bu,gu,gs,iu,yt=C(()=>{vo();wr();le();su=class extends L{constructor({docsPath:t}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(`
4
4
  `),{docsPath:t,name:"AbiConstructorNotFoundError"})}},kc=class extends L{constructor({docsPath:t}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(`
5
- `),{docsPath:t,name:"AbiConstructorParamsNotFoundError"})}},ys=class extends L{constructor({data:t,params:r,size:n}){super([`Data size of ${n} bytes is too small for given parameters.`].join(`
6
- `),{metaMessages:[`Params: (${Ic(r,{includeName:!0})})`,`Data: ${t} (${n} bytes)`],name:"AbiDecodingDataSizeTooSmallError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t,this.params=r,this.size=n}},So=class extends L{constructor({cause:t}={}){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError",cause:t})}},cu=class extends L{constructor({expectedLength:t,givenLength:r,type:n}){super([`ABI encoding array length mismatch for type ${n}.`,`Expected length: ${t}`,`Given length: ${r}`].join(`
7
- `),{name:"AbiEncodingArrayLengthMismatchError"})}},du=class extends L{constructor({expectedSize:t,value:r}){super(`Size of bytes "${r}" (bytes${ge(r)}) does not match expected size (bytes${t}).`,{name:"AbiEncodingBytesSizeMismatchError"})}},fu=class extends L{constructor({expectedLength:t,givenLength:r}){super(["ABI encoding params/values length mismatch.",`Expected length (params): ${t}`,`Given length (values): ${r}`].join(`
8
- `),{name:"AbiEncodingLengthMismatchError"})}},uu=class extends L{constructor(t,{docsPath:r}){super([`Arguments (\`args\`) were provided to "${t}", but "${t}" on the ABI does not contain any parameters (\`inputs\`).`,"Cannot encode error result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the inputs exist on it."].join(`
5
+ `),{docsPath:t,name:"AbiConstructorParamsNotFoundError"})}},hs=class extends L{constructor({data:t,params:r,size:n}){super([`Data size of ${n} bytes is too small for given parameters.`].join(`
6
+ `),{metaMessages:[`Params: (${Ic(r,{includeName:!0})})`,`Data: ${t} (${n} bytes)`],name:"AbiDecodingDataSizeTooSmallError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t,this.params=r,this.size=n}},So=class extends L{constructor({cause:t}={}){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError",cause:t})}},au=class extends L{constructor({expectedLength:t,givenLength:r,type:n}){super([`ABI encoding array length mismatch for type ${n}.`,`Expected length: ${t}`,`Given length: ${r}`].join(`
7
+ `),{name:"AbiEncodingArrayLengthMismatchError"})}},cu=class extends L{constructor({expectedSize:t,value:r}){super(`Size of bytes "${r}" (bytes${ge(r)}) does not match expected size (bytes${t}).`,{name:"AbiEncodingBytesSizeMismatchError"})}},du=class extends L{constructor({expectedLength:t,givenLength:r}){super(["ABI encoding params/values length mismatch.",`Expected length (params): ${t}`,`Given length (values): ${r}`].join(`
8
+ `),{name:"AbiEncodingLengthMismatchError"})}},fu=class extends L{constructor(t,{docsPath:r}){super([`Arguments (\`args\`) were provided to "${t}", but "${t}" on the ABI does not contain any parameters (\`inputs\`).`,"Cannot encode error result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the inputs exist on it."].join(`
9
9
  `),{docsPath:r,name:"AbiErrorInputsNotFoundError"})}},Bc=class extends L{constructor(t,{docsPath:r}={}){super([`Error ${t?`"${t}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it."].join(`
10
- `),{docsPath:r,name:"AbiErrorNotFoundError"})}},bs=class extends L{constructor(t,{docsPath:r,cause:n}){super([`Encoded error signature "${t}" not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${t}.`].join(`
11
- `),{docsPath:r,name:"AbiErrorSignatureNotFoundError",cause:n}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.signature=t}},lu=class extends L{constructor({docsPath:t}){super("Cannot extract event signature from empty topics.",{docsPath:t,name:"AbiEventSignatureEmptyTopicsError"})}},pu=class extends L{constructor(t,{docsPath:r}){super([`Encoded event signature "${t}" not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it.",`You can look up the signature here: https://4byte.sourcify.dev/?q=${t}.`].join(`
12
- `),{docsPath:r,name:"AbiEventSignatureNotFoundError"})}},Er=class extends L{constructor(t,{docsPath:r}={}){super([`Function ${t?`"${t}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it."].join(`
13
- `),{docsPath:r,name:"AbiFunctionNotFoundError"})}},gs=class extends L{constructor(t,{docsPath:r}){super([`Function "${t}" does not contain any \`outputs\` on ABI.`,"Cannot decode function result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the function exists on it."].join(`
14
- `),{docsPath:r,name:"AbiFunctionOutputsNotFoundError"})}},mu=class extends L{constructor(t,{docsPath:r}){super([`Encoded function signature "${t}" not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it.",`You can look up the signature here: https://4byte.sourcify.dev/?q=${t}.`].join(`
15
- `),{docsPath:r,name:"AbiFunctionSignatureNotFoundError"})}},hu=class extends L{constructor(t,r){super("Found ambiguous types in overloaded ABI items.",{metaMessages:[`\`${t.type}\` in \`${dt(t.abiItem)}\`, and`,`\`${r.type}\` in \`${dt(r.abiItem)}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."],name:"AbiItemAmbiguityError"})}},yu=class extends L{constructor({expectedSize:t,givenSize:r}){super(`Expected bytes${t}, got bytes${r}.`,{name:"BytesSizeMismatchError"})}},Pc=class extends L{constructor({abiItem:t,data:r,params:n,size:o}){super([`Data size of ${o} bytes is too small for non-indexed event parameters.`].join(`
16
- `),{metaMessages:[`Params: (${Ic(n,{includeName:!0})})`,`Data: ${r} (${o} bytes)`],name:"DecodeLogDataMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=t,this.data=r,this.params=n,this.size=o}},bu=class extends L{constructor({abiItem:t,param:r}){super([`Expected a topic for indexed event parameter${r.name?` "${r.name}"`:""} on event "${dt(t,{includeName:!0})}".`].join(`
17
- `),{name:"DecodeLogTopicsMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=t}},gu=class extends L{constructor(t,{docsPath:r}){super([`Type "${t}" is not a valid encoding type.`,"Please provide a valid ABI type."].join(`
18
- `),{docsPath:r,name:"InvalidAbiEncodingType"})}},wu=class extends L{constructor(t,{docsPath:r}){super([`Type "${t}" is not a valid decoding type.`,"Please provide a valid ABI type."].join(`
19
- `),{docsPath:r,name:"InvalidAbiDecodingType"})}},ws=class extends L{constructor(t){super([`Value "${t}" is not a valid array.`].join(`
20
- `),{name:"InvalidArrayError"})}},su=class extends L{constructor(t){super([`"${t}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join(`
21
- `),{name:"InvalidDefinitionTypeError"})}}});var Rc,xs,xu,Em=C(()=>{le();Rc=class extends L{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`,{name:"NegativeOffsetError"})}},xs=class extends L{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`,{name:"PositionOutOfBoundsError"})}},xu=class extends L{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`,{name:"RecursiveReadLimitExceededError"})}}});function vs(e,{recursiveReadLimit:t=8192}={}){let r=Object.create(RE);return r.bytes=e,r.dataView=new DataView(e.buffer??e,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}var RE,vu=C(()=>{Em();RE={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new xu({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new xs({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new Rc({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new Rc({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}}});function nr(e,t,r,{strict:n}={}){return ct(e,{strict:!1})?Su(e,t,r,{strict:n}):_m(e,t,r,{strict:n})}function z1(e,t){if(typeof t=="number"&&t>0&&t>ge(e)-1)throw new xc({offset:t,position:"start",size:ge(e)})}function H1(e,t,r){if(typeof t=="number"&&typeof r=="number"&&ge(e)!==r-t)throw new xc({offset:r,position:"end",size:ge(e)})}function _m(e,t,r,{strict:n}={}){z1(e,t);let o=e.slice(t,r);return n&&H1(o,t,r),o}function Su(e,t,r,{strict:n}={}){z1(e,t);let o=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return n&&H1(o,t,r),o}var Eo=C(()=>{Yf();vn();xr()});function $1(e,t={}){typeof t.size<"u"&&Wt(e,{size:t.size});let r=Me(e);return De(r,t)}function L1(e,t={}){let r=e;if(typeof t.size<"u"&&(Wt(r,{size:t.size}),r=Kr(r)),r.length>1||r[0]>1)throw new Jf(r);return!!r[0]}function Yr(e,t={}){typeof t.size<"u"&&Wt(e,{size:t.size});let r=Me(e);return Xe(r,t)}function D1(e,t={}){let r=e;return typeof t.size<"u"&&(Wt(r,{size:t.size}),r=Kr(r,{dir:"right"})),new TextDecoder().decode(r)}var q1=C(()=>{Ec();eu();Pt();xe()});function _r(e){return typeof e[0]=="string"?Le(e):OE(e)}function OE(e){let t=0;for(let o of e)t+=o.length;let r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function Le(e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}var or=C(()=>{});var j1,Eu,Am=C(()=>{j1=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Eu=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/});function Xr(e,t){if(e.length!==t.length)throw new fu({expectedLength:e.length,givenLength:t.length});let r=CE({params:e,values:t});return km(r)}function CE({params:e,values:t}){let r=[];for(let n=0;n<e.length;n++)r.push(Im({param:e[n],value:t[n]}));return r}function Im({param:e,value:t}){let r=Oc(e.type);if(r){let[n,o]=r;return NE(t,{length:n,param:{...e,type:o}})}if(e.type==="tuple")return $E(t,{param:e});if(e.type==="address")return UE(t);if(e.type==="bool")return ME(t);if(e.type.startsWith("uint")||e.type.startsWith("int")){let n=e.type.startsWith("int"),[,,o="256"]=Eu.exec(e.type)??[];return zE(t,{signed:n,size:Number(o)})}if(e.type.startsWith("bytes"))return FE(t,{param:e});if(e.type==="string")return HE(t);throw new gu(e.type,{docsPath:"/docs/contract/encodeAbiParameters"})}function km(e){let t=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:a}=e[i];s?t+=32:t+=ge(a)}let r=[],n=[],o=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:a}=e[i];s?(r.push(V(t+o,{size:32})),n.push(a),o+=ge(a)):r.push(a)}return Le([...r,...n])}function UE(e){if(!pe(e))throw new Ce({address:e});return{dynamic:!1,encoded:Sn(e.toLowerCase())}}function NE(e,{length:t,param:r}){let n=t===null;if(!Array.isArray(e))throw new ws(e);if(!n&&e.length!==t)throw new cu({expectedLength:t,givenLength:e.length,type:`${r.type}[${t}]`});let o=e.length===0&&Tm(r),i=[];for(let s=0;s<e.length;s++){let a=Im({param:r,value:e[s]});a.dynamic&&(o=!0),i.push(a)}if(n||o){let s=km(i);if(n){let a=V(i.length,{size:32});return{dynamic:!0,encoded:Le([a,s])}}if(o)return{dynamic:!0,encoded:s}}return{dynamic:!1,encoded:Le(i.map(({encoded:s})=>s))}}function FE(e,{param:t}){let[,r]=t.type.split("bytes"),n=ge(e);if(!r){let o=e;return n%32!==0&&(o=Sn(o,{dir:"right",size:Math.ceil((e.length-2)/2/32)*32})),{dynamic:!0,encoded:Le([Sn(V(n,{size:32})),o])}}if(n!==Number.parseInt(r,10))throw new du({expectedSize:Number.parseInt(r,10),value:e});return{dynamic:!1,encoded:Sn(e,{dir:"right"})}}function ME(e){if(typeof e!="boolean")throw new L(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:Sn(gm(e))}}function zE(e,{signed:t,size:r=256}){if(typeof r=="number"){let n=2n**(BigInt(r)-(t?1n:0n))-1n,o=t?-n-1n:0n;if(e>n||e<o)throw new bo({max:n.toString(),min:o.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:V(e,{size:32,signed:t})}}function HE(e){let t=_c(e),r=Math.ceil(ge(t)/32),n=[];for(let o=0;o<r;o++)n.push(Sn(nr(t,o*32,(o+1)*32),{dir:"right"}));return{dynamic:!0,encoded:Le([Sn(V(ge(t),{size:32})),...n])}}function $E(e,{param:t}){let r=!1,n=[];for(let o=0;o<t.components.length;o++){let i=t.components[o],s=Array.isArray(e)?o:i.name,a=Im({param:i,value:e[s]});n.push(a),a.dynamic&&(r=!0)}return{dynamic:r,encoded:r?km(n):Le(n.map(({encoded:o})=>o))}}function Oc(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function Tm(e){let{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return e.components.some(Tm);let r=Oc(t);return r?Tm({...e,type:r[1]}):!1}var xi=C(()=>{yt();Vr();le();Ec();Zt();or();Xf();xr();Eo();xe();Am()});function Tn(e,t){let r=typeof t=="string"?Rt(t):t,n=vs(r);if(ge(r)===0&&e.length>0)throw new So;if(ge(t)&&ge(t)<32)throw new ys({data:typeof t=="string"?t:Me(t),params:e,size:ge(t)});let o=0,i=[];for(let s=0;s<e.length;++s){let a=e[s];o<r.length&&n.setPosition(o);let[c,d]=Ss(n,a,{staticPosition:0});o+=d,i.push(c)}return i}function Ss(e,t,{staticPosition:r}){let n=Oc(t.type);if(n){let[o,i]=n;return DE(e,{...t,type:i},{length:o,staticPosition:r})}if(t.type==="tuple")return VE(e,t,{staticPosition:r});if(t.type==="address")return LE(e);if(t.type==="bool")return qE(e);if(t.type.startsWith("bytes"))return jE(e,t,{staticPosition:r});if(t.type.startsWith("uint")||t.type.startsWith("int"))return GE(e,t);if(t.type==="string")return KE(e,{staticPosition:r});throw new wu(t.type,{docsPath:"/docs/contract/decodeAbiParameters"})}function LE(e){let t=e.readBytes(32);return[An(Me(_m(t,-20))),32]}function DE(e,t,{length:r,staticPosition:n}){if(r===null){let s=Yr(e.readBytes(Bm)),a=n+s,c=a+G1;e.setPosition(a);let d=Yr(e.readBytes(G1)),f=Cc(t),u=0,l=[];for(let p=0;p<d;++p){e.setPosition(c+(f?p*32:u));let[m,h]=Ss(e,t,{staticPosition:c});u+=h,l.push(m),h===0&&(e.assertReadLimit(),e._touch())}return e.setPosition(n+32),[l,32]}if(Cc(t)){let s=Yr(e.readBytes(Bm)),a=n+s,c=[];for(let d=0;d<r;++d){e.setPosition(a+d*32);let[f]=Ss(e,t,{staticPosition:a});c.push(f)}return e.setPosition(n+32),[c,32]}let o=0,i=[];for(let s=0;s<r;++s){let[a,c]=Ss(e,t,{staticPosition:n+o});o+=c,i.push(a),c===0&&(e.assertReadLimit(),e._touch())}return[i,o]}function qE(e){return[L1(e.readBytes(32),{size:32}),32]}function jE(e,t,{staticPosition:r}){let[n,o]=t.type.split("bytes");if(!o){let s=Yr(e.readBytes(32));e.setPosition(r+s);let a=Yr(e.readBytes(32));if(a===0)return e.setPosition(r+32),["0x",32];let c=e.readBytes(a);return e.setPosition(r+32),[Me(c),32]}return[Me(e.readBytes(Number.parseInt(o,10),32)),32]}function GE(e,t){let r=t.type.startsWith("int"),n=Number.parseInt(t.type.split("int")[1]||"256",10),o=e.readBytes(32);return[n>48?$1(o,{signed:r}):Yr(o,{signed:r}),32]}function VE(e,t,{staticPosition:r}){let n=t.components.length===0||t.components.some(({name:s})=>!s),o=n?[]:{},i=0;if(Cc(t)){let s=Yr(e.readBytes(Bm)),a=r+s;for(let c=0;c<t.components.length;++c){let d=t.components[c];e.setPosition(a+i);let[f,u]=Ss(e,d,{staticPosition:a});i+=u,o[n?c:d?.name]=f}return e.setPosition(r+32),[o,32]}for(let s=0;s<t.components.length;++s){let a=t.components[s],[c,d]=Ss(e,a,{staticPosition:r});o[n?s:a?.name]=c,i+=d}return[o,i]}function KE(e,{staticPosition:t}){let r=Yr(e.readBytes(32)),n=t+r;e.setPosition(n);let o=Yr(e.readBytes(32));if(o===0)return e.setPosition(t+32),["",32];let i=e.readBytes(o,32),s=D1(i);return e.setPosition(t+32),[s,32]}function Cc(e){let{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return e.components?.some(Cc);let r=Oc(e.type);return!!(r&&Cc({...e,type:r[1]}))}var G1,Bm,Uc=C(()=>{yt();hs();vu();xr();Eo();q1();rr();xe();xi();G1=32,Bm=32});var V1,_u,K1,Au=C(()=>{V1={1:"An `assert` condition failed.",17:"Arithmetic operation resulted in underflow or overflow.",18:"Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).",33:"Attempted to convert to an invalid type.",34:"Attempted to access a storage byte array that is incorrectly encoded.",49:"Performed `.pop()` on an empty array",50:"Array index is out of bounds.",65:"Allocated too much memory or created an array which is too large.",81:"Attempted to call a zero-initialized variable of internal function type."},_u={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},K1={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"}});function W1(e){return WE(e)}var WE,Z1=C(()=>{rr();ms();WE=e=>Sr(go(e))});function Y1(e){let t=!0,r="",n=0,o="",i=!1;for(let s=0;s<e.length;s++){let a=e[s];if(["(",")",","].includes(a)&&(t=!0),a==="("&&n++,a===")"&&n--,!!t){if(n===0){if(a===" "&&["event","function",""].includes(o))o="";else if(o+=a,a===")"){i=!0;break}continue}if(a===" "){!r.endsWith(",")&&!r.endsWith("(")&&(r="",t=!1);continue}o+=a,r+=a}}if(!i)throw new L("Unable to normalize signature.");return o}var X1=C(()=>{le()});var J1,Q1=C(()=>{hm();X1();J1=e=>{let t=typeof e=="string"?e:dm(e);return Y1(t)}});function Tu(e){return W1(J1(e))}var Pm=C(()=>{Z1();Q1()});var Jr,Es=C(()=>{Eo();Pm();Jr=e=>nr(Tu(e),0,4)});function Iu(e){let{abi:t,data:r,cause:n}=e,o=nr(r,0,4);if(o==="0x")throw new So({cause:n});let s=[...t||[],_u,K1].find(a=>a.type==="error"&&o===Jr(dt(a)));if(!s)throw new bs(o,{docsPath:"/docs/contract/decodeErrorResult",cause:n});return{abiItem:s,args:"inputs"in s&&s.inputs&&s.inputs.length>0?Tn(s.inputs,nr(r,4)):void 0,errorName:s.name}}var Rm=C(()=>{Au();yt();Eo();Es();Uc();vo()});var _s,ku=C(()=>{Pm();_s=Tu});function Om(e){let{abi:t,data:r,strict:n,topics:o}=e,i=n??!0,[s,...a]=o;if(!s)throw new lu({docsPath:ex});let c=t.find(b=>b.type==="event"&&s===_s(dt(b)));if(!(c&&"name"in c)||c.type!=="event")throw new pu(s,{docsPath:ex});let{name:d,inputs:f}=c,u=f?.some(b=>!("name"in b&&b.name)),l=u?[]:{},p=f.map((b,x)=>[b,x]).filter(([b])=>"indexed"in b&&b.indexed),m=[];for(let b=0;b<p.length;b++){let[x,g]=p[b],w=a[b];if(!w){if(i)throw new bu({abiItem:c,param:x});m.push([x,g]);continue}l[u?g:x.name||g]=ZE({param:x,value:w})}let h=f.filter(b=>!("indexed"in b&&b.indexed)),y=i?h:[...m.map(([b])=>b),...h];if(y.length>0){if(r&&r!=="0x")try{let b=Tn(y,r);if(b){let x=0;if(!i)for(let[g,w]of m)l[u?w:g.name||w]=b[x++];if(u)for(let g=0;g<f.length;g++)l[g]===void 0&&x<b.length&&(l[g]=b[x++]);else for(let g=0;g<h.length;g++)l[h[g].name]=b[x++]}}catch(b){if(i)throw b instanceof ys||b instanceof xs?new Pc({abiItem:c,data:r,params:y,size:ge(r)}):b}else if(i)throw new Pc({abiItem:c,data:"0x",params:y,size:0})}return{eventName:d,args:Object.values(l).length>0?l:void 0}}function ZE({param:e,value:t}){return e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/)?t:(Tn([e],t)||[])[0]}var ex,tx=C(()=>{yt();Em();xr();ku();Uc();vo();ex="/docs/contract/decodeEventLog"});function rx(e){let{abi:t,data:r}=e,n=nr(r,0,4),o=t.find(i=>i.type==="function"&&n===Jr(dt(i)));if(!o)throw new mu(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:o.name,args:"inputs"in o&&o.inputs&&o.inputs.length>0?Tn(o.inputs,nr(r,4)):void 0}}var nx=C(()=>{yt();Eo();Es();Uc();vo()});function Qr(e){let{abi:t,args:r=[],name:n}=e,o=ct(n,{strict:!1}),i=t.filter(a=>o?a.type==="function"?Jr(a)===n:a.type==="event"?_s(a)===n:!1:"name"in a&&a.name===n);if(i.length===0)return;if(i.length===1)return i[0];let s;for(let a of i){if(!("inputs"in a))continue;if(!r||r.length===0){if(!a.inputs||a.inputs.length===0)return a;continue}if(!a.inputs||a.inputs.length===0||a.inputs.length!==r.length)continue;if(r.every((d,f)=>{let u="inputs"in a&&a.inputs[f];return u?Cm(d,u):!1})){if(s&&"inputs"in s&&s.inputs){let d=ox(a.inputs,s.inputs,r);if(d)throw new hu({abiItem:a,type:d[0]},{abiItem:s,type:d[1]})}s=a}}return s||i[0]}function Cm(e,t){let r=typeof e,n=t.type;switch(n){case"address":return pe(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in t?Object.values(t.components).every((o,i)=>r==="object"&&Cm(Object.values(e)[i],o)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||e instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(e)&&e.every(o=>Cm(o,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function ox(e,t,r){for(let n in e){let o=e[n],i=t[n];if(o.type==="tuple"&&i.type==="tuple"&&"components"in o&&"components"in i)return ox(o.components,i.components,r[n]);let s=[o.type,i.type];if(s.includes("address")&&s.includes("bytes20")?!0:s.includes("address")&&s.includes("string")?pe(r[n],{strict:!1}):s.includes("address")&&s.includes("bytes")?pe(r[n],{strict:!1}):!1)return s}}var As=C(()=>{yt();vn();Zt();ku();Es()});function Bu(e){let{abi:t,args:r,functionName:n,data:o}=e,i=t[0];if(n){let a=Qr({abi:t,args:r,name:n});if(!a)throw new Er(n,{docsPath:Um});i=a}if(i.type!=="function")throw new Er(void 0,{docsPath:Um});if(!i.outputs)throw new gs(i.name,{docsPath:Um});let s=Tn(i.outputs,o);if(s&&s.length>1)return s;if(s&&s.length===1)return s[0]}var Um,Nm=C(()=>{yt();Uc();As();Um="/docs/contract/decodeFunctionResult"});function Nc(e){let{abi:t,args:r,bytecode:n}=e;if(!r||r.length===0)return n;let o=t.find(s=>"type"in s&&s.type==="constructor");if(!o)throw new au({docsPath:Fm});if(!("inputs"in o))throw new kc({docsPath:Fm});if(!o.inputs||o.inputs.length===0)throw new kc({docsPath:Fm});let i=Xr(o.inputs,r);return Le([n,i])}var Fm,Mm=C(()=>{yt();or();xi();Fm="/docs/contract/encodeDeployData"});function Hm(e){let{abi:t,errorName:r,args:n}=e,o=t[0];if(r){let c=Qr({abi:t,args:n,name:r});if(!c)throw new Bc(r,{docsPath:zm});o=c}if(o.type!=="error")throw new Bc(void 0,{docsPath:zm});let i=dt(o),s=Jr(i),a="0x";if(n&&n.length>0){if(!o.inputs)throw new uu(o.name,{docsPath:zm});a=Xr(o.inputs,n)}return Le([s,a])}var zm,ix=C(()=>{yt();or();Es();xi();vo();As();zm="/docs/contract/encodeErrorResult"});function ax(e){let{abi:t,args:r,functionName:n}=e,o=t[0];if(n){let i=Qr({abi:t,args:r,name:n});if(!i)throw new Er(n,{docsPath:sx});o=i}if(o.type!=="function")throw new Er(void 0,{docsPath:sx});return{abi:[o],functionName:Jr(dt(o))}}var sx,cx=C(()=>{yt();Es();vo();As();sx="/docs/contract/encodeFunctionData"});function Yt(e){let{args:t}=e,{abi:r,functionName:n}=e.abi.length===1&&e.functionName?.startsWith("0x")?e:ax(e),o=r[0],i=n,s="inputs"in o&&o.inputs?Xr(o.inputs,t??[]):void 0;return Le([i,s??"0x"])}var vi=C(()=>{or();xi();cx()});function dx(e){let{abi:t,functionName:r,result:n}=e,o=t[0];if(r){let s=Qr({abi:t,name:r});if(!s)throw new Er(r,{docsPath:$m});o=s}if(o.type!=="function")throw new Er(void 0,{docsPath:$m});if(!o.outputs)throw new gs(o.name,{docsPath:$m});let i=(()=>{if(o.outputs.length===0)return[];if(o.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new ws(n)})();return Xr(o.outputs,i)}var $m,fx=C(()=>{yt();xi();As();$m="/docs/contract/encodeFunctionResult"});var qe,Ar=C(()=>{qe=(e,t,r)=>JSON.stringify(e,(n,o)=>{let i=typeof o=="bigint"?o.toString():o;return typeof t=="function"?t(n,i):i},r)});function Lm({abiItem:e,args:t,includeFunctionName:r=!0,includeName:n=!1}){if("name"in e&&"inputs"in e&&e.inputs)return`${r?e.name:""}(${e.inputs.map((o,i)=>`${n&&o.name?`${o.name}: `:""}${typeof t[i]=="object"?qe(t[i]):t[i]}`).join(", ")})`}var ux=C(()=>{Ar()});function Ht(e,t){if(!pe(e,{strict:!1}))throw new Ce({address:e});if(!pe(t,{strict:!1}))throw new Ce({address:t});return e.toLowerCase()===t.toLowerCase()}var Si=C(()=>{Vr();Zt()});function Pu(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,blockTimestamp:e.blockTimestamp?BigInt(e.blockTimestamp):e.blockTimestamp===null?null:void 0,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}var Dm=C(()=>{});function Ru(e){let{abi:t,args:r,logs:n,strict:o=!0}=e,i=(()=>{if(e.eventName)return Array.isArray(e.eventName)?e.eventName:[e.eventName]})(),s=t.filter(a=>a.type==="event").map(a=>({abi:a,selector:_s(a)}));return n.map(a=>{let c=typeof a.blockNumber=="string"?Pu(a):a,d=s.filter(l=>c.topics[0]===l.selector);if(d.length===0)return null;let f,u;for(let l of d)try{f=Om({...c,abi:[l.abi],strict:!0}),u=l;break}catch{}if(!f&&!o){u=d[0];try{f=Om({data:c.data,topics:c.topics,abi:[u.abi],strict:!1})}catch{let l=u.abi.inputs?.some(p=>!("name"in p&&p.name));return{...c,args:l?[]:{},eventName:u.abi.name}}}return!f||!u||i&&!i.includes(f.eventName)||!YE({args:f.args,inputs:u.abi.inputs,matchArgs:r})?null:{...f,...c}}).filter(Boolean)}function YE(e){let{args:t,inputs:r,matchArgs:n}=e;if(!n)return!0;if(!t)return!1;function o(i,s,a){try{return i.type==="address"?Ht(s,a):i.type==="string"?Sr(Ac(s))===a:i.type==="bytes"?Sr(go(s))===a:s===a}catch{return!1}}return Array.isArray(t)&&Array.isArray(n)?n.every((i,s)=>{if(i==null)return!0;let a=r[s];return a?(Array.isArray(i)?i:[i]).some(d=>o(a,d,t[s])):!1}):typeof t=="object"&&!Array.isArray(t)&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).every(([i,s])=>{if(s==null)return!0;let a=r.find(d=>d.name===i);return a?(Array.isArray(s)?s:[s]).some(d=>o(a,d,t[i])):!1}):!1}var qm=C(()=>{Si();rr();Dm();ms();ku();tx()});function Tr(e,t="hex"){let r=lx(e),n=vs(new Uint8Array(r.length));return r.encode(n),t==="hex"?Me(n.bytes):n.bytes}function lx(e){return Array.isArray(e)?XE(e.map(t=>lx(t))):JE(e)}function XE(e){let t=e.reduce((o,i)=>o+i.length,0),r=px(t);return{length:t<=55?1+t:1+r+t,encode(o){t<=55?o.pushByte(192+t):(o.pushByte(247+r),r===1?o.pushUint8(t):r===2?o.pushUint16(t):r===3?o.pushUint24(t):o.pushUint32(t));for(let{encode:i}of e)i(o)}}}function JE(e){let t=typeof e=="string"?Rt(e):e,r=px(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(o){t.length===1&&t[0]<128?o.pushBytes(t):t.length<=55?(o.pushByte(128+t.length),o.pushBytes(t)):(o.pushByte(183+r),r===1?o.pushUint8(t.length):r===2?o.pushUint16(t.length):r===3?o.pushUint24(t.length):o.pushUint32(t.length),o.pushBytes(t))}}}function px(e){if(e<2**8)return 1;if(e<2**16)return 2;if(e<2**24)return 3;if(e<2**32)return 4;throw new L("Length is too large.")}var Ou=C(()=>{le();vu();rr();xe()});function mx(e){let{chainId:t,nonce:r,to:n}=e,o=e.contractAddress??e.address,i=Sr(Le(["0x05",Tr([t?V(t):"0x",o,r?V(r):"0x"])]));return n==="bytes"?Rt(i):i}var hx=C(()=>{or();rr();xe();Ou();ms()});function QE(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(r>>o&i),a=Number(r&i),c=n?4:0,d=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+d,a,n)}function yx(e,t,r){return e&t^~e&r}function bx(e,t,r){return e&t^e&r^t&r}var Cu,In,gx=C(()=>{xo();Cu=class extends wo{constructor(t,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=nu(this.buffer)}update(t){_n(this),t=gi(t),Wr(t);let{view:r,buffer:n,blockLen:o}=this,i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=nu(t);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){_n(this),ru(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;r[s++]=128,Zr(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(n,0),s=0);for(let u=s;u<o;u++)r[u]=0;QE(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=nu(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=c/4,f=this.get();if(d>f.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<d;u++)a.setUint32(4*u,f[u],i)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:i,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=i,t.length=o,t.pos=a,o%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}},In=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])});var e3,_o,Uu,Ei,jm=C(()=>{gx();xo();e3=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),_o=new Uint32Array(64),Uu=class extends Cu{constructor(t=32){super(64,t,8,!1),this.A=In[0]|0,this.B=In[1]|0,this.C=In[2]|0,this.D=In[3]|0,this.E=In[4]|0,this.F=In[5]|0,this.G=In[6]|0,this.H=In[7]|0}get(){let{A:t,B:r,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[t,r,n,o,i,s,a,c]}set(t,r,n,o,i,s,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,r){for(let u=0;u<16;u++,r+=4)_o[u]=t.getUint32(r,!1);for(let u=16;u<64;u++){let l=_o[u-15],p=_o[u-2],m=vr(l,7)^vr(l,18)^l>>>3,h=vr(p,17)^vr(p,19)^p>>>10;_o[u]=h+_o[u-7]+m+_o[u-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:d,H:f}=this;for(let u=0;u<64;u++){let l=vr(a,6)^vr(a,11)^vr(a,25),p=f+l+yx(a,c,d)+e3[u]+_o[u]|0,h=(vr(n,2)^vr(n,13)^vr(n,22))+bx(n,o,i)|0;f=d,d=c,c=a,a=s+p|0,s=i,i=o,o=n,n=p+h|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,d=d+this.G|0,f=f+this.H|0,this.set(n,o,i,s,a,c,d,f)}roundClean(){Zr(_o)}destroy(){this.set(0,0,0,0,0,0,0,0),Zr(this.buffer)}},Ei=ou(()=>new Uu)});var Nu,Gm,wx=C(()=>{xo();Nu=class extends wo{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,_1(t);let n=gi(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,i=new Uint8Array(o);i.set(n.length>o?t.create().update(n).digest():n);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=t.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),Zr(i)}update(t){return _n(this),this.iHash.update(t),this}digestInto(t){_n(this),Wr(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Gm=(e,t,r)=>new Nu(e,t).update(r).digest();Gm.create=(e,t)=>new Nu(e,t)});function Ts(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Bn(e){if(!Ts(e))throw new Error("Uint8Array expected")}function Is(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function Fc(e){let t=e.toString(16);return t.length&1?"0"+t:t}function Sx(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?Zm:BigInt("0x"+e)}function ks(e){if(Bn(e),Ex)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=t3[e[r]];return t}function xx(e){if(e>=kn._0&&e<=kn._9)return e-kn._0;if(e>=kn.A&&e<=kn.F)return e-(kn.A-10);if(e>=kn.a&&e<=kn.f)return e-(kn.a-10)}function Mc(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(Ex)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,i=0;o<r;o++,i+=2){let s=xx(e.charCodeAt(i)),a=xx(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function $t(e){return Sx(ks(e))}function Ym(e){return Bn(e),Sx(ks(Uint8Array.from(e).reverse()))}function en(e,t){return Mc(e.toString(16).padStart(t*2,"0"))}function Xm(e,t){return en(e,t).reverse()}function Je(e,t,r){let n;if(typeof t=="string")try{n=Mc(t)}catch(i){throw new Error(e+" must be hex string or Uint8Array, cause: "+i)}else if(Ts(t))n=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");let o=n.length;if(typeof r=="number"&&o!==r)throw new Error(e+" of length "+r+" expected, got "+o);return n}function Ot(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];Bn(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let i=e[n];r.set(i,o),o+=i.length}return r}function Fu(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function _i(e,t,r){return Vm(e)&&Vm(t)&&Vm(r)&&t<=e&&e<r}function Pn(e,t,r,n){if(!_i(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function _x(e){let t;for(t=0;e>Zm;e>>=Wm,t+=1);return t}function Ax(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=Km(e),o=Km(e),i=0,s=()=>{n.fill(1),o.fill(0),i=0},a=(...u)=>r(o,n,...u),c=(u=Km(0))=>{o=a(vx([0]),u),n=a(),u.length!==0&&(o=a(vx([1]),u),n=a())},d=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let u=0,l=[];for(;u<t;){n=a();let p=n.slice();l.push(p),u+=n.length}return Ot(...l)};return(u,l)=>{s(),c(u);let p;for(;!(p=l(d()));)c();return s(),p}}function Rn(e,t,r={}){let n=(o,i,s)=>{let a=r3[i];if(typeof a!="function")throw new Error("invalid validator function");let c=e[o];if(!(s&&c===void 0)&&!a(c,e))throw new Error("param "+String(o)+" is invalid. Expected "+i+", got "+c)};for(let[o,i]of Object.entries(t))n(o,i,!1);for(let[o,i]of Object.entries(r))n(o,i,!0);return e}function Jm(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let i=e(r,...n);return t.set(r,i),i}}var Zm,Wm,Ex,t3,kn,Vm,Ai,Km,vx,r3,Bs=C(()=>{Zm=BigInt(0),Wm=BigInt(1);Ex=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",t3=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));kn={_0:48,_9:57,A:65,F:70,a:97,f:102};Vm=e=>typeof e=="bigint"&&Zm<=e;Ai=e=>(Wm<<BigInt(e))-Wm,Km=e=>new Uint8Array(e),vx=e=>Uint8Array.from(e);r3={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||Ts(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)}});function Ve(e,t){let r=e%t;return r>=Ct?r:t+r}function Xt(e,t,r){let n=e;for(;t-- >Ct;)n*=n,n%=r;return n}function Mu(e,t){if(e===Ct)throw new Error("invert: expected non-zero number");if(t<=Ct)throw new Error("invert: expected positive modulus, got "+t);let r=Ve(e,t),n=t,o=Ct,i=bt,s=bt,a=Ct;for(;r!==Ct;){let d=n/r,f=n%r,u=o-s*d,l=i-a*d;n=r,r=f,o=s,i=a,s=u,a=l}if(n!==bt)throw new Error("invert: does not exist");return Ve(o,t)}function Px(e,t){let r=(e.ORDER+bt)/Ix,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function o3(e,t){let r=(e.ORDER-kx)/Bx,n=e.mul(t,Ti),o=e.pow(n,r),i=e.mul(t,o),s=e.mul(e.mul(i,Ti),o),a=e.mul(i,e.sub(s,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function i3(e){if(e<BigInt(3))throw new Error("sqrt is not defined for small field");let t=e-bt,r=0;for(;t%Ti===Ct;)t/=Ti,r++;let n=Ti,o=zc(e);for(;Tx(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Px;let i=o.pow(n,t),s=(t+bt)/Ti;return function(c,d){if(c.is0(d))return d;if(Tx(c,d)!==1)throw new Error("Cannot find square root");let f=r,u=c.mul(c.ONE,i),l=c.pow(d,t),p=c.pow(d,s);for(;!c.eql(l,c.ONE);){if(c.is0(l))return c.ZERO;let m=1,h=c.sqr(l);for(;!c.eql(h,c.ONE);)if(m++,h=c.sqr(h),m===f)throw new Error("Cannot find square root");let y=bt<<BigInt(f-m-1),b=c.pow(u,y);f=m,u=c.sqr(b),l=c.mul(l,u),p=c.mul(p,b)}return p}}function s3(e){return e%Ix===n3?Px:e%Bx===kx?o3:i3(e)}function zu(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=a3.reduce((n,o)=>(n[o]="function",n),t);return Rn(e,r)}function c3(e,t,r){if(r<Ct)throw new Error("invalid exponent, negatives unsupported");if(r===Ct)return e.ONE;if(r===bt)return t;let n=e.ONE,o=t;for(;r>Ct;)r&bt&&(n=e.mul(n,o)),o=e.sqr(o),r>>=bt;return n}function Ps(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((s,a,c)=>e.is0(a)?s:(n[c]=s,e.mul(s,a)),e.ONE),i=e.inv(o);return t.reduceRight((s,a,c)=>e.is0(a)?s:(n[c]=e.mul(s,n[c]),e.mul(s,a)),i),n}function Tx(e,t){let r=(e.ORDER-bt)/Ti,n=e.pow(t,r),o=e.eql(n,e.ONE),i=e.eql(n,e.ZERO),s=e.eql(n,e.neg(e.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function Qm(e,t){t!==void 0&&bi(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function zc(e,t,r=!1,n={}){if(e<=Ct)throw new Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:o,nByteLength:i}=Qm(e,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let s,a=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:i,MASK:Ai(o),ZERO:Ct,ONE:bt,create:c=>Ve(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ct<=c&&c<e},is0:c=>c===Ct,isOdd:c=>(c&bt)===bt,neg:c=>Ve(-c,e),eql:(c,d)=>c===d,sqr:c=>Ve(c*c,e),add:(c,d)=>Ve(c+d,e),sub:(c,d)=>Ve(c-d,e),mul:(c,d)=>Ve(c*d,e),pow:(c,d)=>c3(a,c,d),div:(c,d)=>Ve(c*Mu(d,e),e),sqrN:c=>c*c,addN:(c,d)=>c+d,subN:(c,d)=>c-d,mulN:(c,d)=>c*d,inv:c=>Mu(c,e),sqrt:n.sqrt||(c=>(s||(s=s3(e)),s(a,c))),toBytes:c=>r?Xm(c,i):en(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return r?Ym(c):$t(c)},invertBatch:c=>Ps(a,c),cmov:(c,d,f)=>f?d:c});return Object.freeze(a)}function Rx(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function eh(e){let t=Rx(e);return t+Math.ceil(t/2)}function Ox(e,t,r=!1){let n=e.length,o=Rx(t),i=eh(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=r?Ym(e):$t(e),a=Ve(s,t-bt)+bt;return r?Xm(a,o):en(a,o)}var Ct,bt,Ti,n3,Ix,kx,Bx,a3,Hc=C(()=>{xo();Bs();Ct=BigInt(0),bt=BigInt(1),Ti=BigInt(2),n3=BigInt(3),Ix=BigInt(4),kx=BigInt(5),Bx=BigInt(8);a3=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function th(e,t){let r=t.negate();return e?r:t}function Nx(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function rh(e,t){Nx(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,i=Ai(e),s=BigInt(e);return{windows:r,windowSize:n,mask:i,maxNumber:o,shiftBy:s}}function Ux(e,t,r){let{windowSize:n,mask:o,maxNumber:i,shiftBy:s}=r,a=Number(e&o),c=e>>s;a>n&&(a-=i,c+=ih);let d=t*n,f=d+Math.abs(a)-1,u=a===0,l=a<0,p=t%2!==0;return{nextN:c,offset:f,isZero:u,isNeg:l,isNegF:p,offsetF:d}}function d3(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function f3(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}function oh(e){return Fx.get(e)||1}function Mx(e,t){return{constTimeNegate:th,hasPrecomputes(r){return oh(r)!==1},unsafeLadder(r,n,o=e.ZERO){let i=r;for(;n>Cx;)n&ih&&(o=o.add(i)),i=i.double(),n>>=ih;return o},precomputeWindow(r,n){let{windows:o,windowSize:i}=rh(n,t),s=[],a=r,c=a;for(let d=0;d<o;d++){c=a,s.push(c);for(let f=1;f<i;f++)c=c.add(a),s.push(c);a=c.double()}return s},wNAF(r,n,o){let i=e.ZERO,s=e.BASE,a=rh(r,t);for(let c=0;c<a.windows;c++){let{nextN:d,offset:f,isZero:u,isNeg:l,isNegF:p,offsetF:m}=Ux(o,c,a);o=d,u?s=s.add(th(p,n[m])):i=i.add(th(l,n[f]))}return{p:i,f:s}},wNAFUnsafe(r,n,o,i=e.ZERO){let s=rh(r,t);for(let a=0;a<s.windows&&o!==Cx;a++){let{nextN:c,offset:d,isZero:f,isNeg:u}=Ux(o,a,s);if(o=c,!f){let l=n[d];i=i.add(u?l.negate():l)}}return i},getPrecomputes(r,n,o){let i=nh.get(n);return i||(i=this.precomputeWindow(n,r),r!==1&&nh.set(n,o(i))),i},wNAFCached(r,n,o){let i=oh(r);return this.wNAF(i,this.getPrecomputes(i,r,o),n)},wNAFCachedUnsafe(r,n,o,i){let s=oh(r);return s===1?this.unsafeLadder(r,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,r,o),n,i)},setWindowSize(r,n){Nx(n,t),Fx.set(r,n),nh.delete(r)}}}function zx(e,t,r,n){d3(r,e),f3(n,t);let o=r.length,i=n.length;if(o!==i)throw new Error("arrays of points and scalars must have equal length");let s=e.ZERO,a=_x(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let d=Ai(c),f=new Array(Number(d)+1).fill(s),u=Math.floor((t.BITS-1)/c)*c,l=s;for(let p=u;p>=0;p-=c){f.fill(s);for(let h=0;h<i;h++){let y=n[h],b=Number(y>>BigInt(p)&d);f[b]=f[b].add(r[h])}let m=s;for(let h=f.length-1,y=s;h>0;h--)y=y.add(f[h]),m=m.add(y);if(l=l.add(m),p!==0)for(let h=0;h<c;h++)l=l.double()}return l}function sh(e){return zu(e.Fp),Rn(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Qm(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}var Cx,ih,nh,Fx,Hx=C(()=>{Hc();Bs();Cx=BigInt(0),ih=BigInt(1);nh=new WeakMap,Fx=new WeakMap});function $x(e){e.lowS!==void 0&&Is("lowS",e.lowS),e.prehash!==void 0&&Is("prehash",e.prehash)}function u3(e){let t=sh(e);Rn(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:r,Fp:n,a:o}=t;if(r){if(!n.eql(o,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}function ah(e,t){return ks(en(e,t))}function l3(e){let t=u3(e),{Fp:r}=t,n=zc(t.n,t.nBitLength),o=t.toBytes||((g,w,v)=>{let E=w.toAffine();return Ot(Uint8Array.from([4]),r.toBytes(E.x),r.toBytes(E.y))}),i=t.fromBytes||(g=>{let w=g.subarray(1),v=r.fromBytes(w.subarray(0,r.BYTES)),E=r.fromBytes(w.subarray(r.BYTES,2*r.BYTES));return{x:v,y:E}});function s(g){let{a:w,b:v}=t,E=r.sqr(g),B=r.mul(E,g);return r.add(r.add(B,r.mul(g,w)),v)}function a(g,w){let v=r.sqr(w),E=s(g);return r.eql(v,E)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let c=r.mul(r.pow(t.a,$c),dh),d=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,d)))throw new Error("bad curve params: a or b");function f(g){return _i(g,Se,t.n)}function u(g){let{allowedPrivateKeyLengths:w,nByteLength:v,wrapPrivateKey:E,n:B}=t;if(w&&typeof g!="bigint"){if(Ts(g)&&(g=ks(g)),typeof g!="string"||!w.includes(g.length))throw new Error("invalid private key");g=g.padStart(v*2,"0")}let N;try{N=typeof g=="bigint"?g:$t(Je("private key",g,v))}catch{throw new Error("invalid private key, expected hex or "+v+" bytes, got "+typeof g)}return E&&(N=Ve(N,B)),Pn("private key",N,Se,B),N}function l(g){if(!(g instanceof h))throw new Error("ProjectivePoint expected")}let p=Jm((g,w)=>{let{px:v,py:E,pz:B}=g;if(r.eql(B,r.ONE))return{x:v,y:E};let N=g.is0();w==null&&(w=N?r.ONE:r.inv(B));let U=r.mul(v,w),R=r.mul(E,w),T=r.mul(B,w);if(N)return{x:r.ZERO,y:r.ZERO};if(!r.eql(T,r.ONE))throw new Error("invZ was invalid");return{x:U,y:R}}),m=Jm(g=>{if(g.is0()){if(t.allowInfinityPoint&&!r.is0(g.py))return;throw new Error("bad point: ZERO")}let{x:w,y:v}=g.toAffine();if(!r.isValid(w)||!r.isValid(v))throw new Error("bad point: x or y not FE");if(!a(w,v))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class h{constructor(w,v,E){if(w==null||!r.isValid(w))throw new Error("x required");if(v==null||!r.isValid(v)||r.is0(v))throw new Error("y required");if(E==null||!r.isValid(E))throw new Error("z required");this.px=w,this.py=v,this.pz=E,Object.freeze(this)}static fromAffine(w){let{x:v,y:E}=w||{};if(!w||!r.isValid(v)||!r.isValid(E))throw new Error("invalid affine point");if(w instanceof h)throw new Error("projective point not allowed");let B=N=>r.eql(N,r.ZERO);return B(v)&&B(E)?h.ZERO:new h(v,E,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(w){let v=Ps(r,w.map(E=>E.pz));return w.map((E,B)=>E.toAffine(v[B])).map(h.fromAffine)}static fromHex(w){let v=h.fromAffine(i(Je("pointHex",w)));return v.assertValidity(),v}static fromPrivateKey(w){return h.BASE.multiply(u(w))}static msm(w,v){return zx(h,n,w,v)}_setWindowSize(w){x.setWindowSize(this,w)}assertValidity(){m(this)}hasEvenY(){let{y:w}=this.toAffine();if(r.isOdd)return!r.isOdd(w);throw new Error("Field doesn't support isOdd")}equals(w){l(w);let{px:v,py:E,pz:B}=this,{px:N,py:U,pz:R}=w,T=r.eql(r.mul(v,R),r.mul(N,B)),O=r.eql(r.mul(E,R),r.mul(U,B));return T&&O}negate(){return new h(this.px,r.neg(this.py),this.pz)}double(){let{a:w,b:v}=t,E=r.mul(v,$c),{px:B,py:N,pz:U}=this,R=r.ZERO,T=r.ZERO,O=r.ZERO,z=r.mul(B,B),P=r.mul(N,N),_=r.mul(U,U),I=r.mul(B,N);return I=r.add(I,I),O=r.mul(B,U),O=r.add(O,O),R=r.mul(w,O),T=r.mul(E,_),T=r.add(R,T),R=r.sub(P,T),T=r.add(P,T),T=r.mul(R,T),R=r.mul(I,R),O=r.mul(E,O),_=r.mul(w,_),I=r.sub(z,_),I=r.mul(w,I),I=r.add(I,O),O=r.add(z,z),z=r.add(O,z),z=r.add(z,_),z=r.mul(z,I),T=r.add(T,z),_=r.mul(N,U),_=r.add(_,_),z=r.mul(_,I),R=r.sub(R,z),O=r.mul(_,P),O=r.add(O,O),O=r.add(O,O),new h(R,T,O)}add(w){l(w);let{px:v,py:E,pz:B}=this,{px:N,py:U,pz:R}=w,T=r.ZERO,O=r.ZERO,z=r.ZERO,P=t.a,_=r.mul(t.b,$c),I=r.mul(v,N),k=r.mul(E,U),M=r.mul(B,R),$=r.add(v,E),F=r.add(N,U);$=r.mul($,F),F=r.add(I,k),$=r.sub($,F),F=r.add(v,B);let A=r.add(N,R);return F=r.mul(F,A),A=r.add(I,M),F=r.sub(F,A),A=r.add(E,B),T=r.add(U,R),A=r.mul(A,T),T=r.add(k,M),A=r.sub(A,T),z=r.mul(P,F),T=r.mul(_,M),z=r.add(T,z),T=r.sub(k,z),z=r.add(k,z),O=r.mul(T,z),k=r.add(I,I),k=r.add(k,I),M=r.mul(P,M),F=r.mul(_,F),k=r.add(k,M),M=r.sub(I,M),M=r.mul(P,M),F=r.add(F,M),I=r.mul(k,F),O=r.add(O,I),I=r.mul(A,F),T=r.mul($,T),T=r.sub(T,I),I=r.mul($,k),z=r.mul(A,z),z=r.add(z,I),new h(T,O,z)}subtract(w){return this.add(w.negate())}is0(){return this.equals(h.ZERO)}wNAF(w){return x.wNAFCached(this,w,h.normalizeZ)}multiplyUnsafe(w){let{endo:v,n:E}=t;Pn("scalar",w,Ir,E);let B=h.ZERO;if(w===Ir)return B;if(this.is0()||w===Se)return this;if(!v||x.hasPrecomputes(this))return x.wNAFCachedUnsafe(this,w,h.normalizeZ);let{k1neg:N,k1:U,k2neg:R,k2:T}=v.splitScalar(w),O=B,z=B,P=this;for(;U>Ir||T>Ir;)U&Se&&(O=O.add(P)),T&Se&&(z=z.add(P)),P=P.double(),U>>=Se,T>>=Se;return N&&(O=O.negate()),R&&(z=z.negate()),z=new h(r.mul(z.px,v.beta),z.py,z.pz),O.add(z)}multiply(w){let{endo:v,n:E}=t;Pn("scalar",w,Se,E);let B,N;if(v){let{k1neg:U,k1:R,k2neg:T,k2:O}=v.splitScalar(w),{p:z,f:P}=this.wNAF(R),{p:_,f:I}=this.wNAF(O);z=x.constTimeNegate(U,z),_=x.constTimeNegate(T,_),_=new h(r.mul(_.px,v.beta),_.py,_.pz),B=z.add(_),N=P.add(I)}else{let{p:U,f:R}=this.wNAF(w);B=U,N=R}return h.normalizeZ([B,N])[0]}multiplyAndAddUnsafe(w,v,E){let B=h.BASE,N=(R,T)=>T===Ir||T===Se||!R.equals(B)?R.multiplyUnsafe(T):R.multiply(T),U=N(this,v).add(N(w,E));return U.is0()?void 0:U}toAffine(w){return p(this,w)}isTorsionFree(){let{h:w,isTorsionFree:v}=t;if(w===Se)return!0;if(v)return v(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:w,clearCofactor:v}=t;return w===Se?this:v?v(h,this):this.multiplyUnsafe(t.h)}toRawBytes(w=!0){return Is("isCompressed",w),this.assertValidity(),o(h,this,w)}toHex(w=!0){return Is("isCompressed",w),ks(this.toRawBytes(w))}}h.BASE=new h(t.Gx,t.Gy,r.ONE),h.ZERO=new h(r.ZERO,r.ONE,r.ZERO);let{endo:y,nBitLength:b}=t,x=Mx(h,y?Math.ceil(b/2):b);return{CURVE:t,ProjectivePoint:h,normPrivateKeyToScalar:u,weierstrassEquation:s,isWithinCurveOrder:f}}function p3(e){let t=sh(e);return Rn(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Lx(e){let t=p3(e),{Fp:r,n,nByteLength:o,nBitLength:i}=t,s=r.BYTES+1,a=2*r.BYTES+1;function c(_){return Ve(_,n)}function d(_){return Mu(_,n)}let{ProjectivePoint:f,normPrivateKeyToScalar:u,weierstrassEquation:l,isWithinCurveOrder:p}=l3({...t,toBytes(_,I,k){let M=I.toAffine(),$=r.toBytes(M.x),F=Ot;return Is("isCompressed",k),k?F(Uint8Array.from([I.hasEvenY()?2:3]),$):F(Uint8Array.from([4]),$,r.toBytes(M.y))},fromBytes(_){let I=_.length,k=_[0],M=_.subarray(1);if(I===s&&(k===2||k===3)){let $=$t(M);if(!_i($,Se,r.ORDER))throw new Error("Point is not on curve");let F=l($),A;try{A=r.sqrt(F)}catch(q){let j=q instanceof Error?": "+q.message:"";throw new Error("Point is not on curve"+j)}let H=(A&Se)===Se;return(k&1)===1!==H&&(A=r.neg(A)),{x:$,y:A}}else if(I===a&&k===4){let $=r.fromBytes(M.subarray(0,r.BYTES)),F=r.fromBytes(M.subarray(r.BYTES,2*r.BYTES));return{x:$,y:F}}else{let $=s,F=a;throw new Error("invalid Point, expected length of "+$+", or uncompressed "+F+", got "+I)}}});function m(_){let I=n>>Se;return _>I}function h(_){return m(_)?c(-_):_}let y=(_,I,k)=>$t(_.slice(I,k));class b{constructor(I,k,M){Pn("r",I,Se,n),Pn("s",k,Se,n),this.r=I,this.s=k,M!=null&&(this.recovery=M),Object.freeze(this)}static fromCompact(I){let k=o;return I=Je("compactSignature",I,k*2),new b(y(I,0,k),y(I,k,2*k))}static fromDER(I){let{r:k,s:M}=On.toSig(Je("DER",I));return new b(k,M)}assertValidity(){}addRecoveryBit(I){return new b(this.r,this.s,I)}recoverPublicKey(I){let{r:k,s:M,recovery:$}=this,F=B(Je("msgHash",I));if($==null||![0,1,2,3].includes($))throw new Error("recovery id invalid");let A=$===2||$===3?k+t.n:k;if(A>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let H=($&1)===0?"02":"03",D=f.fromHex(H+ah(A,r.BYTES)),q=d(A),j=c(-F*q),K=c(M*q),W=f.BASE.multiplyAndAddUnsafe(D,j,K);if(!W)throw new Error("point at infinify");return W.assertValidity(),W}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new b(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Mc(this.toDERHex())}toDERHex(){return On.hexFromSig(this)}toCompactRawBytes(){return Mc(this.toCompactHex())}toCompactHex(){let I=o;return ah(this.r,I)+ah(this.s,I)}}let x={isValidPrivateKey(_){try{return u(_),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let _=eh(t.n);return Ox(t.randomBytes(_),t.n)},precompute(_=8,I=f.BASE){return I._setWindowSize(_),I.multiply(BigInt(3)),I}};function g(_,I=!0){return f.fromPrivateKey(_).toRawBytes(I)}function w(_){if(typeof _=="bigint")return!1;if(_ instanceof f)return!0;let k=Je("key",_).length,M=r.BYTES,$=M+1,F=2*M+1;if(!(t.allowedPrivateKeyLengths||o===$))return k===$||k===F}function v(_,I,k=!0){if(w(_)===!0)throw new Error("first arg must be private key");if(w(I)===!1)throw new Error("second arg must be public key");return f.fromHex(I).multiply(u(_)).toRawBytes(k)}let E=t.bits2int||function(_){if(_.length>8192)throw new Error("input is too large");let I=$t(_),k=_.length*8-i;return k>0?I>>BigInt(k):I},B=t.bits2int_modN||function(_){return c(E(_))},N=Ai(i);function U(_){return Pn("num < 2^"+i,_,Ir,N),en(_,o)}function R(_,I,k=T){if(["recovered","canonical"].some(te=>te in k))throw new Error("sign() legacy options not supported");let{hash:M,randomBytes:$}=t,{lowS:F,prehash:A,extraEntropy:H}=k;F==null&&(F=!0),_=Je("msgHash",_),$x(k),A&&(_=Je("prehashed msgHash",M(_)));let D=B(_),q=u(I),j=[U(q),U(D)];if(H!=null&&H!==!1){let te=H===!0?$(r.BYTES):H;j.push(Je("extraEntropy",te))}let K=Ot(...j),W=D;function Z(te){let J=E(te);if(!p(J))return;let de=d(J),ue=f.BASE.multiply(J).toAffine(),me=c(ue.x);if(me===Ir)return;let Ne=c(de*c(W+me*q));if(Ne===Ir)return;let fe=(ue.x===me?0:2)|Number(ue.y&Se),we=Ne;return F&&m(Ne)&&(we=h(Ne),fe^=1),new b(me,we,fe)}return{seed:K,k2sig:Z}}let T={lowS:t.lowS,prehash:!1},O={lowS:t.lowS,prehash:!1};function z(_,I,k=T){let{seed:M,k2sig:$}=R(_,I,k),F=t;return Ax(F.hash.outputLen,F.nByteLength,F.hmac)(M,$)}f.BASE._setWindowSize(8);function P(_,I,k,M=O){let $=_;I=Je("msgHash",I),k=Je("publicKey",k);let{lowS:F,prehash:A,format:H}=M;if($x(M),"strict"in M)throw new Error("options.strict was renamed to lowS");if(H!==void 0&&H!=="compact"&&H!=="der")throw new Error("format must be compact or der");let D=typeof $=="string"||Ts($),q=!D&&!H&&typeof $=="object"&&$!==null&&typeof $.r=="bigint"&&typeof $.s=="bigint";if(!D&&!q)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let j,K;try{if(q&&(j=new b($.r,$.s)),D){try{H!=="compact"&&(j=b.fromDER($))}catch(fe){if(!(fe instanceof On.Err))throw fe}!j&&H!=="der"&&(j=b.fromCompact($))}K=f.fromHex(k)}catch{return!1}if(!j||F&&j.hasHighS())return!1;A&&(I=t.hash(I));let{r:W,s:Z}=j,te=B(I),J=d(Z),de=c(te*J),ue=c(W*J),me=f.BASE.multiplyAndAddUnsafe(K,de,ue)?.toAffine();return me?c(me.x)===W:!1}return{CURVE:t,getPublicKey:g,getSharedSecret:v,sign:z,verify:P,ProjectivePoint:f,Signature:b,utils:x}}function m3(e,t){let r=e.ORDER,n=Ir;for(let m=r-Se;m%Ao===Ir;m/=Ao)n+=Se;let o=n,i=Ao<<o-Se-Se,s=i*Ao,a=(r-Se)/s,c=(a-Se)/Ao,d=s-Se,f=i,u=e.pow(t,a),l=e.pow(t,(a+Se)/Ao),p=(m,h)=>{let y=u,b=e.pow(h,d),x=e.sqr(b);x=e.mul(x,h);let g=e.mul(m,x);g=e.pow(g,c),g=e.mul(g,b),b=e.mul(g,h),x=e.mul(g,m);let w=e.mul(x,b);g=e.pow(w,f);let v=e.eql(g,e.ONE);b=e.mul(x,l),g=e.mul(w,y),x=e.cmov(b,x,v),w=e.cmov(g,w,v);for(let E=o;E>Se;E--){let B=E-Ao;B=Ao<<B-Se;let N=e.pow(w,B),U=e.eql(N,e.ONE);b=e.mul(x,y),y=e.mul(y,y),N=e.mul(w,y),x=e.cmov(b,x,U),w=e.cmov(N,w,U)}return{isValid:v,value:x}};if(e.ORDER%dh===$c){let m=(e.ORDER-$c)/dh,h=e.sqrt(e.neg(t));p=(y,b)=>{let x=e.sqr(b),g=e.mul(y,b);x=e.mul(x,g);let w=e.pow(x,m);w=e.mul(w,g);let v=e.mul(w,h),E=e.mul(e.sqr(w),b),B=e.eql(E,y),N=e.cmov(v,w,B);return{isValid:B,value:N}}}return p}function Dx(e,t){if(zu(e),!e.isValid(t.A)||!e.isValid(t.B)||!e.isValid(t.Z))throw new Error("mapToCurveSimpleSWU: invalid opts");let r=m3(e,t.Z);if(!e.isOdd)throw new Error("Fp.isOdd is not implemented!");return n=>{let o,i,s,a,c,d,f,u;o=e.sqr(n),o=e.mul(o,t.Z),i=e.sqr(o),i=e.add(i,o),s=e.add(i,e.ONE),s=e.mul(s,t.B),a=e.cmov(t.Z,e.neg(i),!e.eql(i,e.ZERO)),a=e.mul(a,t.A),i=e.sqr(s),d=e.sqr(a),c=e.mul(d,t.A),i=e.add(i,c),i=e.mul(i,s),d=e.mul(d,a),c=e.mul(d,t.B),i=e.add(i,c),f=e.mul(o,s);let{isValid:l,value:p}=r(i,d);u=e.mul(o,n),u=e.mul(u,p),f=e.cmov(f,s,l),u=e.cmov(u,p,l);let m=e.isOdd(n)===e.isOdd(u);u=e.cmov(e.neg(u),u,m);let h=Ps(e,[a],!0)[0];return f=e.mul(f,h),{x:f,y:u}}}var ch,On,Ir,Se,Ao,$c,dh,fh=C(()=>{Hx();Hc();Bs();ch=class extends Error{constructor(t=""){super(t)}},On={Err:ch,_tlv:{encode:(e,t)=>{let{Err:r}=On;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=Fc(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let i=n>127?Fc(o.length/2|128):"";return Fc(e)+i+o+t},decode(e,t){let{Err:r}=On,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let d=t.subarray(n,n+c);if(d.length!==c)throw new r("tlv.decode: length bytes not complete");if(d[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let f of d)s=s<<8|f;if(n+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(e){let{Err:t}=On;if(e<Ir)throw new t("integer: negative integers are not allowed");let r=Fc(e);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=On;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return $t(e)}},toSig(e){let{Err:t,_int:r,_tlv:n}=On,o=Je("signature",e),{v:i,l:s}=n.decode(48,o);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:d,l:f}=n.decode(2,c);if(f.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(d)}},hexFromSig(e){let{_tlv:t,_int:r}=On,n=t.encode(2,r.encode(e.r)),o=t.encode(2,r.encode(e.s)),i=n+o;return t.encode(48,i)}};Ir=BigInt(0),Se=BigInt(1),Ao=BigInt(2),$c=BigInt(3),dh=BigInt(4)});function h3(e){return{hash:e,hmac:(t,...r)=>Gm(e,t,T1(...r)),randomBytes:iu}}function qx(e,t){let r=n=>Lx({...e,...h3(n)});return{...r(t),create:r}}var jx=C(()=>{wx();xo();fh();});function To(e,t){if(Lc(e),Lc(t),e<0||e>=1<<8*t)throw new Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let n=t-1;n>=0;n--)r[n]=e&255,e>>>=8;return new Uint8Array(r)}function b3(e,t){let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e[n]^t[n];return r}function Lc(e){if(!Number.isSafeInteger(e))throw new Error("number expected")}function g3(e,t,r,n){Bn(e),Bn(t),Lc(r),t.length>255&&(t=n(Ot(Fu("H2C-OVERSIZE-DST-"),t)));let{outputLen:o,blockLen:i}=n,s=Math.ceil(r/o);if(r>65535||s>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=Ot(t,To(t.length,1)),c=To(0,i),d=To(r,2),f=new Array(s),u=n(Ot(c,e,d,To(0,1),a));f[0]=n(Ot(u,To(1,1),a));for(let p=1;p<=s;p++){let m=[b3(u,f[p-1]),To(p+1,1),a];f[p]=n(Ot(...m))}return Ot(...f).slice(0,r)}function w3(e,t,r,n,o){if(Bn(e),Bn(t),Lc(r),t.length>255){let i=Math.ceil(2*n/8);t=o.create({dkLen:i}).update(Fu("H2C-OVERSIZE-DST-")).update(t).digest()}if(r>65535||t.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return o.create({dkLen:r}).update(e).update(To(r,2)).update(t).update(To(t.length,1)).digest()}function Gx(e,t,r){Rn(r,{DST:"stringOrUint8Array",p:"bigint",m:"isSafeInteger",k:"isSafeInteger",hash:"hash"});let{p:n,k:o,m:i,hash:s,expand:a,DST:c}=r;Bn(e),Lc(t);let d=typeof c=="string"?Fu(c):c,f=n.toString(2).length,u=Math.ceil((f+o)/8),l=t*i*u,p;if(a==="xmd")p=g3(e,d,l,s);else if(a==="xof")p=w3(e,d,l,o,s);else if(a==="_internal_pass")p=e;else throw new Error('expand must be "xmd" or "xof"');let m=new Array(t);for(let h=0;h<t;h++){let y=new Array(i);for(let b=0;b<i;b++){let x=u*(b+h*i),g=p.subarray(x,x+u);y[b]=Ve(y3(g),n)}m[h]=y}return m}function Vx(e,t){let r=t.map(n=>Array.from(n).reverse());return(n,o)=>{let[i,s,a,c]=r.map(u=>u.reduce((l,p)=>e.add(e.mul(l,n),p))),[d,f]=Ps(e,[s,c],!0);return n=e.mul(i,d),o=e.mul(o,e.mul(a,f)),{x:n,y:o}}}function Kx(e,t,r){if(typeof t!="function")throw new Error("mapToCurve() must be defined");function n(i){return e.fromAffine(t(i))}function o(i){let s=i.clearCofactor();return s.equals(e.ZERO)?e.ZERO:(s.assertValidity(),s)}return{defaults:r,hashToCurve(i,s){let a=Gx(i,2,{...r,DST:r.DST,...s}),c=n(a[0]),d=n(a[1]);return o(c.add(d))},encodeToCurve(i,s){let a=Gx(i,1,{...r,DST:r.encodeDST,...s});return o(n(a[0]))},mapToCurve(i){if(!Array.isArray(i))throw new Error("expected array of bigints");for(let s of i)if(typeof s!="bigint")throw new Error("expected array of bigints");return o(n(i))}}}var y3,Wx=C(()=>{Hc();Bs();y3=$t});var t2={};Iy(t2,{encodeToCurve:()=>I3,hashToCurve:()=>T3,schnorr:()=>E3,secp256k1:()=>Gc,secp256k1_hasher:()=>bh});function Xx(e){let t=jc,r=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),d=e*e*e%t,f=d*d*e%t,u=Xt(f,r,t)*f%t,l=Xt(u,r,t)*f%t,p=Xt(l,$u,t)*d%t,m=Xt(p,o,t)*p%t,h=Xt(m,i,t)*m%t,y=Xt(h,a,t)*h%t,b=Xt(y,c,t)*y%t,x=Xt(b,a,t)*h%t,g=Xt(x,r,t)*f%t,w=Xt(g,s,t)*m%t,v=Xt(w,n,t)*d%t,E=Xt(v,$u,t);if(!Io.eql(Io.sqr(E),e))throw new Error("Cannot find square root");return E}function Lu(e,...t){let r=Yx[e];if(r===void 0){let n=Ei(Uint8Array.from(e,o=>o.charCodeAt(0)));r=Ot(n,n),Yx[e]=r}return Ei(Ot(r,...t))}function ph(e){let t=Gc.utils.normPrivateKeyToScalar(e),r=yh.fromPrivateKey(t);return{scalar:r.hasEvenY()?t:qc(-t),bytes:hh(r)}}function Jx(e){Pn("x",e,Dc,jc);let t=uh(e*e),r=uh(t*e+BigInt(7)),n=Xx(r);n%$u!==mh&&(n=uh(-n));let o=new yh(e,n,Dc);return o.assertValidity(),o}function Qx(...e){return qc(Rs(Lu("BIP0340/challenge",...e)))}function v3(e){return ph(e).bytes}function S3(e,t,r=iu(32)){let n=Je("message",e),{bytes:o,scalar:i}=ph(t),s=Je("auxRand",r,32),a=lh(i^Rs(Lu("BIP0340/aux",s))),c=Lu("BIP0340/nonce",a,o,n),d=qc(Rs(c));if(d===mh)throw new Error("sign failed: k is zero");let{bytes:f,scalar:u}=ph(d),l=Qx(f,o,n),p=new Uint8Array(64);if(p.set(f,0),p.set(lh(qc(u+l*i)),32),!e2(p,n,o))throw new Error("sign: Invalid signature produced");return p}function e2(e,t,r){let n=Je("signature",e,64),o=Je("message",t),i=Je("publicKey",r,32);try{let s=Jx(Rs(i)),a=Rs(n.subarray(0,32));if(!_i(a,Dc,jc))return!1;let c=Rs(n.subarray(32,64));if(!_i(c,Dc,Hu))return!1;let d=Qx(lh(a),hh(s),o),f=x3(s,c,qc(-d));return!(!f||!f.hasEvenY()||f.toAffine().x!==a)}catch{return!1}}var jc,Hu,mh,Dc,$u,Zx,Io,Gc,Yx,hh,lh,uh,qc,yh,x3,Rs,E3,_3,A3,bh,T3,I3,r2=C(()=>{jm();xo();jx();Wx();Hc();Bs();fh();jc=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Hu=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),mh=BigInt(0),Dc=BigInt(1),$u=BigInt(2),Zx=(e,t)=>(e+t/$u)/t;Io=zc(jc,void 0,void 0,{sqrt:Xx}),Gc=qx({a:mh,b:BigInt(7),Fp:Io,n:Hu,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=Hu,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Dc*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,s=BigInt("0x100000000000000000000000000000000"),a=Zx(i*e,t),c=Zx(-n*e,t),d=Ve(e-a*r-c*o,t),f=Ve(-a*n-c*i,t),u=d>s,l=f>s;if(u&&(d=t-d),l&&(f=t-f),d>s||f>s)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:u,k1:d,k2neg:l,k2:f}}}},Ei),Yx={};hh=e=>e.toRawBytes(!0).slice(1),lh=e=>en(e,32),uh=e=>Ve(e,jc),qc=e=>Ve(e,Hu),yh=Gc.ProjectivePoint,x3=(e,t,r)=>yh.BASE.multiplyAndAddUnsafe(e,t,r);Rs=$t;E3={getPublicKey:v3,sign:S3,verify:e2,utils:{randomPrivateKey:Gc.utils.randomPrivateKey,lift_x:Jx,pointToBytes:hh,numberToBytesBE:en,bytesToNumberBE:$t,taggedHash:Lu,mod:Ve}},_3=Vx(Io,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),A3=Dx(Io,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:Io.create(BigInt("-11"))}),bh=Kx(Gc.ProjectivePoint,e=>{let{x:t,y:r}=A3(Io.create(e[0]));return _3(t,r)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:Io.ORDER,m:1,k:128,expand:"xmd",hash:Ei}),T3=bh.hashToCurve,I3=bh.encodeToCurve});async function o2({hash:e,signature:t}){let r=ct(e)?e:ht(e),{secp256k1:n}=await Promise.resolve().then(()=>(r2(),t2));return`0x${(()=>{if(typeof t=="object"&&"r"in t&&"s"in t){let{r:d,s:f,v:u,yParity:l}=t,p=Number(l??u),m=n2(p);return new n.Signature(De(d),De(f)).addRecoveryBit(m)}let s=ct(t)?t:ht(t);if(ge(s)!==65)throw new Error("invalid signature length");let a=Xe(`0x${s.slice(130)}`),c=n2(a);return n.Signature.fromCompact(s.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function n2(e){if(e===0||e===1)return e;if(e===27)return 0;if(e===28)return 1;throw new Error("Invalid yParityOrV value")}var i2=C(()=>{vn();xr();Pt();xe()});async function s2({hash:e,signature:t}){return F1(await o2({hash:e,signature:t}))}var a2=C(()=>{M1();i2()});async function Os(e){let{authorization:t,signature:r}=e;return s2({hash:mx(t),signature:r??t})}var Du=C(()=>{a2();hx()});function Gu(e,t=0){if(!Number.isInteger(t)||t<0)throw new ju({decimals:t});let r=e.toString(),n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(t,"0");let[o,i]=[r.slice(0,r.length-t),r.slice(r.length-t)];return i=i.replace(/(0+)$/,""),`${n?"-":""}${o||"0"}${i?`.${i}`:""}`}function c2(e,t="wei"){return Gu(e,qu.ether-qu[t])}function d2(e,t="wei"){return Gu(e,qu.gwei-qu[t])}function f2(e,t=0){if(!Number.isInteger(t)||t<0)throw new ju({decimals:t});if(!/^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/.test(e))throw new gh({value:e});let[r="",n="0"]=e.split("."),o=r.startsWith("-");if(o&&(r=r.slice(1)),r===""&&(r="0"),n=n.replace(/(0+)$/,""),t===0)n.length>0&&Number.parseInt(n[0],10)>=5&&(r=`${BigInt(r)+1n}`),n="";else if(n.length>t){let i=n.slice(0,t);if(Number.parseInt(n.slice(t,t+1),10)>=5){let a=k3(i);a.length>t?(n=a.slice(1),r=`${BigInt(r)+1n}`):n=a}else n=i}else n=n.padEnd(t,"0");return BigInt(`${o?"-":""}${r}${n}`)}function k3(e){let t=e.split(""),r=t.length-1;for(;r>=0;){let n=Number.parseInt(t[r],10)+1;if(n<10)return t[r]=String(n),t.join("");t[r]="0",r--}return`1${t.join("")}`}var qu,gh,ju,Vc=C(()=>{qu={wei:0,gwei:9,szabo:12,finney:15,ether:18};gh=class extends Error{constructor({value:t}){super(`Value \`${t}\` is not a valid decimal number.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Value.InvalidDecimalNumberError"})}},ju=class extends Error{constructor({decimals:t}){super(`\`decimals\` must be a non-negative integer. Got \`${t}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Value.InvalidDecimalsError"})}}});function Cs(e,t="wei"){return c2(e,t)}var Ku=C(()=>{Vc()});function ot(e,t="wei"){return d2(e,t)}var Us=C(()=>{Vc()});function ki(e){let t=Object.entries(e).map(([n,o])=>o===void 0||o===!1?null:[n,o]).filter(Boolean),r=t.reduce((n,[o])=>Math.max(n,o.length),0);return t.map(([n,o])=>` ${`${n}:`.padEnd(r+1)} ${o}`).join(`
22
- `)}var Ns,Wu,Zu,Yu,Xu,Fs,Ms,Ii,Ju,Lt=C(()=>{Ku();Us();le();Ns=class extends L{constructor({filledNonce:t,requestedNonce:r}){super("The filled transaction nonce does not match the requested nonce.",{metaMessages:[`Requested Nonce: ${r}`,`Filled Nonce: ${t}`],name:"FeePayerNonceMismatchError"})}},Wu=class extends L{constructor({v:t}){super(`Invalid \`v\` value "${t}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}},Zu=class extends L{constructor({transaction:t}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",ki(t),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}},Yu=class extends L{constructor({storageKey:t}){super(`Size for storage key "${t}" is invalid. Expected 32 bytes. Got ${Math.floor((t.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}},Xu=class extends L{constructor(t,{account:r,docsPath:n,chain:o,data:i,gas:s,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:d,nonce:f,to:u,value:l}){let p=ki({chain:o&&`${o?.name} (id: ${o?.id})`,from:r?.address,to:u,value:typeof l<"u"&&`${Cs(l)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:i,gas:s,gasPrice:typeof a<"u"&&`${ot(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${ot(c)} gwei`,maxPriorityFeePerGas:typeof d<"u"&&`${ot(d)} gwei`,nonce:f});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Request Arguments:",p].filter(Boolean),name:"TransactionExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}},Fs=class extends L{constructor({blockHash:t,blockNumber:r,blockTag:n,hash:o,index:i}){let s="Transaction";n&&i!==void 0&&(s=`Transaction at block time "${n}" at index "${i}"`),t&&i!==void 0&&(s=`Transaction at block hash "${t}" at index "${i}"`),r&&i!==void 0&&(s=`Transaction at block number "${r}" at index "${i}"`),o&&(s=`Transaction with hash "${o}"`),super(`${s} could not be found.`,{name:"TransactionNotFoundError"})}},Ms=class extends L{constructor({hash:t}){super(`Transaction receipt with hash "${t}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}},Ii=class extends L{constructor({receipt:t}){super(`Transaction with hash "${t.transactionHash}" reverted.`,{metaMessages:['The receipt marked the transaction as "reverted". This could mean that the function on the contract you are trying to call threw an error.'," ","You can attempt to extract the revert reason by:","- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract","- using the `call` Action with raw `data`"],name:"TransactionReceiptRevertedError"}),Object.defineProperty(this,"receipt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.receipt=t}},Ju=class extends L{constructor({hash:t}){super(`Timed out while waiting for transaction with hash "${t}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}});function zs(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(i=>Rt(i)):e.blobs,o=[];for(let i of n)o.push(Uint8Array.from(t.blobToKzgCommitment(i)));return r==="bytes"?o:o.map(i=>Me(i))}var Qu=C(()=>{rr();xe()});function Hs(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(s=>Rt(s)):e.blobs,o=typeof e.commitments[0]=="string"?e.commitments.map(s=>Rt(s)):e.commitments,i=[];for(let s=0;s<n.length;s++){let a=n[s],c=o[s];i.push(Uint8Array.from(t.computeBlobKzgProof(a,c)))}return r==="bytes"?i:i.map(s=>Me(s))}var el=C(()=>{rr();xe()});var u2,l2=C(()=>{jm();u2=Ei});function p2(e,t){let r=t||"hex",n=u2(ct(e,{strict:!1})?go(e):e);return r==="bytes"?n:ht(n)}var m2=C(()=>{l2();vn();rr();xe()});function h2(e){let{commitment:t,version:r=1}=e,n=e.to??(typeof t=="string"?"hex":"bytes"),o=p2(t,"bytes");return o.set([r],0),n==="bytes"?o:Me(o)}var y2=C(()=>{xe();m2()});function tl(e){let{commitments:t,version:r}=e,n=e.to??(typeof t[0]=="string"?"hex":"bytes"),o=[];for(let i of t)o.push(h2({commitment:i,to:n,version:r}));return o}var wh=C(()=>{y2()});var rl,$s,nl,ol,xh=C(()=>{le();rl=class extends L{constructor({maxSize:t,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${t} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}},$s=class extends L{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}},nl=class extends L{constructor({hash:t,size:r}){super(`Versioned hash "${t}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}},ol=class extends L{constructor({hash:t,version:r}){super(`Versioned hash "${t}" version is invalid.`,{metaMessages:[`Expected: ${1}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}});function b2(e){let t=e.to??(typeof e.data=="string"?"hex":"bytes"),r=typeof e.data=="string"?Rt(e.data):e.data,n=ge(r);if(!n)throw new $s;if(n>761855)throw new rl({maxSize:761855,size:n});let o=[],i=!0,s=0;for(;i;){let a=vs(new Uint8Array(131072)),c=0;for(;c<4096;){let d=r.slice(s,s+31);if(a.pushByte(0),a.pushBytes(d),d.length<31){a.pushByte(128),i=!1;break}c++,s+=31}o.push(a)}return t==="bytes"?o.map(a=>a.bytes):o.map(a=>Me(a.bytes))}var g2=C(()=>{xh();vu();xr();rr();xe()});function il(e){let{data:t,kzg:r,to:n}=e,o=e.blobs??b2({data:t,to:n}),i=e.commitments??zs({blobs:o,kzg:r,to:n}),s=e.proofs??Hs({blobs:o,commitments:i,kzg:r,to:n}),a=[];for(let c=0;c<o.length;c++)a.push({blob:o[c],commitment:i[c],proof:s[c]});return a}var vh=C(()=>{Qu();el();g2()});var J7,Q7,eO,tO,rO,nO,oO,iO,sO,aO,cO,dO,fO,uO,lO,pO,mO,hO,yO,bO,gO,wO,xO,vO,SO,EO,_O,AO,TO,IO,kO,BO,PO,RO,OO,CO,UO,NO,FO,MO,zO,HO,$O,LO,DO,qO,jO,GO,VO,KO,WO,ZO,YO,XO,JO,QO,eC,tC,rC,nC,oC,iC,sC,aC,cC,dC,fC,uC,lC,pC,mC,hC,yC,bC,gC,wC,xC,vC,SC,EC,_C,AC,TC,IC,kC,BC,PC,RC,OC,CC,UC,NC,FC,MC,zC,Ls,Sh=C(()=>{J7=2n**(8n-1n)-1n,Q7=2n**(16n-1n)-1n,eO=2n**(24n-1n)-1n,tO=2n**(32n-1n)-1n,rO=2n**(40n-1n)-1n,nO=2n**(48n-1n)-1n,oO=2n**(56n-1n)-1n,iO=2n**(64n-1n)-1n,sO=2n**(72n-1n)-1n,aO=2n**(80n-1n)-1n,cO=2n**(88n-1n)-1n,dO=2n**(96n-1n)-1n,fO=2n**(104n-1n)-1n,uO=2n**(112n-1n)-1n,lO=2n**(120n-1n)-1n,pO=2n**(128n-1n)-1n,mO=2n**(136n-1n)-1n,hO=2n**(144n-1n)-1n,yO=2n**(152n-1n)-1n,bO=2n**(160n-1n)-1n,gO=2n**(168n-1n)-1n,wO=2n**(176n-1n)-1n,xO=2n**(184n-1n)-1n,vO=2n**(192n-1n)-1n,SO=2n**(200n-1n)-1n,EO=2n**(208n-1n)-1n,_O=2n**(216n-1n)-1n,AO=2n**(224n-1n)-1n,TO=2n**(232n-1n)-1n,IO=2n**(240n-1n)-1n,kO=2n**(248n-1n)-1n,BO=2n**(256n-1n)-1n,PO=-(2n**(8n-1n)),RO=-(2n**(16n-1n)),OO=-(2n**(24n-1n)),CO=-(2n**(32n-1n)),UO=-(2n**(40n-1n)),NO=-(2n**(48n-1n)),FO=-(2n**(56n-1n)),MO=-(2n**(64n-1n)),zO=-(2n**(72n-1n)),HO=-(2n**(80n-1n)),$O=-(2n**(88n-1n)),LO=-(2n**(96n-1n)),DO=-(2n**(104n-1n)),qO=-(2n**(112n-1n)),jO=-(2n**(120n-1n)),GO=-(2n**(128n-1n)),VO=-(2n**(136n-1n)),KO=-(2n**(144n-1n)),WO=-(2n**(152n-1n)),ZO=-(2n**(160n-1n)),YO=-(2n**(168n-1n)),XO=-(2n**(176n-1n)),JO=-(2n**(184n-1n)),QO=-(2n**(192n-1n)),eC=-(2n**(200n-1n)),tC=-(2n**(208n-1n)),rC=-(2n**(216n-1n)),nC=-(2n**(224n-1n)),oC=-(2n**(232n-1n)),iC=-(2n**(240n-1n)),sC=-(2n**(248n-1n)),aC=-(2n**(256n-1n)),cC=2n**8n-1n,dC=2n**16n-1n,fC=2n**24n-1n,uC=2n**32n-1n,lC=2n**40n-1n,pC=2n**48n-1n,mC=2n**56n-1n,hC=2n**64n-1n,yC=2n**72n-1n,bC=2n**80n-1n,gC=2n**88n-1n,wC=2n**96n-1n,xC=2n**104n-1n,vC=2n**112n-1n,SC=2n**120n-1n,EC=2n**128n-1n,_C=2n**136n-1n,AC=2n**144n-1n,TC=2n**152n-1n,IC=2n**160n-1n,kC=2n**168n-1n,BC=2n**176n-1n,PC=2n**184n-1n,RC=2n**192n-1n,OC=2n**200n-1n,CC=2n**208n-1n,UC=2n**216n-1n,NC=2n**224n-1n,FC=2n**232n-1n,MC=2n**240n-1n,zC=2n**248n-1n,Ls=2n**256n-1n});var Bi,sl,al,Kc,Pi,Wc=C(()=>{le();Bi=class extends L{constructor({blockNumber:t,chain:r,contract:n}){super(`Chain "${r.name}" does not support contract "${n.name}".`,{metaMessages:["This could be due to any of the following:",...t&&n.blockCreated&&n.blockCreated>t?[`- The contract "${n.name}" was not deployed until block ${n.blockCreated} (current block ${t}).`]:[`- The chain does not have the contract "${n.name}" configured.`]],name:"ChainDoesNotSupportContract"})}},sl=class extends L{constructor({chain:t,currentChainId:r}){super(`The current chain of the wallet (id: ${r}) does not match the target chain for the transaction (id: ${t.id} \u2013 ${t.name}).`,{metaMessages:[`Current Chain ID: ${r}`,`Expected Chain ID: ${t.id} \u2013 ${t.name}`],name:"ChainMismatchError"})}},al=class extends L{constructor(){super(["No chain was provided to the request.","Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient."].join(`
23
- `),{name:"ChainNotFoundError"})}},Kc=class extends L{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}},Pi=class extends L{constructor({chainId:t}){super(typeof t=="number"?`Chain ID "${t}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}});var Cn,ir,Ds,qs,js,Gs,Vs,Ks,Ws,Zs,tn,rn,Ri=C(()=>{Us();le();Cn=class extends L{constructor({cause:t,message:r}={}){let n=r?.replace("execution reverted: ","")?.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:t,name:"ExecutionRevertedError"})}};Object.defineProperty(Cn,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(Cn,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});ir=class extends L{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${ot(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:t,name:"FeeCapTooHighError"})}};Object.defineProperty(ir,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});Ds=class extends L{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${ot(r)}`:""} gwei) cannot be lower than the block base fee.`,{cause:t,name:"FeeCapTooLowError"})}};Object.defineProperty(Ds,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});qs=class extends L{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}is higher than the next one expected.`,{cause:t,name:"NonceTooHighError"})}};Object.defineProperty(qs,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});js=class extends L{constructor({cause:t,nonce:r}={}){super([`Nonce provided for the transaction ${r?`(${r}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(`
24
- `),{cause:t,name:"NonceTooLowError"})}};Object.defineProperty(js,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});Gs=class extends L{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}exceeds the maximum allowed nonce.`,{cause:t,name:"NonceMaxValueError"})}};Object.defineProperty(Gs,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});Vs=class extends L{constructor({cause:t}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
25
- `),{cause:t,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}};Object.defineProperty(Vs,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});Ks=class extends L{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:t,name:"IntrinsicGasTooHighError"})}};Object.defineProperty(Ks,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});Ws=class extends L{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction is too low.`,{cause:t,name:"IntrinsicGasTooLowError"})}};Object.defineProperty(Ws,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});Zs=class extends L{constructor({cause:t}){super("The transaction type is not supported for this chain.",{cause:t,name:"TransactionTypeNotSupportedError"})}};Object.defineProperty(Zs,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});tn=class extends L{constructor({cause:t,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${r?` = ${ot(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${ot(n)} gwei`:""}).`].join(`
26
- `),{cause:t,name:"TipAboveFeeCapError"})}};Object.defineProperty(tn,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});rn=class extends L{constructor({cause:t}){super(`An error occurred while executing: ${t?.shortMessage}`,{cause:t,name:"UnknownNodeError"})}}});function w2(e){let{authorizationList:t}=e;if(t)for(let r of t){let{chainId:n}=r,o=r.address;if(!pe(o))throw new Ce({address:o});if(n<0)throw new Pi({chainId:n})}cl(e)}function x2(e){let{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new $s;for(let r of t){let n=ge(r),o=Xe(nr(r,0,1));if(n!==32)throw new nl({hash:r,size:n});if(o!==1)throw new ol({hash:r,version:o})}}cl(e)}function cl(e){let{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:o}=e;if(t<=0)throw new Pi({chainId:t});if(o&&!pe(o))throw new Ce({address:o});if(n&&n>Ls)throw new ir({maxFeePerGas:n});if(r&&n&&r>n)throw new tn({maxFeePerGas:n,maxPriorityFeePerGas:r})}function v2(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:i}=e;if(t<=0)throw new Pi({chainId:t});if(i&&!pe(i))throw new Ce({address:i});if(r||o)throw new L("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>Ls)throw new ir({maxFeePerGas:n})}function S2(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:i}=e;if(i&&!pe(i))throw new Ce({address:i});if(typeof t<"u"&&t<=0)throw new Pi({chainId:t});if(r||o)throw new L("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>Ls)throw new ir({maxFeePerGas:n})}var E2=C(()=>{Sh();Vr();le();xh();Wc();Ri();Zt();xr();Eo();Pt()});function dl(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u")return typeof e.accessList<"u"?"eip2930":"legacy";throw new Zu({transaction:e})}var Eh=C(()=>{Lt()});function Zc(e){if(!e||e.length===0)return[];let t=[];for(let r=0;r<e.length;r++){let{address:n,storageKeys:o}=e[r];for(let i=0;i<o.length;i++)if(o[i].length-2!==64)throw new Yu({storageKey:o[i]});if(!pe(n,{strict:!1}))throw new Ce({address:n});t.push([n,o])}return t}var _2=C(()=>{Vr();Lt();Zt()});function A2(e,t){let r=dl(e);return r==="eip1559"?C3(e,t):r==="eip2930"?U3(e,t):r==="eip4844"?O3(e,t):r==="eip7702"?R3(e,t):N3(e,t)}function R3(e,t){let{authorizationList:r,chainId:n,gas:o,nonce:i,to:s,value:a,maxFeePerGas:c,maxPriorityFeePerGas:d,accessList:f,data:u}=e;w2(e);let l=Zc(f),p=T2(r);return Le(["0x04",Tr([V(n),i?V(i):"0x",d?V(d):"0x",c?V(c):"0x",o?V(o):"0x",s??"0x",a?V(a):"0x",u??"0x",l,p,...Ys(e,t)])])}function O3(e,t){let{chainId:r,gas:n,nonce:o,to:i,value:s,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:d,accessList:f,data:u}=e;x2(e);let l=e.blobVersionedHashes,p=e.sidecars;if(e.blobs&&(typeof l>"u"||typeof p>"u")){let g=typeof e.blobs[0]=="string"?e.blobs:e.blobs.map(E=>Me(E)),w=e.kzg,v=zs({blobs:g,kzg:w});if(typeof l>"u"&&(l=tl({commitments:v})),typeof p>"u"){let E=Hs({blobs:g,commitments:v,kzg:w});p=il({blobs:g,commitments:v,proofs:E})}}let m=Zc(f),h=[V(r),o?V(o):"0x",d?V(d):"0x",c?V(c):"0x",n?V(n):"0x",i??"0x",s?V(s):"0x",u??"0x",m,a?V(a):"0x",l??[],...Ys(e,t)],y=[],b=[],x=[];if(p)for(let g=0;g<p.length;g++){let{blob:w,commitment:v,proof:E}=p[g];y.push(w),b.push(v),x.push(E)}return Le(["0x03",p?Tr([h,y,b,x]):Tr(h)])}function C3(e,t){let{chainId:r,gas:n,nonce:o,to:i,value:s,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:d,data:f}=e;cl(e);let u=Zc(d),l=[V(r),o?V(o):"0x",c?V(c):"0x",a?V(a):"0x",n?V(n):"0x",i??"0x",s?V(s):"0x",f??"0x",u,...Ys(e,t)];return Le(["0x02",Tr(l)])}function U3(e,t){let{chainId:r,gas:n,data:o,nonce:i,to:s,value:a,accessList:c,gasPrice:d}=e;v2(e);let f=Zc(c),u=[V(r),i?V(i):"0x",d?V(d):"0x",n?V(n):"0x",s??"0x",a?V(a):"0x",o??"0x",f,...Ys(e,t)];return Le(["0x01",Tr(u)])}function N3(e,t){let{chainId:r=0,gas:n,data:o,nonce:i,to:s,value:a,gasPrice:c}=e;S2(e);let d=[i?V(i):"0x",c?V(c):"0x",n?V(n):"0x",s??"0x",a?V(a):"0x",o??"0x"];if(t){let f=(()=>{if(t.v>=35n)return(t.v-35n)/2n>0?t.v:27n+(t.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);let p=27n+(t.v===27n?0n:1n);if(t.v!==p)throw new Wu({v:t.v});return p})(),u=Kr(t.r),l=Kr(t.s);d=[...d,V(f),u==="0x00"?"0x":u,l==="0x00"?"0x":l]}else r>0&&(d=[...d,V(r),"0x","0x"]);return Tr(d)}function Ys(e,t){let r=t??e,{v:n,yParity:o}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof o>"u")return[];let i=Kr(r.r),s=Kr(r.s);return[typeof o=="number"?o?V(1):"0x":n===0n?"0x":n===1n?V(1):n===27n?"0x":V(1),i==="0x00"?"0x":i,s==="0x00"?"0x":s]}var _h=C(()=>{Lt();I2();Qu();el();wh();vh();or();eu();xe();Ou();E2();Eh();_2()});function T2(e){if(!e||e.length===0)return[];let t=[];for(let r of e){let{chainId:n,nonce:o,...i}=r,s=r.address;t.push([n?ht(n):"0x",s,o?ht(o):"0x",...Ys({},i)])}return t}var I2=C(()=>{xe();_h()});function gt(e){if(e?.reason)return e.reason;if(typeof DOMException=="function")return new DOMException("This operation was aborted","AbortError");let t=new Error("This operation was aborted");return t.name="AbortError",t}function nn(e){return typeof e=="object"&&e!==null&&"name"in e&&e.name==="AbortError"}var k2,Xs,Un=C(()=>{k2=e=>e;Xs=e=>{try{let t=new URL(e);return!t.username&&!t.password?e:(t.username="",t.password="",t.toString())}catch{return e}}});var ko,Js,Yc=C(()=>{Ar();le();Un();ko=class extends L{constructor({body:t,cause:r,details:n,headers:o,status:i,url:s}){super("HTTP request failed.",{cause:r,details:n,metaMessages:[i&&`Status: ${i}`,`URL: ${Xs(s)}`,t&&`Request body: ${qe(t)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=t,this.headers=o,this.status=i,this.url=s}},Js=class extends L{constructor({body:t,error:r,url:n}){super("RPC Request failed.",{cause:r,details:r.message,metaMessages:[`URL: ${Xs(n)}`,`Request body: ${qe(t)}`],name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=r.code,this.data=r.data,this.url=n}}});var F3,wt,xt,Qs,ea,ta,ra,Nn,Bo,na,oa,ia,Po,Oi,sa,Ci,aa,ca,da,fa,ua,Ro,la,pa,ma,ha,ya,Oo,ba,fl,ul=C(()=>{le();Yc();F3=-1,wt=class extends L{constructor(t,{code:r,docsPath:n,metaMessages:o,name:i,shortMessage:s}){super(s,{cause:t,docsPath:n,metaMessages:o||t?.metaMessages,name:i||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i||t.name,this.code=t instanceof Js?t.code:r??F3}},xt=class extends wt{constructor(t,r){super(t,r),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=r.data}},Qs=class e extends wt{constructor(t){super(t,{code:e.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}};Object.defineProperty(Qs,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});ea=class e extends wt{constructor(t){super(t,{code:e.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}};Object.defineProperty(ea,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});ta=class e extends wt{constructor(t,{method:r}={}){super(t,{code:e.code,name:"MethodNotFoundRpcError",shortMessage:`The method${r?` "${r}"`:""} does not exist / is not available.`})}};Object.defineProperty(ta,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});ra=class e extends wt{constructor(t){super(t,{code:e.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
27
- `)})}};Object.defineProperty(ra,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});Nn=class e extends wt{constructor(t){super(t,{code:e.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}};Object.defineProperty(Nn,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});Bo=class e extends wt{constructor(t){super(t,{code:e.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
28
- `)})}};Object.defineProperty(Bo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});na=class e extends wt{constructor(t){super(t,{code:e.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}};Object.defineProperty(na,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});oa=class e extends wt{constructor(t){super(t,{code:e.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}};Object.defineProperty(oa,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});ia=class e extends wt{constructor(t){super(t,{code:e.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}};Object.defineProperty(ia,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});Po=class e extends wt{constructor(t,{method:r}={}){super(t,{code:e.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${r?` "${r}"`:""} is not supported.`})}};Object.defineProperty(Po,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});Oi=class e extends wt{constructor(t){super(t,{code:e.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}};Object.defineProperty(Oi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});sa=class e extends wt{constructor(t){super(t,{code:e.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}};Object.defineProperty(sa,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});Ci=class e extends xt{constructor(t){super(t,{code:e.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}};Object.defineProperty(Ci,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});aa=class e extends xt{constructor(t){super(t,{code:e.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}};Object.defineProperty(aa,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});ca=class e extends xt{constructor(t,{method:r}={}){super(t,{code:e.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}};Object.defineProperty(ca,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});da=class e extends xt{constructor(t){super(t,{code:e.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}};Object.defineProperty(da,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});fa=class e extends xt{constructor(t){super(t,{code:e.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}};Object.defineProperty(fa,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});ua=class e extends xt{constructor(t){super(t,{code:e.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}};Object.defineProperty(ua,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});Ro=class e extends xt{constructor(t){super(t,{code:e.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}};Object.defineProperty(Ro,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});la=class e extends xt{constructor(t){super(t,{code:e.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}};Object.defineProperty(la,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});pa=class e extends xt{constructor(t){super(t,{code:e.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}};Object.defineProperty(pa,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});ma=class e extends xt{constructor(t){super(t,{code:e.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}};Object.defineProperty(ma,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});ha=class e extends xt{constructor(t){super(t,{code:e.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}};Object.defineProperty(ha,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});ya=class e extends xt{constructor(t){super(t,{code:e.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}};Object.defineProperty(ya,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});Oo=class e extends xt{constructor(t){super(t,{code:e.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}};Object.defineProperty(Oo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});ba=class e extends xt{constructor(t){super(t,{code:e.code,name:"WalletConnectSessionSettlementError",shortMessage:"WalletConnect session settlement failed."})}};Object.defineProperty(ba,"code",{enumerable:!0,configurable:!0,writable:!0,value:7e3});fl=class extends wt{constructor(t){super(t,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}});function B2(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(ll.get(r))return ll.get(r);let n=e().finally(()=>ll.delete(r));return ll.set(r,n),n}var ll,P2=C(()=>{wi();ll=new zt(8192)});async function Xc(e,{signal:t}={}){return new Promise((r,n)=>{if(t?.aborted){n(gt(t));return}let o=()=>t?.removeEventListener("abort",s),i=setTimeout(()=>{o(),r()},e),s=()=>{clearTimeout(i),o(),n(gt(t))};t?.addEventListener("abort",s,{once:!0})})}var Ah=C(()=>{Un()});function Ui(e,{delay:t=100,retryCount:r=2,shouldRetry:n=()=>!0,signal:o}={}){return new Promise((i,s)=>{let a=()=>s(gt(o));o?.addEventListener("abort",a,{once:!0});let c=async({count:d=0}={})=>{if(o?.aborted){s(gt(o));return}let f=async({error:u})=>{let l=typeof t=="function"?t({count:d,error:u}):t;if(l)try{await Xc(l,{signal:o})}catch(p){s(p);return}return c({count:d+1})};try{let u=await e();i(u)}catch(u){if(o?.aborted){s(gt(o));return}if(nn(u)){s(u);return}if(d<r&&await n({count:d,error:u}))return f({error:u});s(u)}};c().catch(s).finally(()=>o?.removeEventListener("abort",a))})}var pl=C(()=>{Un();Ah()});function R2(e,t={}){return async(r,n={})=>{let{dedupe:o=!1,methods:i,retryDelay:s=150,retryCount:a=3,signal:c,uid:d}={...t,...n},{method:f}=r;if(i?.exclude?.includes(f))throw new Po(new Error("method not supported"),{method:f});if(i?.include&&!i.include.includes(f))throw new Po(new Error("method not supported"),{method:f});if(c?.aborted)throw gt(c);let u=o?z3(`${d}.${qe(r)}`):void 0;return B2(()=>Ui(async()=>{try{return await e(r,c?{signal:c}:void 0)}catch(l){if(c?.aborted)throw gt(c);if(nn(l))throw l;let p=l;switch(p.code){case Qs.code:throw new Qs(p);case ea.code:throw new ea(p);case ta.code:throw new ta(p,{method:r.method});case ra.code:throw new ra(p);case Nn.code:throw new Nn(p);case Bo.code:throw new Bo(p);case na.code:throw new na(p);case oa.code:throw new oa(p);case ia.code:throw new ia(p);case Po.code:throw new Po(p,{method:r.method});case Oi.code:throw new Oi(p);case sa.code:throw new sa(p);case Ci.code:throw new Ci(p);case aa.code:throw new aa(p);case ca.code:throw new ca(p);case da.code:throw new da(p);case fa.code:throw new fa(p);case ua.code:throw new ua(p);case Ro.code:throw new Ro(p);case la.code:throw new la(p);case pa.code:throw new pa(p);case ma.code:throw new ma(p);case ha.code:throw new ha(p);case ya.code:throw new ya(p);case Oo.code:throw new Oo(p);case 5e3:throw new Ci(p);case ba.code:throw new ba(p);default:throw l instanceof L?l:new fl(p)}}},{delay:({count:l,error:p})=>{if(p&&p instanceof ko){let m=p?.headers?.get("Retry-After");if(m?.match(/\d/))return Number.parseInt(m,10)*1e3}return~~(1<<l)*s},retryCount:a,signal:c,shouldRetry:({error:l})=>M3(l)}),{enabled:o,id:u})}}function M3(e){return nn(e)?!1:"code"in e&&typeof e.code=="number"?e.code===-1||e.code===Oi.code||e.code===Nn.code||e.code===429||e.code===-32007:e instanceof ko&&e.status?e.status===403||e.status===408||e.status===413||e.status===429||e.status===500||e.status===502||e.status===503||e.status===504:!0}function z3(e,t=0){let r=3735928559^t,n=1103547991^t;for(let o=0;o<e.length;o++){let i=e.charCodeAt(o);r=Math.imul(r^i,2654435761),n=Math.imul(n^i,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>16,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>16,3266489909),(4294967296*(2097151&n)+(r>>>0)).toString(36)}var O2=C(()=>{le();Yc();ul();Un();P2();pl();Ar()});var C2,U2=C(()=>{C2="0.1.1"});function N2(){return C2}var F2=C(()=>{U2()});function M2(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?M2(e.cause,t):t?null:e}var Co,z2=C(()=>{F2();Co=class e extends Error{static setStaticOptions(t){e.prototype.docsOrigin=t.docsOrigin,e.prototype.showVersion=t.showVersion,e.prototype.version=t.version}constructor(t,r={}){let n=(()=>{if(r.cause instanceof e){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:r.cause?.message?r.cause.message:r.details})(),o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,i=r.docsOrigin??e.prototype.docsOrigin,s=`${i}${o??""}`,a=!!(r.version??e.prototype.showVersion),c=r.version??e.prototype.version,d=[t||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||o||a?["",n?`Details: ${n}`:void 0,o?`See: ${s}`:void 0,a?`Version: ${c}`:void 0]:[]].filter(f=>typeof f=="string").join(`
29
- `);super(d,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsOrigin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"showVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.cause=r.cause,this.details=n,this.docs=s,this.docsOrigin=i,this.docsPath=o,this.shortMessage=t,this.showVersion=a,this.version=c}walk(t){return M2(this,t)}};Object.defineProperty(Co,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:`ox@${N2()}`}});Co.setStaticOptions(Co.defaultStaticOptions)});function H2(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;let o=e.replace("0x","");if(o.length>n*2)throw new ml({size:Math.ceil(o.length/2),targetSize:n,type:"Hex"});return`0x${o[r==="right"?"padEnd":"padStart"](n*2,"0")}`}var $2=C(()=>{hl()});function kr(e,t={}){let{signed:r,size:n}=t,o=BigInt(e),i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));let s=typeof i=="bigint"&&r?-i-1n:0;if(i&&o>i||o<s){let d=typeof e=="bigint"?"n":"";throw new Ih({max:i?`${i}${d}`:void 0,min:`${s}${d}`,signed:r,size:n,value:`${e}${d}`})}let c=`0x${(r&&o<0?BigInt.asUintN(n*8,BigInt(o)):o).toString(16)}`;return n?L3(c,n):c}function L3(e,t){return H2(e,{dir:"left",size:t})}var Ih,ml,hl=C(()=>{z2();$2();Ih=class extends Co{constructor({max:t,min:r,signed:n,size:o,value:i}){super(`Number \`${i}\` is not in safe${o?` ${o*8}-bit`:""}${n?" signed":" unsigned"} integer range ${t?`(\`${r}\` to \`${t}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}},ml=class extends Co{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}});function L2(e){return{address:e.address,amount:kr(e.amount),index:kr(e.index),validatorIndex:kr(e.validatorIndex)}}var D2=C(()=>{hl()});function q2(e){return{...typeof e.baseFeePerGas=="bigint"&&{baseFeePerGas:kr(e.baseFeePerGas)},...typeof e.blobBaseFee=="bigint"&&{blobBaseFee:kr(e.blobBaseFee)},...typeof e.feeRecipient=="string"&&{feeRecipient:e.feeRecipient},...typeof e.gasLimit=="bigint"&&{gasLimit:kr(e.gasLimit)},...typeof e.number=="bigint"&&{number:kr(e.number)},...typeof e.prevRandao=="bigint"&&{prevRandao:kr(e.prevRandao)},...typeof e.time=="bigint"&&{time:kr(e.time)},...e.withdrawals&&{withdrawals:e.withdrawals.map(L2)}}}var j2=C(()=>{hl();D2()});var kh,yl,G2,sN,aN,Ni,Jc=C(()=>{kh=[{inputs:[{components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}],name:"returnData",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{name:"addr",type:"address"}],name:"getEthBalance",outputs:[{name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"}],yl=[{name:"query",type:"function",stateMutability:"view",inputs:[{type:"tuple[]",name:"queries",components:[{type:"address",name:"sender"},{type:"string[]",name:"urls"},{type:"bytes",name:"data"}]}],outputs:[{type:"bool[]",name:"failures"},{type:"bytes[]",name:"responses"}]},{name:"HttpError",type:"error",inputs:[{type:"uint16",name:"status"},{type:"string",name:"message"}]}],G2=[{inputs:[{name:"dns",type:"bytes"}],name:"DNSDecodingFailed",type:"error"},{inputs:[{name:"ens",type:"string"}],name:"DNSEncodingFailed",type:"error"},{inputs:[],name:"EmptyAddress",type:"error"},{inputs:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"HttpError",type:"error"},{inputs:[],name:"InvalidBatchGatewayResponse",type:"error"},{inputs:[{name:"errorData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{name:"name",type:"bytes"},{name:"resolver",type:"address"}],name:"ResolverNotContract",type:"error"},{inputs:[{name:"name",type:"bytes"}],name:"ResolverNotFound",type:"error"},{inputs:[{name:"primary",type:"string"},{name:"primaryAddress",type:"bytes"}],name:"ReverseAddressMismatch",type:"error"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"}],name:"UnsupportedResolverProfile",type:"error"}],sN=[...G2,{name:"resolveWithGateways",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}],aN=[...G2,{name:"reverseWithGateways",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"uint256",name:"coinType"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolver"},{type:"address",name:"reverseResolver"}]}],Ni=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{type:"uint8"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}]});var V2,K2=C(()=>{V2="0x82ad56cb"});var W2,Z2,Y2,X2=C(()=>{W2="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",Z2="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",Y2="0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033"});function J2(e){return e.reduce((t,{slot:r,value:n})=>`${t} ${r}: ${n}
30
- `,"")}function Q2(e){return e.reduce((t,{address:r,...n})=>{let o=`${t} ${r}:
10
+ `),{docsPath:r,name:"AbiErrorNotFoundError"})}},ys=class extends L{constructor(t,{docsPath:r,cause:n}){super([`Encoded error signature "${t}" not found on ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${t}.`].join(`
11
+ `),{docsPath:r,name:"AbiErrorSignatureNotFoundError",cause:n}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.signature=t}},uu=class extends L{constructor({docsPath:t}){super("Cannot extract event signature from empty topics.",{docsPath:t,name:"AbiEventSignatureEmptyTopicsError"})}},lu=class extends L{constructor(t,{docsPath:r}){super([`Encoded event signature "${t}" not found on ABI.`,"Make sure you are using the correct ABI and that the event exists on it.",`You can look up the signature here: https://4byte.sourcify.dev/?q=${t}.`].join(`
12
+ `),{docsPath:r,name:"AbiEventSignatureNotFoundError"})}},Sr=class extends L{constructor(t,{docsPath:r}={}){super([`Function ${t?`"${t}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it."].join(`
13
+ `),{docsPath:r,name:"AbiFunctionNotFoundError"})}},bs=class extends L{constructor(t,{docsPath:r}){super([`Function "${t}" does not contain any \`outputs\` on ABI.`,"Cannot decode function result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the function exists on it."].join(`
14
+ `),{docsPath:r,name:"AbiFunctionOutputsNotFoundError"})}},pu=class extends L{constructor(t,{docsPath:r}){super([`Encoded function signature "${t}" not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it.",`You can look up the signature here: https://4byte.sourcify.dev/?q=${t}.`].join(`
15
+ `),{docsPath:r,name:"AbiFunctionSignatureNotFoundError"})}},mu=class extends L{constructor(t,r){super("Found ambiguous types in overloaded ABI items.",{metaMessages:[`\`${t.type}\` in \`${ft(t.abiItem)}\`, and`,`\`${r.type}\` in \`${ft(r.abiItem)}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."],name:"AbiItemAmbiguityError"})}},hu=class extends L{constructor({expectedSize:t,givenSize:r}){super(`Expected bytes${t}, got bytes${r}.`,{name:"BytesSizeMismatchError"})}},Pc=class extends L{constructor({abiItem:t,data:r,params:n,size:o}){super([`Data size of ${o} bytes is too small for non-indexed event parameters.`].join(`
16
+ `),{metaMessages:[`Params: (${Ic(n,{includeName:!0})})`,`Data: ${r} (${o} bytes)`],name:"DecodeLogDataMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=t,this.data=r,this.params=n,this.size=o}},yu=class extends L{constructor({abiItem:t,param:r}){super([`Expected a topic for indexed event parameter${r.name?` "${r.name}"`:""} on event "${ft(t,{includeName:!0})}".`].join(`
17
+ `),{name:"DecodeLogTopicsMismatch"}),Object.defineProperty(this,"abiItem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abiItem=t}},bu=class extends L{constructor(t,{docsPath:r}){super([`Type "${t}" is not a valid encoding type.`,"Please provide a valid ABI type."].join(`
18
+ `),{docsPath:r,name:"InvalidAbiEncodingType"})}},gu=class extends L{constructor(t,{docsPath:r}){super([`Type "${t}" is not a valid decoding type.`,"Please provide a valid ABI type."].join(`
19
+ `),{docsPath:r,name:"InvalidAbiDecodingType"})}},gs=class extends L{constructor(t){super([`Value "${t}" is not a valid array.`].join(`
20
+ `),{name:"InvalidArrayError"})}},iu=class extends L{constructor(t){super([`"${t}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join(`
21
+ `),{name:"InvalidDefinitionTypeError"})}}});var Rc,ws,wu,Sm=C(()=>{le();Rc=class extends L{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`,{name:"NegativeOffsetError"})}},ws=class extends L{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`,{name:"PositionOutOfBoundsError"})}},wu=class extends L{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`,{name:"RecursiveReadLimitExceededError"})}}});function xs(e,{recursiveReadLimit:t=8192}={}){let r=Object.create(ME);return r.bytes=e,r.dataView=new DataView(e.buffer??e,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}var ME,xu=C(()=>{Sm();ME={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new wu({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new ws({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new Rc({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new Rc({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}}});function nr(e,t,r,{strict:n}={}){return dt(e,{strict:!1})?vu(e,t,r,{strict:n}):Em(e,t,r,{strict:n})}function q1(e,t){if(typeof t=="number"&&t>0&&t>ge(e)-1)throw new xc({offset:t,position:"start",size:ge(e)})}function j1(e,t,r){if(typeof t=="number"&&typeof r=="number"&&ge(e)!==r-t)throw new xc({offset:r,position:"end",size:ge(e)})}function Em(e,t,r,{strict:n}={}){q1(e,t);let o=e.slice(t,r);return n&&j1(o,t,r),o}function vu(e,t,r,{strict:n}={}){q1(e,t);let o=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return n&&j1(o,t,r),o}var Eo=C(()=>{Zf();xn();wr()});function G1(e,t={}){typeof t.size<"u"&&Wt(e,{size:t.size});let r=Me(e);return De(r,t)}function V1(e,t={}){let r=e;if(typeof t.size<"u"&&(Wt(r,{size:t.size}),r=Vr(r)),r.length>1||r[0]>1)throw new Xf(r);return!!r[0]}function Zr(e,t={}){typeof t.size<"u"&&Wt(e,{size:t.size});let r=Me(e);return Xe(r,t)}function K1(e,t={}){let r=e;return typeof t.size<"u"&&(Wt(r,{size:t.size}),r=Vr(r,{dir:"right"})),new TextDecoder().decode(r)}var W1=C(()=>{Ec();Qf();Bt();xe()});function Er(e){return typeof e[0]=="string"?Le(e):HE(e)}function HE(e){let t=0;for(let o of e)t+=o.length;let r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function Le(e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}var or=C(()=>{});var Z1,Su,_m=C(()=>{Z1=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Su=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/});function Yr(e,t){if(e.length!==t.length)throw new du({expectedLength:e.length,givenLength:t.length});let r=zE({params:e,values:t});return Im(r)}function zE({params:e,values:t}){let r=[];for(let n=0;n<e.length;n++)r.push(Tm({param:e[n],value:t[n]}));return r}function Tm({param:e,value:t}){let r=Oc(e.type);if(r){let[n,o]=r;return LE(t,{length:n,param:{...e,type:o}})}if(e.type==="tuple")return VE(t,{param:e});if(e.type==="address")return $E(t);if(e.type==="bool")return qE(t);if(e.type.startsWith("uint")||e.type.startsWith("int")){let n=e.type.startsWith("int"),[,,o="256"]=Su.exec(e.type)??[];return jE(t,{signed:n,size:Number(o)})}if(e.type.startsWith("bytes"))return DE(t,{param:e});if(e.type==="string")return GE(t);throw new bu(e.type,{docsPath:"/docs/contract/encodeAbiParameters"})}function Im(e){let t=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:a}=e[i];s?t+=32:t+=ge(a)}let r=[],n=[],o=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:a}=e[i];s?(r.push(V(t+o,{size:32})),n.push(a),o+=ge(a)):r.push(a)}return Le([...r,...n])}function $E(e){if(!pe(e))throw new Ce({address:e});return{dynamic:!1,encoded:vn(e.toLowerCase())}}function LE(e,{length:t,param:r}){let n=t===null;if(!Array.isArray(e))throw new gs(e);if(!n&&e.length!==t)throw new au({expectedLength:t,givenLength:e.length,type:`${r.type}[${t}]`});let o=e.length===0&&Am(r),i=[];for(let s=0;s<e.length;s++){let a=Tm({param:r,value:e[s]});a.dynamic&&(o=!0),i.push(a)}if(n||o){let s=Im(i);if(n){let a=V(i.length,{size:32});return{dynamic:!0,encoded:Le([a,s])}}if(o)return{dynamic:!0,encoded:s}}return{dynamic:!1,encoded:Le(i.map(({encoded:s})=>s))}}function DE(e,{param:t}){let[,r]=t.type.split("bytes"),n=ge(e);if(!r){let o=e;return n%32!==0&&(o=vn(o,{dir:"right",size:Math.ceil((e.length-2)/2/32)*32})),{dynamic:!0,encoded:Le([vn(V(n,{size:32})),o])}}if(n!==Number.parseInt(r,10))throw new cu({expectedSize:Number.parseInt(r,10),value:e});return{dynamic:!1,encoded:vn(e,{dir:"right"})}}function qE(e){if(typeof e!="boolean")throw new L(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:vn(bm(e))}}function jE(e,{signed:t,size:r=256}){if(typeof r=="number"){let n=2n**(BigInt(r)-(t?1n:0n))-1n,o=t?-n-1n:0n;if(e>n||e<o)throw new bo({max:n.toString(),min:o.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:V(e,{size:32,signed:t})}}function GE(e){let t=_c(e),r=Math.ceil(ge(t)/32),n=[];for(let o=0;o<r;o++)n.push(vn(nr(t,o*32,(o+1)*32),{dir:"right"}));return{dynamic:!0,encoded:Le([vn(V(ge(t),{size:32})),...n])}}function VE(e,{param:t}){let r=!1,n=[];for(let o=0;o<t.components.length;o++){let i=t.components[o],s=Array.isArray(e)?o:i.name,a=Tm({param:i,value:e[s]});n.push(a),a.dynamic&&(r=!0)}return{dynamic:r,encoded:r?Im(n):Le(n.map(({encoded:o})=>o))}}function Oc(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function Am(e){let{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return e.components.some(Am);let r=Oc(t);return r?Am({...e,type:r[1]}):!1}var vi=C(()=>{yt();Gr();le();Ec();Zt();or();Yf();wr();Eo();xe();_m()});function An(e,t){let r=typeof t=="string"?Pt(t):t,n=xs(r);if(ge(r)===0&&e.length>0)throw new So;if(ge(t)&&ge(t)<32)throw new hs({data:typeof t=="string"?t:Me(t),params:e,size:ge(t)});let o=0,i=[];for(let s=0;s<e.length;++s){let a=e[s];o<r.length&&n.setPosition(o);let[c,d]=vs(n,a,{staticPosition:0});o+=d,i.push(c)}return i}function vs(e,t,{staticPosition:r}){let n=Oc(t.type);if(n){let[o,i]=n;return WE(e,{...t,type:i},{length:o,staticPosition:r})}if(t.type==="tuple")return JE(e,t,{staticPosition:r});if(t.type==="address")return KE(e);if(t.type==="bool")return ZE(e);if(t.type.startsWith("bytes"))return YE(e,t,{staticPosition:r});if(t.type.startsWith("uint")||t.type.startsWith("int"))return XE(e,t);if(t.type==="string")return QE(e,{staticPosition:r});throw new gu(t.type,{docsPath:"/docs/contract/decodeAbiParameters"})}function KE(e){let t=e.readBytes(32);return[_n(Me(Em(t,-20))),32]}function WE(e,t,{length:r,staticPosition:n}){if(r===null){let s=Zr(e.readBytes(km)),a=n+s,c=a+Y1;e.setPosition(a);let d=Zr(e.readBytes(Y1)),f=Cc(t),u=0,l=[];for(let p=0;p<d;++p){e.setPosition(c+(f?p*32:u));let[m,h]=vs(e,t,{staticPosition:c});u+=h,l.push(m),h===0&&(e.assertReadLimit(),e._touch())}return e.setPosition(n+32),[l,32]}if(Cc(t)){let s=Zr(e.readBytes(km)),a=n+s,c=[];for(let d=0;d<r;++d){e.setPosition(a+d*32);let[f]=vs(e,t,{staticPosition:a});c.push(f)}return e.setPosition(n+32),[c,32]}let o=0,i=[];for(let s=0;s<r;++s){let[a,c]=vs(e,t,{staticPosition:n+o});o+=c,i.push(a),c===0&&(e.assertReadLimit(),e._touch())}return[i,o]}function ZE(e){return[V1(e.readBytes(32),{size:32}),32]}function YE(e,t,{staticPosition:r}){let[n,o]=t.type.split("bytes");if(!o){let s=Zr(e.readBytes(32));e.setPosition(r+s);let a=Zr(e.readBytes(32));if(a===0)return e.setPosition(r+32),["0x",32];let c=e.readBytes(a);return e.setPosition(r+32),[Me(c),32]}return[Me(e.readBytes(Number.parseInt(o,10),32)),32]}function XE(e,t){let r=t.type.startsWith("int"),n=Number.parseInt(t.type.split("int")[1]||"256",10),o=e.readBytes(32);return[n>48?G1(o,{signed:r}):Zr(o,{signed:r}),32]}function JE(e,t,{staticPosition:r}){let n=t.components.length===0||t.components.some(({name:s})=>!s),o=n?[]:{},i=0;if(Cc(t)){let s=Zr(e.readBytes(km)),a=r+s;for(let c=0;c<t.components.length;++c){let d=t.components[c];e.setPosition(a+i);let[f,u]=vs(e,d,{staticPosition:a});i+=u,o[n?c:d?.name]=f}return e.setPosition(r+32),[o,32]}for(let s=0;s<t.components.length;++s){let a=t.components[s],[c,d]=vs(e,a,{staticPosition:r});o[n?s:a?.name]=c,i+=d}return[o,i]}function QE(e,{staticPosition:t}){let r=Zr(e.readBytes(32)),n=t+r;e.setPosition(n);let o=Zr(e.readBytes(32));if(o===0)return e.setPosition(t+32),["",32];let i=e.readBytes(o,32),s=K1(i);return e.setPosition(t+32),[s,32]}function Cc(e){let{type:t}=e;if(t==="string"||t==="bytes"||t.endsWith("[]"))return!0;if(t==="tuple")return e.components?.some(Cc);let r=Oc(e.type);return!!(r&&Cc({...e,type:r[1]}))}var Y1,km,Uc=C(()=>{yt();ms();xu();wr();Eo();W1();rr();xe();vi();Y1=32,km=32});var X1,Eu,J1,_u=C(()=>{X1={1:"An `assert` condition failed.",17:"Arithmetic operation resulted in underflow or overflow.",18:"Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).",33:"Attempted to convert to an invalid type.",34:"Attempted to access a storage byte array that is incorrectly encoded.",49:"Performed `.pop()` on an empty array",50:"Array index is out of bounds.",65:"Allocated too much memory or created an array which is too large.",81:"Attempted to call a zero-initialized variable of internal function type."},Eu={inputs:[{name:"message",type:"string"}],name:"Error",type:"error"},J1={inputs:[{name:"reason",type:"uint256"}],name:"Panic",type:"error"}});function Q1(e){return e3(e)}var e3,ex=C(()=>{rr();ps();e3=e=>vr(go(e))});function tx(e){let t=!0,r="",n=0,o="",i=!1;for(let s=0;s<e.length;s++){let a=e[s];if(["(",")",","].includes(a)&&(t=!0),a==="("&&n++,a===")"&&n--,!!t){if(n===0){if(a===" "&&["event","function",""].includes(o))o="";else if(o+=a,a===")"){i=!0;break}continue}if(a===" "){!r.endsWith(",")&&!r.endsWith("(")&&(r="",t=!1);continue}o+=a,r+=a}}if(!i)throw new L("Unable to normalize signature.");return o}var rx=C(()=>{le()});var nx,ox=C(()=>{mm();rx();nx=e=>{let t=typeof e=="string"?e:cm(e);return tx(t)}});function Au(e){return Q1(nx(e))}var Bm=C(()=>{ex();ox()});var Xr,Ss=C(()=>{Eo();Bm();Xr=e=>nr(Au(e),0,4)});function Tu(e){let{abi:t,data:r,cause:n}=e,o=nr(r,0,4);if(o==="0x")throw new So({cause:n});let s=[...t||[],Eu,J1].find(a=>a.type==="error"&&o===Xr(ft(a)));if(!s)throw new ys(o,{docsPath:"/docs/contract/decodeErrorResult",cause:n});return{abiItem:s,args:"inputs"in s&&s.inputs&&s.inputs.length>0?An(s.inputs,nr(r,4)):void 0,errorName:s.name}}var Pm=C(()=>{_u();yt();Eo();Ss();Uc();vo()});var Es,Iu=C(()=>{Bm();Es=Au});function Rm(e){let{abi:t,data:r,strict:n,topics:o}=e,i=n??!0,[s,...a]=o;if(!s)throw new uu({docsPath:ix});let c=t.find(b=>b.type==="event"&&s===Es(ft(b)));if(!(c&&"name"in c)||c.type!=="event")throw new lu(s,{docsPath:ix});let{name:d,inputs:f}=c,u=f?.some(b=>!("name"in b&&b.name)),l=u?[]:{},p=f.map((b,x)=>[b,x]).filter(([b])=>"indexed"in b&&b.indexed),m=[];for(let b=0;b<p.length;b++){let[x,g]=p[b],w=a[b];if(!w){if(i)throw new yu({abiItem:c,param:x});m.push([x,g]);continue}l[u?g:x.name||g]=t3({param:x,value:w})}let h=f.filter(b=>!("indexed"in b&&b.indexed)),y=i?h:[...m.map(([b])=>b),...h];if(y.length>0){if(r&&r!=="0x")try{let b=An(y,r);if(b){let x=0;if(!i)for(let[g,w]of m)l[u?w:g.name||w]=b[x++];if(u)for(let g=0;g<f.length;g++)l[g]===void 0&&x<b.length&&(l[g]=b[x++]);else for(let g=0;g<h.length;g++)l[h[g].name]=b[x++]}}catch(b){if(i)throw b instanceof hs||b instanceof ws?new Pc({abiItem:c,data:r,params:y,size:ge(r)}):b}else if(i)throw new Pc({abiItem:c,data:"0x",params:y,size:0})}return{eventName:d,args:Object.values(l).length>0?l:void 0}}function t3({param:e,value:t}){return e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/)?t:(An([e],t)||[])[0]}var ix,sx=C(()=>{yt();Sm();wr();Iu();Uc();vo();ix="/docs/contract/decodeEventLog"});function ax(e){let{abi:t,data:r}=e,n=nr(r,0,4),o=t.find(i=>i.type==="function"&&n===Xr(ft(i)));if(!o)throw new pu(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:o.name,args:"inputs"in o&&o.inputs&&o.inputs.length>0?An(o.inputs,nr(r,4)):void 0}}var cx=C(()=>{yt();Eo();Ss();Uc();vo()});function Jr(e){let{abi:t,args:r=[],name:n}=e,o=dt(n,{strict:!1}),i=t.filter(a=>o?a.type==="function"?Xr(a)===n:a.type==="event"?Es(a)===n:!1:"name"in a&&a.name===n);if(i.length===0)return;if(i.length===1)return i[0];let s;for(let a of i){if(!("inputs"in a))continue;if(!r||r.length===0){if(!a.inputs||a.inputs.length===0)return a;continue}if(!a.inputs||a.inputs.length===0||a.inputs.length!==r.length)continue;if(r.every((d,f)=>{let u="inputs"in a&&a.inputs[f];return u?Om(d,u):!1})){if(s&&"inputs"in s&&s.inputs){let d=dx(a.inputs,s.inputs,r);if(d)throw new mu({abiItem:a,type:d[0]},{abiItem:s,type:d[1]})}s=a}}return s||i[0]}function Om(e,t){let r=typeof e,n=t.type;switch(n){case"address":return pe(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in t?Object.values(t.components).every((o,i)=>r==="object"&&Om(Object.values(e)[i],o)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||e instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(e)&&e.every(o=>Om(o,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function dx(e,t,r){for(let n in e){let o=e[n],i=t[n];if(o.type==="tuple"&&i.type==="tuple"&&"components"in o&&"components"in i)return dx(o.components,i.components,r[n]);let s=[o.type,i.type];if(s.includes("address")&&s.includes("bytes20")?!0:s.includes("address")&&s.includes("string")?pe(r[n],{strict:!1}):s.includes("address")&&s.includes("bytes")?pe(r[n],{strict:!1}):!1)return s}}var _s=C(()=>{yt();xn();Zt();Iu();Ss()});function ku(e){let{abi:t,args:r,functionName:n,data:o}=e,i=t[0];if(n){let a=Jr({abi:t,args:r,name:n});if(!a)throw new Sr(n,{docsPath:Cm});i=a}if(i.type!=="function")throw new Sr(void 0,{docsPath:Cm});if(!i.outputs)throw new bs(i.name,{docsPath:Cm});let s=An(i.outputs,o);if(s&&s.length>1)return s;if(s&&s.length===1)return s[0]}var Cm,Um=C(()=>{yt();Uc();_s();Cm="/docs/contract/decodeFunctionResult"});function Nc(e){let{abi:t,args:r,bytecode:n}=e;if(!r||r.length===0)return n;let o=t.find(s=>"type"in s&&s.type==="constructor");if(!o)throw new su({docsPath:Nm});if(!("inputs"in o))throw new kc({docsPath:Nm});if(!o.inputs||o.inputs.length===0)throw new kc({docsPath:Nm});let i=Yr(o.inputs,r);return Le([n,i])}var Nm,Fm=C(()=>{yt();or();vi();Nm="/docs/contract/encodeDeployData"});function Hm(e){let{abi:t,errorName:r,args:n}=e,o=t[0];if(r){let c=Jr({abi:t,args:n,name:r});if(!c)throw new Bc(r,{docsPath:Mm});o=c}if(o.type!=="error")throw new Bc(void 0,{docsPath:Mm});let i=ft(o),s=Xr(i),a="0x";if(n&&n.length>0){if(!o.inputs)throw new fu(o.name,{docsPath:Mm});a=Yr(o.inputs,n)}return Le([s,a])}var Mm,fx=C(()=>{yt();or();Ss();vi();vo();_s();Mm="/docs/contract/encodeErrorResult"});function lx(e){let{abi:t,args:r,functionName:n}=e,o=t[0];if(n){let i=Jr({abi:t,args:r,name:n});if(!i)throw new Sr(n,{docsPath:ux});o=i}if(o.type!=="function")throw new Sr(void 0,{docsPath:ux});return{abi:[o],functionName:Xr(ft(o))}}var ux,px=C(()=>{yt();Ss();vo();_s();ux="/docs/contract/encodeFunctionData"});function Yt(e){let{args:t}=e,{abi:r,functionName:n}=e.abi.length===1&&e.functionName?.startsWith("0x")?e:lx(e),o=r[0],i=n,s="inputs"in o&&o.inputs?Yr(o.inputs,t??[]):void 0;return Le([i,s??"0x"])}var Si=C(()=>{or();vi();px()});function mx(e){let{abi:t,functionName:r,result:n}=e,o=t[0];if(r){let s=Jr({abi:t,name:r});if(!s)throw new Sr(r,{docsPath:zm});o=s}if(o.type!=="function")throw new Sr(void 0,{docsPath:zm});if(!o.outputs)throw new bs(o.name,{docsPath:zm});let i=(()=>{if(o.outputs.length===0)return[];if(o.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new gs(n)})();return Yr(o.outputs,i)}var zm,hx=C(()=>{yt();vi();_s();zm="/docs/contract/encodeFunctionResult"});var qe,_r=C(()=>{qe=(e,t,r)=>JSON.stringify(e,(n,o)=>{let i=typeof o=="bigint"?o.toString():o;return typeof t=="function"?t(n,i):i},r)});function $m({abiItem:e,args:t,includeFunctionName:r=!0,includeName:n=!1}){if("name"in e&&"inputs"in e&&e.inputs)return`${r?e.name:""}(${e.inputs.map((o,i)=>`${n&&o.name?`${o.name}: `:""}${typeof t[i]=="object"?qe(t[i]):t[i]}`).join(", ")})`}var yx=C(()=>{_r()});function Ht(e,t){if(!pe(e,{strict:!1}))throw new Ce({address:e});if(!pe(t,{strict:!1}))throw new Ce({address:t});return e.toLowerCase()===t.toLowerCase()}var Ei=C(()=>{Gr();Zt()});function Bu(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,blockTimestamp:e.blockTimestamp?BigInt(e.blockTimestamp):e.blockTimestamp===null?null:void 0,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}var Lm=C(()=>{});function Pu(e){let{abi:t,args:r,logs:n,strict:o=!0}=e,i=(()=>{if(e.eventName)return Array.isArray(e.eventName)?e.eventName:[e.eventName]})(),s=t.filter(a=>a.type==="event").map(a=>({abi:a,selector:Es(a)}));return n.map(a=>{let c=typeof a.blockNumber=="string"?Bu(a):a,d=s.filter(l=>c.topics[0]===l.selector);if(d.length===0)return null;let f,u;for(let l of d)try{f=Rm({...c,abi:[l.abi],strict:!0}),u=l;break}catch{}if(!f&&!o){u=d[0];try{f=Rm({data:c.data,topics:c.topics,abi:[u.abi],strict:!1})}catch{let l=u.abi.inputs?.some(p=>!("name"in p&&p.name));return{...c,args:l?[]:{},eventName:u.abi.name}}}return!f||!u||i&&!i.includes(f.eventName)||!r3({args:f.args,inputs:u.abi.inputs,matchArgs:r})?null:{...f,...c}}).filter(Boolean)}function r3(e){let{args:t,inputs:r,matchArgs:n}=e;if(!n)return!0;if(!t)return!1;function o(i,s,a){try{return i.type==="address"?Ht(s,a):i.type==="string"?vr(Ac(s))===a:i.type==="bytes"?vr(go(s))===a:s===a}catch{return!1}}return Array.isArray(t)&&Array.isArray(n)?n.every((i,s)=>{if(i==null)return!0;let a=r[s];return a?(Array.isArray(i)?i:[i]).some(d=>o(a,d,t[s])):!1}):typeof t=="object"&&!Array.isArray(t)&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).every(([i,s])=>{if(s==null)return!0;let a=r.find(d=>d.name===i);return a?(Array.isArray(s)?s:[s]).some(d=>o(a,d,t[i])):!1}):!1}var Dm=C(()=>{Ei();rr();Lm();ps();Iu();sx()});function Ar(e,t="hex"){let r=bx(e),n=xs(new Uint8Array(r.length));return r.encode(n),t==="hex"?Me(n.bytes):n.bytes}function bx(e){return Array.isArray(e)?n3(e.map(t=>bx(t))):o3(e)}function n3(e){let t=e.reduce((o,i)=>o+i.length,0),r=gx(t);return{length:t<=55?1+t:1+r+t,encode(o){t<=55?o.pushByte(192+t):(o.pushByte(247+r),r===1?o.pushUint8(t):r===2?o.pushUint16(t):r===3?o.pushUint24(t):o.pushUint32(t));for(let{encode:i}of e)i(o)}}}function o3(e){let t=typeof e=="string"?Pt(e):e,r=gx(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(o){t.length===1&&t[0]<128?o.pushBytes(t):t.length<=55?(o.pushByte(128+t.length),o.pushBytes(t)):(o.pushByte(183+r),r===1?o.pushUint8(t.length):r===2?o.pushUint16(t.length):r===3?o.pushUint24(t.length):o.pushUint32(t.length),o.pushBytes(t))}}}function gx(e){if(e<2**8)return 1;if(e<2**16)return 2;if(e<2**24)return 3;if(e<2**32)return 4;throw new L("Length is too large.")}var Ru=C(()=>{le();xu();rr();xe()});function wx(e){let{chainId:t,nonce:r,to:n}=e,o=e.contractAddress??e.address,i=vr(Le(["0x05",Ar([t?V(t):"0x",o,r?V(r):"0x"])]));return n==="bytes"?Pt(i):i}var xx=C(()=>{or();rr();xe();Ru();ps()});function i3(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(r>>o&i),a=Number(r&i),c=n?4:0,d=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+d,a,n)}function vx(e,t,r){return e&t^~e&r}function Sx(e,t,r){return e&t^e&r^t&r}var Ou,Tn,Ex=C(()=>{xo();Ou=class extends wo{constructor(t,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=ru(this.buffer)}update(t){En(this),t=wi(t),Kr(t);let{view:r,buffer:n,blockLen:o}=this,i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=ru(t);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){En(this),tu(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;r[s++]=128,Wr(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(n,0),s=0);for(let u=s;u<o;u++)r[u]=0;i3(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=ru(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=c/4,f=this.get();if(d>f.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<d;u++)a.setUint32(4*u,f[u],i)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:i,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=i,t.length=o,t.pos=a,o%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Tn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])});var s3,_o,Cu,_i,qm=C(()=>{Ex();xo();s3=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),_o=new Uint32Array(64),Cu=class extends Ou{constructor(t=32){super(64,t,8,!1),this.A=Tn[0]|0,this.B=Tn[1]|0,this.C=Tn[2]|0,this.D=Tn[3]|0,this.E=Tn[4]|0,this.F=Tn[5]|0,this.G=Tn[6]|0,this.H=Tn[7]|0}get(){let{A:t,B:r,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[t,r,n,o,i,s,a,c]}set(t,r,n,o,i,s,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,r){for(let u=0;u<16;u++,r+=4)_o[u]=t.getUint32(r,!1);for(let u=16;u<64;u++){let l=_o[u-15],p=_o[u-2],m=xr(l,7)^xr(l,18)^l>>>3,h=xr(p,17)^xr(p,19)^p>>>10;_o[u]=h+_o[u-7]+m+_o[u-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:d,H:f}=this;for(let u=0;u<64;u++){let l=xr(a,6)^xr(a,11)^xr(a,25),p=f+l+vx(a,c,d)+s3[u]+_o[u]|0,h=(xr(n,2)^xr(n,13)^xr(n,22))+Sx(n,o,i)|0;f=d,d=c,c=a,a=s+p|0,s=i,i=o,o=n,n=p+h|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,d=d+this.G|0,f=f+this.H|0,this.set(n,o,i,s,a,c,d,f)}roundClean(){Wr(_o)}destroy(){this.set(0,0,0,0,0,0,0,0),Wr(this.buffer)}},_i=nu(()=>new Cu)});var Uu,jm,_x=C(()=>{xo();Uu=class extends wo{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,B1(t);let n=wi(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,i=new Uint8Array(o);i.set(n.length>o?t.create().update(n).digest():n);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=t.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),Wr(i)}update(t){return En(this),this.iHash.update(t),this}digestInto(t){En(this),Kr(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},jm=(e,t,r)=>new Uu(e,t).update(r).digest();jm.create=(e,t)=>new Uu(e,t)});function As(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function kn(e){if(!As(e))throw new Error("Uint8Array expected")}function Ts(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function Fc(e){let t=e.toString(16);return t.length&1?"0"+t:t}function Ix(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?Wm:BigInt("0x"+e)}function Is(e){if(kn(e),kx)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=a3[e[r]];return t}function Ax(e){if(e>=In._0&&e<=In._9)return e-In._0;if(e>=In.A&&e<=In.F)return e-(In.A-10);if(e>=In.a&&e<=In.f)return e-(In.a-10)}function Mc(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(kx)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,i=0;o<r;o++,i+=2){let s=Ax(e.charCodeAt(i)),a=Ax(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function zt(e){return Ix(Is(e))}function Zm(e){return kn(e),Ix(Is(Uint8Array.from(e).reverse()))}function Qr(e,t){return Mc(e.toString(16).padStart(t*2,"0"))}function Ym(e,t){return Qr(e,t).reverse()}function Je(e,t,r){let n;if(typeof t=="string")try{n=Mc(t)}catch(i){throw new Error(e+" must be hex string or Uint8Array, cause: "+i)}else if(As(t))n=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");let o=n.length;if(typeof r=="number"&&o!==r)throw new Error(e+" of length "+r+" expected, got "+o);return n}function Rt(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];kn(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let i=e[n];r.set(i,o),o+=i.length}return r}function Nu(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function Ai(e,t,r){return Gm(e)&&Gm(t)&&Gm(r)&&t<=e&&e<r}function Bn(e,t,r,n){if(!Ai(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function Bx(e){let t;for(t=0;e>Wm;e>>=Km,t+=1);return t}function Px(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=Vm(e),o=Vm(e),i=0,s=()=>{n.fill(1),o.fill(0),i=0},a=(...u)=>r(o,n,...u),c=(u=Vm(0))=>{o=a(Tx([0]),u),n=a(),u.length!==0&&(o=a(Tx([1]),u),n=a())},d=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let u=0,l=[];for(;u<t;){n=a();let p=n.slice();l.push(p),u+=n.length}return Rt(...l)};return(u,l)=>{s(),c(u);let p;for(;!(p=l(d()));)c();return s(),p}}function Pn(e,t,r={}){let n=(o,i,s)=>{let a=c3[i];if(typeof a!="function")throw new Error("invalid validator function");let c=e[o];if(!(s&&c===void 0)&&!a(c,e))throw new Error("param "+String(o)+" is invalid. Expected "+i+", got "+c)};for(let[o,i]of Object.entries(t))n(o,i,!1);for(let[o,i]of Object.entries(r))n(o,i,!0);return e}function Xm(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let i=e(r,...n);return t.set(r,i),i}}var Wm,Km,kx,a3,In,Gm,Ti,Vm,Tx,c3,ks=C(()=>{Wm=BigInt(0),Km=BigInt(1);kx=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",a3=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));In={_0:48,_9:57,A:65,F:70,a:97,f:102};Gm=e=>typeof e=="bigint"&&Wm<=e;Ti=e=>(Km<<BigInt(e))-Km,Vm=e=>new Uint8Array(e),Tx=e=>Uint8Array.from(e);c3={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||As(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)}});function Ve(e,t){let r=e%t;return r>=Ot?r:t+r}function Xt(e,t,r){let n=e;for(;t-- >Ot;)n*=n,n%=r;return n}function Fu(e,t){if(e===Ot)throw new Error("invert: expected non-zero number");if(t<=Ot)throw new Error("invert: expected positive modulus, got "+t);let r=Ve(e,t),n=t,o=Ot,i=bt,s=bt,a=Ot;for(;r!==Ot;){let d=n/r,f=n%r,u=o-s*d,l=i-a*d;n=r,r=f,o=s,i=a,s=u,a=l}if(n!==bt)throw new Error("invert: does not exist");return Ve(o,t)}function Nx(e,t){let r=(e.ORDER+bt)/Ox,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function f3(e,t){let r=(e.ORDER-Cx)/Ux,n=e.mul(t,Ii),o=e.pow(n,r),i=e.mul(t,o),s=e.mul(e.mul(i,Ii),o),a=e.mul(i,e.sub(s,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function u3(e){if(e<BigInt(3))throw new Error("sqrt is not defined for small field");let t=e-bt,r=0;for(;t%Ii===Ot;)t/=Ii,r++;let n=Ii,o=Hc(e);for(;Rx(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Nx;let i=o.pow(n,t),s=(t+bt)/Ii;return function(c,d){if(c.is0(d))return d;if(Rx(c,d)!==1)throw new Error("Cannot find square root");let f=r,u=c.mul(c.ONE,i),l=c.pow(d,t),p=c.pow(d,s);for(;!c.eql(l,c.ONE);){if(c.is0(l))return c.ZERO;let m=1,h=c.sqr(l);for(;!c.eql(h,c.ONE);)if(m++,h=c.sqr(h),m===f)throw new Error("Cannot find square root");let y=bt<<BigInt(f-m-1),b=c.pow(u,y);f=m,u=c.sqr(b),l=c.mul(l,u),p=c.mul(p,b)}return p}}function l3(e){return e%Ox===d3?Nx:e%Ux===Cx?f3:u3(e)}function Mu(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=p3.reduce((n,o)=>(n[o]="function",n),t);return Pn(e,r)}function m3(e,t,r){if(r<Ot)throw new Error("invalid exponent, negatives unsupported");if(r===Ot)return e.ONE;if(r===bt)return t;let n=e.ONE,o=t;for(;r>Ot;)r&bt&&(n=e.mul(n,o)),o=e.sqr(o),r>>=bt;return n}function Bs(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((s,a,c)=>e.is0(a)?s:(n[c]=s,e.mul(s,a)),e.ONE),i=e.inv(o);return t.reduceRight((s,a,c)=>e.is0(a)?s:(n[c]=e.mul(s,n[c]),e.mul(s,a)),i),n}function Rx(e,t){let r=(e.ORDER-bt)/Ii,n=e.pow(t,r),o=e.eql(n,e.ONE),i=e.eql(n,e.ZERO),s=e.eql(n,e.neg(e.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function Jm(e,t){t!==void 0&&gi(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Hc(e,t,r=!1,n={}){if(e<=Ot)throw new Error("invalid field: expected ORDER > 0, got "+e);let{nBitLength:o,nByteLength:i}=Jm(e,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let s,a=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:i,MASK:Ti(o),ZERO:Ot,ONE:bt,create:c=>Ve(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ot<=c&&c<e},is0:c=>c===Ot,isOdd:c=>(c&bt)===bt,neg:c=>Ve(-c,e),eql:(c,d)=>c===d,sqr:c=>Ve(c*c,e),add:(c,d)=>Ve(c+d,e),sub:(c,d)=>Ve(c-d,e),mul:(c,d)=>Ve(c*d,e),pow:(c,d)=>m3(a,c,d),div:(c,d)=>Ve(c*Fu(d,e),e),sqrN:c=>c*c,addN:(c,d)=>c+d,subN:(c,d)=>c-d,mulN:(c,d)=>c*d,inv:c=>Fu(c,e),sqrt:n.sqrt||(c=>(s||(s=l3(e)),s(a,c))),toBytes:c=>r?Ym(c,i):Qr(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return r?Zm(c):zt(c)},invertBatch:c=>Bs(a,c),cmov:(c,d,f)=>f?d:c});return Object.freeze(a)}function Fx(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function Qm(e){let t=Fx(e);return t+Math.ceil(t/2)}function Mx(e,t,r=!1){let n=e.length,o=Fx(t),i=Qm(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=r?Zm(e):zt(e),a=Ve(s,t-bt)+bt;return r?Ym(a,o):Qr(a,o)}var Ot,bt,Ii,d3,Ox,Cx,Ux,p3,zc=C(()=>{xo();ks();Ot=BigInt(0),bt=BigInt(1),Ii=BigInt(2),d3=BigInt(3),Ox=BigInt(4),Cx=BigInt(5),Ux=BigInt(8);p3=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function eh(e,t){let r=t.negate();return e?r:t}function $x(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function th(e,t){$x(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,i=Ti(e),s=BigInt(e);return{windows:r,windowSize:n,mask:i,maxNumber:o,shiftBy:s}}function zx(e,t,r){let{windowSize:n,mask:o,maxNumber:i,shiftBy:s}=r,a=Number(e&o),c=e>>s;a>n&&(a-=i,c+=oh);let d=t*n,f=d+Math.abs(a)-1,u=a===0,l=a<0,p=t%2!==0;return{nextN:c,offset:f,isZero:u,isNeg:l,isNegF:p,offsetF:d}}function h3(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function y3(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}function nh(e){return Lx.get(e)||1}function Dx(e,t){return{constTimeNegate:eh,hasPrecomputes(r){return nh(r)!==1},unsafeLadder(r,n,o=e.ZERO){let i=r;for(;n>Hx;)n&oh&&(o=o.add(i)),i=i.double(),n>>=oh;return o},precomputeWindow(r,n){let{windows:o,windowSize:i}=th(n,t),s=[],a=r,c=a;for(let d=0;d<o;d++){c=a,s.push(c);for(let f=1;f<i;f++)c=c.add(a),s.push(c);a=c.double()}return s},wNAF(r,n,o){let i=e.ZERO,s=e.BASE,a=th(r,t);for(let c=0;c<a.windows;c++){let{nextN:d,offset:f,isZero:u,isNeg:l,isNegF:p,offsetF:m}=zx(o,c,a);o=d,u?s=s.add(eh(p,n[m])):i=i.add(eh(l,n[f]))}return{p:i,f:s}},wNAFUnsafe(r,n,o,i=e.ZERO){let s=th(r,t);for(let a=0;a<s.windows&&o!==Hx;a++){let{nextN:c,offset:d,isZero:f,isNeg:u}=zx(o,a,s);if(o=c,!f){let l=n[d];i=i.add(u?l.negate():l)}}return i},getPrecomputes(r,n,o){let i=rh.get(n);return i||(i=this.precomputeWindow(n,r),r!==1&&rh.set(n,o(i))),i},wNAFCached(r,n,o){let i=nh(r);return this.wNAF(i,this.getPrecomputes(i,r,o),n)},wNAFCachedUnsafe(r,n,o,i){let s=nh(r);return s===1?this.unsafeLadder(r,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,r,o),n,i)},setWindowSize(r,n){$x(n,t),Lx.set(r,n),rh.delete(r)}}}function qx(e,t,r,n){h3(r,e),y3(n,t);let o=r.length,i=n.length;if(o!==i)throw new Error("arrays of points and scalars must have equal length");let s=e.ZERO,a=Bx(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let d=Ti(c),f=new Array(Number(d)+1).fill(s),u=Math.floor((t.BITS-1)/c)*c,l=s;for(let p=u;p>=0;p-=c){f.fill(s);for(let h=0;h<i;h++){let y=n[h],b=Number(y>>BigInt(p)&d);f[b]=f[b].add(r[h])}let m=s;for(let h=f.length-1,y=s;h>0;h--)y=y.add(f[h]),m=m.add(y);if(l=l.add(m),p!==0)for(let h=0;h<c;h++)l=l.double()}return l}function ih(e){return Mu(e.Fp),Pn(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Jm(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}var Hx,oh,rh,Lx,jx=C(()=>{zc();ks();Hx=BigInt(0),oh=BigInt(1);rh=new WeakMap,Lx=new WeakMap});function Gx(e){e.lowS!==void 0&&Ts("lowS",e.lowS),e.prehash!==void 0&&Ts("prehash",e.prehash)}function b3(e){let t=ih(e);Pn(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:r,Fp:n,a:o}=t;if(r){if(!n.eql(o,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}function sh(e,t){return Is(Qr(e,t))}function g3(e){let t=b3(e),{Fp:r}=t,n=Hc(t.n,t.nBitLength),o=t.toBytes||((g,w,v)=>{let E=w.toAffine();return Rt(Uint8Array.from([4]),r.toBytes(E.x),r.toBytes(E.y))}),i=t.fromBytes||(g=>{let w=g.subarray(1),v=r.fromBytes(w.subarray(0,r.BYTES)),E=r.fromBytes(w.subarray(r.BYTES,2*r.BYTES));return{x:v,y:E}});function s(g){let{a:w,b:v}=t,E=r.sqr(g),B=r.mul(E,g);return r.add(r.add(B,r.mul(g,w)),v)}function a(g,w){let v=r.sqr(w),E=s(g);return r.eql(v,E)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");let c=r.mul(r.pow(t.a,$c),ch),d=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,d)))throw new Error("bad curve params: a or b");function f(g){return Ai(g,Se,t.n)}function u(g){let{allowedPrivateKeyLengths:w,nByteLength:v,wrapPrivateKey:E,n:B}=t;if(w&&typeof g!="bigint"){if(As(g)&&(g=Is(g)),typeof g!="string"||!w.includes(g.length))throw new Error("invalid private key");g=g.padStart(v*2,"0")}let N;try{N=typeof g=="bigint"?g:zt(Je("private key",g,v))}catch{throw new Error("invalid private key, expected hex or "+v+" bytes, got "+typeof g)}return E&&(N=Ve(N,B)),Bn("private key",N,Se,B),N}function l(g){if(!(g instanceof h))throw new Error("ProjectivePoint expected")}let p=Xm((g,w)=>{let{px:v,py:E,pz:B}=g;if(r.eql(B,r.ONE))return{x:v,y:E};let N=g.is0();w==null&&(w=N?r.ONE:r.inv(B));let U=r.mul(v,w),R=r.mul(E,w),T=r.mul(B,w);if(N)return{x:r.ZERO,y:r.ZERO};if(!r.eql(T,r.ONE))throw new Error("invZ was invalid");return{x:U,y:R}}),m=Xm(g=>{if(g.is0()){if(t.allowInfinityPoint&&!r.is0(g.py))return;throw new Error("bad point: ZERO")}let{x:w,y:v}=g.toAffine();if(!r.isValid(w)||!r.isValid(v))throw new Error("bad point: x or y not FE");if(!a(w,v))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class h{constructor(w,v,E){if(w==null||!r.isValid(w))throw new Error("x required");if(v==null||!r.isValid(v)||r.is0(v))throw new Error("y required");if(E==null||!r.isValid(E))throw new Error("z required");this.px=w,this.py=v,this.pz=E,Object.freeze(this)}static fromAffine(w){let{x:v,y:E}=w||{};if(!w||!r.isValid(v)||!r.isValid(E))throw new Error("invalid affine point");if(w instanceof h)throw new Error("projective point not allowed");let B=N=>r.eql(N,r.ZERO);return B(v)&&B(E)?h.ZERO:new h(v,E,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(w){let v=Bs(r,w.map(E=>E.pz));return w.map((E,B)=>E.toAffine(v[B])).map(h.fromAffine)}static fromHex(w){let v=h.fromAffine(i(Je("pointHex",w)));return v.assertValidity(),v}static fromPrivateKey(w){return h.BASE.multiply(u(w))}static msm(w,v){return qx(h,n,w,v)}_setWindowSize(w){x.setWindowSize(this,w)}assertValidity(){m(this)}hasEvenY(){let{y:w}=this.toAffine();if(r.isOdd)return!r.isOdd(w);throw new Error("Field doesn't support isOdd")}equals(w){l(w);let{px:v,py:E,pz:B}=this,{px:N,py:U,pz:R}=w,T=r.eql(r.mul(v,R),r.mul(N,B)),O=r.eql(r.mul(E,R),r.mul(U,B));return T&&O}negate(){return new h(this.px,r.neg(this.py),this.pz)}double(){let{a:w,b:v}=t,E=r.mul(v,$c),{px:B,py:N,pz:U}=this,R=r.ZERO,T=r.ZERO,O=r.ZERO,H=r.mul(B,B),P=r.mul(N,N),_=r.mul(U,U),I=r.mul(B,N);return I=r.add(I,I),O=r.mul(B,U),O=r.add(O,O),R=r.mul(w,O),T=r.mul(E,_),T=r.add(R,T),R=r.sub(P,T),T=r.add(P,T),T=r.mul(R,T),R=r.mul(I,R),O=r.mul(E,O),_=r.mul(w,_),I=r.sub(H,_),I=r.mul(w,I),I=r.add(I,O),O=r.add(H,H),H=r.add(O,H),H=r.add(H,_),H=r.mul(H,I),T=r.add(T,H),_=r.mul(N,U),_=r.add(_,_),H=r.mul(_,I),R=r.sub(R,H),O=r.mul(_,P),O=r.add(O,O),O=r.add(O,O),new h(R,T,O)}add(w){l(w);let{px:v,py:E,pz:B}=this,{px:N,py:U,pz:R}=w,T=r.ZERO,O=r.ZERO,H=r.ZERO,P=t.a,_=r.mul(t.b,$c),I=r.mul(v,N),k=r.mul(E,U),M=r.mul(B,R),$=r.add(v,E),F=r.add(N,U);$=r.mul($,F),F=r.add(I,k),$=r.sub($,F),F=r.add(v,B);let A=r.add(N,R);return F=r.mul(F,A),A=r.add(I,M),F=r.sub(F,A),A=r.add(E,B),T=r.add(U,R),A=r.mul(A,T),T=r.add(k,M),A=r.sub(A,T),H=r.mul(P,F),T=r.mul(_,M),H=r.add(T,H),T=r.sub(k,H),H=r.add(k,H),O=r.mul(T,H),k=r.add(I,I),k=r.add(k,I),M=r.mul(P,M),F=r.mul(_,F),k=r.add(k,M),M=r.sub(I,M),M=r.mul(P,M),F=r.add(F,M),I=r.mul(k,F),O=r.add(O,I),I=r.mul(A,F),T=r.mul($,T),T=r.sub(T,I),I=r.mul($,k),H=r.mul(A,H),H=r.add(H,I),new h(T,O,H)}subtract(w){return this.add(w.negate())}is0(){return this.equals(h.ZERO)}wNAF(w){return x.wNAFCached(this,w,h.normalizeZ)}multiplyUnsafe(w){let{endo:v,n:E}=t;Bn("scalar",w,Tr,E);let B=h.ZERO;if(w===Tr)return B;if(this.is0()||w===Se)return this;if(!v||x.hasPrecomputes(this))return x.wNAFCachedUnsafe(this,w,h.normalizeZ);let{k1neg:N,k1:U,k2neg:R,k2:T}=v.splitScalar(w),O=B,H=B,P=this;for(;U>Tr||T>Tr;)U&Se&&(O=O.add(P)),T&Se&&(H=H.add(P)),P=P.double(),U>>=Se,T>>=Se;return N&&(O=O.negate()),R&&(H=H.negate()),H=new h(r.mul(H.px,v.beta),H.py,H.pz),O.add(H)}multiply(w){let{endo:v,n:E}=t;Bn("scalar",w,Se,E);let B,N;if(v){let{k1neg:U,k1:R,k2neg:T,k2:O}=v.splitScalar(w),{p:H,f:P}=this.wNAF(R),{p:_,f:I}=this.wNAF(O);H=x.constTimeNegate(U,H),_=x.constTimeNegate(T,_),_=new h(r.mul(_.px,v.beta),_.py,_.pz),B=H.add(_),N=P.add(I)}else{let{p:U,f:R}=this.wNAF(w);B=U,N=R}return h.normalizeZ([B,N])[0]}multiplyAndAddUnsafe(w,v,E){let B=h.BASE,N=(R,T)=>T===Tr||T===Se||!R.equals(B)?R.multiplyUnsafe(T):R.multiply(T),U=N(this,v).add(N(w,E));return U.is0()?void 0:U}toAffine(w){return p(this,w)}isTorsionFree(){let{h:w,isTorsionFree:v}=t;if(w===Se)return!0;if(v)return v(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:w,clearCofactor:v}=t;return w===Se?this:v?v(h,this):this.multiplyUnsafe(t.h)}toRawBytes(w=!0){return Ts("isCompressed",w),this.assertValidity(),o(h,this,w)}toHex(w=!0){return Ts("isCompressed",w),Is(this.toRawBytes(w))}}h.BASE=new h(t.Gx,t.Gy,r.ONE),h.ZERO=new h(r.ZERO,r.ONE,r.ZERO);let{endo:y,nBitLength:b}=t,x=Dx(h,y?Math.ceil(b/2):b);return{CURVE:t,ProjectivePoint:h,normPrivateKeyToScalar:u,weierstrassEquation:s,isWithinCurveOrder:f}}function w3(e){let t=ih(e);return Pn(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Vx(e){let t=w3(e),{Fp:r,n,nByteLength:o,nBitLength:i}=t,s=r.BYTES+1,a=2*r.BYTES+1;function c(_){return Ve(_,n)}function d(_){return Fu(_,n)}let{ProjectivePoint:f,normPrivateKeyToScalar:u,weierstrassEquation:l,isWithinCurveOrder:p}=g3({...t,toBytes(_,I,k){let M=I.toAffine(),$=r.toBytes(M.x),F=Rt;return Ts("isCompressed",k),k?F(Uint8Array.from([I.hasEvenY()?2:3]),$):F(Uint8Array.from([4]),$,r.toBytes(M.y))},fromBytes(_){let I=_.length,k=_[0],M=_.subarray(1);if(I===s&&(k===2||k===3)){let $=zt(M);if(!Ai($,Se,r.ORDER))throw new Error("Point is not on curve");let F=l($),A;try{A=r.sqrt(F)}catch(q){let j=q instanceof Error?": "+q.message:"";throw new Error("Point is not on curve"+j)}let z=(A&Se)===Se;return(k&1)===1!==z&&(A=r.neg(A)),{x:$,y:A}}else if(I===a&&k===4){let $=r.fromBytes(M.subarray(0,r.BYTES)),F=r.fromBytes(M.subarray(r.BYTES,2*r.BYTES));return{x:$,y:F}}else{let $=s,F=a;throw new Error("invalid Point, expected length of "+$+", or uncompressed "+F+", got "+I)}}});function m(_){let I=n>>Se;return _>I}function h(_){return m(_)?c(-_):_}let y=(_,I,k)=>zt(_.slice(I,k));class b{constructor(I,k,M){Bn("r",I,Se,n),Bn("s",k,Se,n),this.r=I,this.s=k,M!=null&&(this.recovery=M),Object.freeze(this)}static fromCompact(I){let k=o;return I=Je("compactSignature",I,k*2),new b(y(I,0,k),y(I,k,2*k))}static fromDER(I){let{r:k,s:M}=Rn.toSig(Je("DER",I));return new b(k,M)}assertValidity(){}addRecoveryBit(I){return new b(this.r,this.s,I)}recoverPublicKey(I){let{r:k,s:M,recovery:$}=this,F=B(Je("msgHash",I));if($==null||![0,1,2,3].includes($))throw new Error("recovery id invalid");let A=$===2||$===3?k+t.n:k;if(A>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let z=($&1)===0?"02":"03",D=f.fromHex(z+sh(A,r.BYTES)),q=d(A),j=c(-F*q),K=c(M*q),W=f.BASE.multiplyAndAddUnsafe(D,j,K);if(!W)throw new Error("point at infinify");return W.assertValidity(),W}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new b(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Mc(this.toDERHex())}toDERHex(){return Rn.hexFromSig(this)}toCompactRawBytes(){return Mc(this.toCompactHex())}toCompactHex(){let I=o;return sh(this.r,I)+sh(this.s,I)}}let x={isValidPrivateKey(_){try{return u(_),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let _=Qm(t.n);return Mx(t.randomBytes(_),t.n)},precompute(_=8,I=f.BASE){return I._setWindowSize(_),I.multiply(BigInt(3)),I}};function g(_,I=!0){return f.fromPrivateKey(_).toRawBytes(I)}function w(_){if(typeof _=="bigint")return!1;if(_ instanceof f)return!0;let k=Je("key",_).length,M=r.BYTES,$=M+1,F=2*M+1;if(!(t.allowedPrivateKeyLengths||o===$))return k===$||k===F}function v(_,I,k=!0){if(w(_)===!0)throw new Error("first arg must be private key");if(w(I)===!1)throw new Error("second arg must be public key");return f.fromHex(I).multiply(u(_)).toRawBytes(k)}let E=t.bits2int||function(_){if(_.length>8192)throw new Error("input is too large");let I=zt(_),k=_.length*8-i;return k>0?I>>BigInt(k):I},B=t.bits2int_modN||function(_){return c(E(_))},N=Ti(i);function U(_){return Bn("num < 2^"+i,_,Tr,N),Qr(_,o)}function R(_,I,k=T){if(["recovered","canonical"].some(te=>te in k))throw new Error("sign() legacy options not supported");let{hash:M,randomBytes:$}=t,{lowS:F,prehash:A,extraEntropy:z}=k;F==null&&(F=!0),_=Je("msgHash",_),Gx(k),A&&(_=Je("prehashed msgHash",M(_)));let D=B(_),q=u(I),j=[U(q),U(D)];if(z!=null&&z!==!1){let te=z===!0?$(r.BYTES):z;j.push(Je("extraEntropy",te))}let K=Rt(...j),W=D;function Z(te){let J=E(te);if(!p(J))return;let de=d(J),ue=f.BASE.multiply(J).toAffine(),me=c(ue.x);if(me===Tr)return;let Ne=c(de*c(W+me*q));if(Ne===Tr)return;let fe=(ue.x===me?0:2)|Number(ue.y&Se),we=Ne;return F&&m(Ne)&&(we=h(Ne),fe^=1),new b(me,we,fe)}return{seed:K,k2sig:Z}}let T={lowS:t.lowS,prehash:!1},O={lowS:t.lowS,prehash:!1};function H(_,I,k=T){let{seed:M,k2sig:$}=R(_,I,k),F=t;return Px(F.hash.outputLen,F.nByteLength,F.hmac)(M,$)}f.BASE._setWindowSize(8);function P(_,I,k,M=O){let $=_;I=Je("msgHash",I),k=Je("publicKey",k);let{lowS:F,prehash:A,format:z}=M;if(Gx(M),"strict"in M)throw new Error("options.strict was renamed to lowS");if(z!==void 0&&z!=="compact"&&z!=="der")throw new Error("format must be compact or der");let D=typeof $=="string"||As($),q=!D&&!z&&typeof $=="object"&&$!==null&&typeof $.r=="bigint"&&typeof $.s=="bigint";if(!D&&!q)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let j,K;try{if(q&&(j=new b($.r,$.s)),D){try{z!=="compact"&&(j=b.fromDER($))}catch(fe){if(!(fe instanceof Rn.Err))throw fe}!j&&z!=="der"&&(j=b.fromCompact($))}K=f.fromHex(k)}catch{return!1}if(!j||F&&j.hasHighS())return!1;A&&(I=t.hash(I));let{r:W,s:Z}=j,te=B(I),J=d(Z),de=c(te*J),ue=c(W*J),me=f.BASE.multiplyAndAddUnsafe(K,de,ue)?.toAffine();return me?c(me.x)===W:!1}return{CURVE:t,getPublicKey:g,getSharedSecret:v,sign:H,verify:P,ProjectivePoint:f,Signature:b,utils:x}}function x3(e,t){let r=e.ORDER,n=Tr;for(let m=r-Se;m%Ao===Tr;m/=Ao)n+=Se;let o=n,i=Ao<<o-Se-Se,s=i*Ao,a=(r-Se)/s,c=(a-Se)/Ao,d=s-Se,f=i,u=e.pow(t,a),l=e.pow(t,(a+Se)/Ao),p=(m,h)=>{let y=u,b=e.pow(h,d),x=e.sqr(b);x=e.mul(x,h);let g=e.mul(m,x);g=e.pow(g,c),g=e.mul(g,b),b=e.mul(g,h),x=e.mul(g,m);let w=e.mul(x,b);g=e.pow(w,f);let v=e.eql(g,e.ONE);b=e.mul(x,l),g=e.mul(w,y),x=e.cmov(b,x,v),w=e.cmov(g,w,v);for(let E=o;E>Se;E--){let B=E-Ao;B=Ao<<B-Se;let N=e.pow(w,B),U=e.eql(N,e.ONE);b=e.mul(x,y),y=e.mul(y,y),N=e.mul(w,y),x=e.cmov(b,x,U),w=e.cmov(N,w,U)}return{isValid:v,value:x}};if(e.ORDER%ch===$c){let m=(e.ORDER-$c)/ch,h=e.sqrt(e.neg(t));p=(y,b)=>{let x=e.sqr(b),g=e.mul(y,b);x=e.mul(x,g);let w=e.pow(x,m);w=e.mul(w,g);let v=e.mul(w,h),E=e.mul(e.sqr(w),b),B=e.eql(E,y),N=e.cmov(v,w,B);return{isValid:B,value:N}}}return p}function Kx(e,t){if(Mu(e),!e.isValid(t.A)||!e.isValid(t.B)||!e.isValid(t.Z))throw new Error("mapToCurveSimpleSWU: invalid opts");let r=x3(e,t.Z);if(!e.isOdd)throw new Error("Fp.isOdd is not implemented!");return n=>{let o,i,s,a,c,d,f,u;o=e.sqr(n),o=e.mul(o,t.Z),i=e.sqr(o),i=e.add(i,o),s=e.add(i,e.ONE),s=e.mul(s,t.B),a=e.cmov(t.Z,e.neg(i),!e.eql(i,e.ZERO)),a=e.mul(a,t.A),i=e.sqr(s),d=e.sqr(a),c=e.mul(d,t.A),i=e.add(i,c),i=e.mul(i,s),d=e.mul(d,a),c=e.mul(d,t.B),i=e.add(i,c),f=e.mul(o,s);let{isValid:l,value:p}=r(i,d);u=e.mul(o,n),u=e.mul(u,p),f=e.cmov(f,s,l),u=e.cmov(u,p,l);let m=e.isOdd(n)===e.isOdd(u);u=e.cmov(e.neg(u),u,m);let h=Bs(e,[a],!0)[0];return f=e.mul(f,h),{x:f,y:u}}}var ah,Rn,Tr,Se,Ao,$c,ch,dh=C(()=>{jx();zc();ks();ah=class extends Error{constructor(t=""){super(t)}},Rn={Err:ah,_tlv:{encode:(e,t)=>{let{Err:r}=Rn;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=Fc(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let i=n>127?Fc(o.length/2|128):"";return Fc(e)+i+o+t},decode(e,t){let{Err:r}=Rn,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let d=t.subarray(n,n+c);if(d.length!==c)throw new r("tlv.decode: length bytes not complete");if(d[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let f of d)s=s<<8|f;if(n+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(e){let{Err:t}=Rn;if(e<Tr)throw new t("integer: negative integers are not allowed");let r=Fc(e);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=Rn;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return zt(e)}},toSig(e){let{Err:t,_int:r,_tlv:n}=Rn,o=Je("signature",e),{v:i,l:s}=n.decode(48,o);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:d,l:f}=n.decode(2,c);if(f.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(d)}},hexFromSig(e){let{_tlv:t,_int:r}=Rn,n=t.encode(2,r.encode(e.r)),o=t.encode(2,r.encode(e.s)),i=n+o;return t.encode(48,i)}};Tr=BigInt(0),Se=BigInt(1),Ao=BigInt(2),$c=BigInt(3),ch=BigInt(4)});function v3(e){return{hash:e,hmac:(t,...r)=>jm(e,t,R1(...r)),randomBytes:ou}}function Wx(e,t){let r=n=>Vx({...e,...v3(n)});return{...r(t),create:r}}var Zx=C(()=>{_x();xo();dh();});function To(e,t){if(Lc(e),Lc(t),e<0||e>=1<<8*t)throw new Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let n=t-1;n>=0;n--)r[n]=e&255,e>>>=8;return new Uint8Array(r)}function E3(e,t){let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e[n]^t[n];return r}function Lc(e){if(!Number.isSafeInteger(e))throw new Error("number expected")}function _3(e,t,r,n){kn(e),kn(t),Lc(r),t.length>255&&(t=n(Rt(Nu("H2C-OVERSIZE-DST-"),t)));let{outputLen:o,blockLen:i}=n,s=Math.ceil(r/o);if(r>65535||s>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=Rt(t,To(t.length,1)),c=To(0,i),d=To(r,2),f=new Array(s),u=n(Rt(c,e,d,To(0,1),a));f[0]=n(Rt(u,To(1,1),a));for(let p=1;p<=s;p++){let m=[E3(u,f[p-1]),To(p+1,1),a];f[p]=n(Rt(...m))}return Rt(...f).slice(0,r)}function A3(e,t,r,n,o){if(kn(e),kn(t),Lc(r),t.length>255){let i=Math.ceil(2*n/8);t=o.create({dkLen:i}).update(Nu("H2C-OVERSIZE-DST-")).update(t).digest()}if(r>65535||t.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return o.create({dkLen:r}).update(e).update(To(r,2)).update(t).update(To(t.length,1)).digest()}function Yx(e,t,r){Pn(r,{DST:"stringOrUint8Array",p:"bigint",m:"isSafeInteger",k:"isSafeInteger",hash:"hash"});let{p:n,k:o,m:i,hash:s,expand:a,DST:c}=r;kn(e),Lc(t);let d=typeof c=="string"?Nu(c):c,f=n.toString(2).length,u=Math.ceil((f+o)/8),l=t*i*u,p;if(a==="xmd")p=_3(e,d,l,s);else if(a==="xof")p=A3(e,d,l,o,s);else if(a==="_internal_pass")p=e;else throw new Error('expand must be "xmd" or "xof"');let m=new Array(t);for(let h=0;h<t;h++){let y=new Array(i);for(let b=0;b<i;b++){let x=u*(b+h*i),g=p.subarray(x,x+u);y[b]=Ve(S3(g),n)}m[h]=y}return m}function Xx(e,t){let r=t.map(n=>Array.from(n).reverse());return(n,o)=>{let[i,s,a,c]=r.map(u=>u.reduce((l,p)=>e.add(e.mul(l,n),p))),[d,f]=Bs(e,[s,c],!0);return n=e.mul(i,d),o=e.mul(o,e.mul(a,f)),{x:n,y:o}}}function Jx(e,t,r){if(typeof t!="function")throw new Error("mapToCurve() must be defined");function n(i){return e.fromAffine(t(i))}function o(i){let s=i.clearCofactor();return s.equals(e.ZERO)?e.ZERO:(s.assertValidity(),s)}return{defaults:r,hashToCurve(i,s){let a=Yx(i,2,{...r,DST:r.DST,...s}),c=n(a[0]),d=n(a[1]);return o(c.add(d))},encodeToCurve(i,s){let a=Yx(i,1,{...r,DST:r.encodeDST,...s});return o(n(a[0]))},mapToCurve(i){if(!Array.isArray(i))throw new Error("expected array of bigints");for(let s of i)if(typeof s!="bigint")throw new Error("expected array of bigints");return o(n(i))}}}var S3,Qx=C(()=>{zc();ks();S3=zt});var s2={};By(s2,{encodeToCurve:()=>C3,hashToCurve:()=>O3,schnorr:()=>B3,secp256k1:()=>Gc,secp256k1_hasher:()=>yh});function r2(e){let t=jc,r=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),d=e*e*e%t,f=d*d*e%t,u=Xt(f,r,t)*f%t,l=Xt(u,r,t)*f%t,p=Xt(l,zu,t)*d%t,m=Xt(p,o,t)*p%t,h=Xt(m,i,t)*m%t,y=Xt(h,a,t)*h%t,b=Xt(y,c,t)*y%t,x=Xt(b,a,t)*h%t,g=Xt(x,r,t)*f%t,w=Xt(g,s,t)*m%t,v=Xt(w,n,t)*d%t,E=Xt(v,zu,t);if(!Io.eql(Io.sqr(E),e))throw new Error("Cannot find square root");return E}function $u(e,...t){let r=t2[e];if(r===void 0){let n=_i(Uint8Array.from(e,o=>o.charCodeAt(0)));r=Rt(n,n),t2[e]=r}return _i(Rt(r,...t))}function lh(e){let t=Gc.utils.normPrivateKeyToScalar(e),r=hh.fromPrivateKey(t);return{scalar:r.hasEvenY()?t:qc(-t),bytes:mh(r)}}function n2(e){Bn("x",e,Dc,jc);let t=fh(e*e),r=fh(t*e+BigInt(7)),n=r2(r);n%zu!==ph&&(n=fh(-n));let o=new hh(e,n,Dc);return o.assertValidity(),o}function o2(...e){return qc(Ps($u("BIP0340/challenge",...e)))}function I3(e){return lh(e).bytes}function k3(e,t,r=ou(32)){let n=Je("message",e),{bytes:o,scalar:i}=lh(t),s=Je("auxRand",r,32),a=uh(i^Ps($u("BIP0340/aux",s))),c=$u("BIP0340/nonce",a,o,n),d=qc(Ps(c));if(d===ph)throw new Error("sign failed: k is zero");let{bytes:f,scalar:u}=lh(d),l=o2(f,o,n),p=new Uint8Array(64);if(p.set(f,0),p.set(uh(qc(u+l*i)),32),!i2(p,n,o))throw new Error("sign: Invalid signature produced");return p}function i2(e,t,r){let n=Je("signature",e,64),o=Je("message",t),i=Je("publicKey",r,32);try{let s=n2(Ps(i)),a=Ps(n.subarray(0,32));if(!Ai(a,Dc,jc))return!1;let c=Ps(n.subarray(32,64));if(!Ai(c,Dc,Hu))return!1;let d=o2(uh(a),mh(s),o),f=T3(s,c,qc(-d));return!(!f||!f.hasEvenY()||f.toAffine().x!==a)}catch{return!1}}var jc,Hu,ph,Dc,zu,e2,Io,Gc,t2,mh,uh,fh,qc,hh,T3,Ps,B3,P3,R3,yh,O3,C3,a2=C(()=>{qm();xo();Zx();Qx();zc();ks();dh();jc=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Hu=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),ph=BigInt(0),Dc=BigInt(1),zu=BigInt(2),e2=(e,t)=>(e+t/zu)/t;Io=Hc(jc,void 0,void 0,{sqrt:r2}),Gc=Wx({a:ph,b:BigInt(7),Fp:Io,n:Hu,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=Hu,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Dc*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,s=BigInt("0x100000000000000000000000000000000"),a=e2(i*e,t),c=e2(-n*e,t),d=Ve(e-a*r-c*o,t),f=Ve(-a*n-c*i,t),u=d>s,l=f>s;if(u&&(d=t-d),l&&(f=t-f),d>s||f>s)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:u,k1:d,k2neg:l,k2:f}}}},_i),t2={};mh=e=>e.toRawBytes(!0).slice(1),uh=e=>Qr(e,32),fh=e=>Ve(e,jc),qc=e=>Ve(e,Hu),hh=Gc.ProjectivePoint,T3=(e,t,r)=>hh.BASE.multiplyAndAddUnsafe(e,t,r);Ps=zt;B3={getPublicKey:I3,sign:k3,verify:i2,utils:{randomPrivateKey:Gc.utils.randomPrivateKey,lift_x:n2,pointToBytes:mh,numberToBytesBE:Qr,bytesToNumberBE:zt,taggedHash:$u,mod:Ve}},P3=Xx(Io,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),R3=Kx(Io,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:Io.create(BigInt("-11"))}),yh=Jx(Gc.ProjectivePoint,e=>{let{x:t,y:r}=R3(Io.create(e[0]));return P3(t,r)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:Io.ORDER,m:1,k:128,expand:"xmd",hash:_i}),O3=yh.hashToCurve,C3=yh.encodeToCurve});async function d2({hash:e,signature:t}){let r=dt(e)?e:ht(e),{secp256k1:n}=await Promise.resolve().then(()=>(a2(),s2));return`0x${(()=>{if(typeof t=="object"&&"r"in t&&"s"in t){let{r:d,s:f,v:u,yParity:l}=t,p=Number(l??u),m=c2(p);return new n.Signature(De(d),De(f)).addRecoveryBit(m)}let s=dt(t)?t:ht(t);if(ge(s)!==65)throw new Error("invalid signature length");let a=Xe(`0x${s.slice(130)}`),c=c2(a);return n.Signature.fromCompact(s.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function c2(e){if(e===0||e===1)return e;if(e===27)return 0;if(e===28)return 1;throw new Error("Invalid yParityOrV value")}var f2=C(()=>{xn();wr();Bt();xe()});async function u2({hash:e,signature:t}){return L1(await d2({hash:e,signature:t}))}var l2=C(()=>{D1();f2()});async function Rs(e){let{authorization:t,signature:r}=e;return u2({hash:wx(t),signature:r??t})}var Lu=C(()=>{l2();xx()});function ju(e,t=0){if(!Number.isInteger(t)||t<0)throw new qu({decimals:t});let r=e.toString(),n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(t,"0");let[o,i]=[r.slice(0,r.length-t),r.slice(r.length-t)];return i=i.replace(/(0+)$/,""),`${n?"-":""}${o||"0"}${i?`.${i}`:""}`}function p2(e,t="wei"){return ju(e,Du.ether-Du[t])}function m2(e,t="wei"){return ju(e,Du.gwei-Du[t])}function h2(e,t=0){if(!Number.isInteger(t)||t<0)throw new qu({decimals:t});if(!/^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/.test(e))throw new bh({value:e});let[r="",n="0"]=e.split("."),o=r.startsWith("-");if(o&&(r=r.slice(1)),r===""&&(r="0"),n=n.replace(/(0+)$/,""),t===0)n.length>0&&Number.parseInt(n[0],10)>=5&&(r=`${BigInt(r)+1n}`),n="";else if(n.length>t){let i=n.slice(0,t);if(Number.parseInt(n.slice(t,t+1),10)>=5){let a=U3(i);a.length>t?(n=a.slice(1),r=`${BigInt(r)+1n}`):n=a}else n=i}else n=n.padEnd(t,"0");return BigInt(`${o?"-":""}${r}${n}`)}function U3(e){let t=e.split(""),r=t.length-1;for(;r>=0;){let n=Number.parseInt(t[r],10)+1;if(n<10)return t[r]=String(n),t.join("");t[r]="0",r--}return`1${t.join("")}`}var Du,bh,qu,Vc=C(()=>{Du={wei:0,gwei:9,szabo:12,finney:15,ether:18};bh=class extends Error{constructor({value:t}){super(`Value \`${t}\` is not a valid decimal number.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Value.InvalidDecimalNumberError"})}},qu=class extends Error{constructor({decimals:t}){super(`\`decimals\` must be a non-negative integer. Got \`${t}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Value.InvalidDecimalsError"})}}});function Os(e,t="wei"){return p2(e,t)}var Vu=C(()=>{Vc()});function ot(e,t="wei"){return m2(e,t)}var Cs=C(()=>{Vc()});function Bi(e){let t=Object.entries(e).map(([n,o])=>o===void 0||o===!1?null:[n,o]).filter(Boolean),r=t.reduce((n,[o])=>Math.max(n,o.length),0);return t.map(([n,o])=>` ${`${n}:`.padEnd(r+1)} ${o}`).join(`
22
+ `)}var Us,Ku,Wu,Zu,Yu,Ns,Fs,ki,Xu,$t=C(()=>{Vu();Cs();le();Us=class extends L{constructor({filledNonce:t,requestedNonce:r}){super("The filled transaction nonce does not match the requested nonce.",{metaMessages:[`Requested Nonce: ${r}`,`Filled Nonce: ${t}`],name:"FeePayerNonceMismatchError"})}},Ku=class extends L{constructor({v:t}){super(`Invalid \`v\` value "${t}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}},Wu=class extends L{constructor({transaction:t}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",Bi(t),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}},Zu=class extends L{constructor({storageKey:t}){super(`Size for storage key "${t}" is invalid. Expected 32 bytes. Got ${Math.floor((t.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}},Yu=class extends L{constructor(t,{account:r,docsPath:n,chain:o,data:i,gas:s,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:d,nonce:f,to:u,value:l}){let p=Bi({chain:o&&`${o?.name} (id: ${o?.id})`,from:r?.address,to:u,value:typeof l<"u"&&`${Os(l)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:i,gas:s,gasPrice:typeof a<"u"&&`${ot(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${ot(c)} gwei`,maxPriorityFeePerGas:typeof d<"u"&&`${ot(d)} gwei`,nonce:f});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Request Arguments:",p].filter(Boolean),name:"TransactionExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}},Ns=class extends L{constructor({blockHash:t,blockNumber:r,blockTag:n,hash:o,index:i}){let s="Transaction";n&&i!==void 0&&(s=`Transaction at block time "${n}" at index "${i}"`),t&&i!==void 0&&(s=`Transaction at block hash "${t}" at index "${i}"`),r&&i!==void 0&&(s=`Transaction at block number "${r}" at index "${i}"`),o&&(s=`Transaction with hash "${o}"`),super(`${s} could not be found.`,{name:"TransactionNotFoundError"})}},Fs=class extends L{constructor({hash:t}){super(`Transaction receipt with hash "${t}" could not be found. The Transaction may not be processed on a block yet.`,{name:"TransactionReceiptNotFoundError"})}},ki=class extends L{constructor({receipt:t}){super(`Transaction with hash "${t.transactionHash}" reverted.`,{metaMessages:['The receipt marked the transaction as "reverted". This could mean that the function on the contract you are trying to call threw an error.'," ","You can attempt to extract the revert reason by:","- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract","- using the `call` Action with raw `data`"],name:"TransactionReceiptRevertedError"}),Object.defineProperty(this,"receipt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.receipt=t}},Xu=class extends L{constructor({hash:t}){super(`Timed out while waiting for transaction with hash "${t}" to be confirmed.`,{name:"WaitForTransactionReceiptTimeoutError"})}}});function Ms(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(i=>Pt(i)):e.blobs,o=[];for(let i of n)o.push(Uint8Array.from(t.blobToKzgCommitment(i)));return r==="bytes"?o:o.map(i=>Me(i))}var Ju=C(()=>{rr();xe()});function Hs(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(s=>Pt(s)):e.blobs,o=typeof e.commitments[0]=="string"?e.commitments.map(s=>Pt(s)):e.commitments,i=[];for(let s=0;s<n.length;s++){let a=n[s],c=o[s];i.push(Uint8Array.from(t.computeBlobKzgProof(a,c)))}return r==="bytes"?i:i.map(s=>Me(s))}var Qu=C(()=>{rr();xe()});var y2,b2=C(()=>{qm();y2=_i});function g2(e,t){let r=t||"hex",n=y2(dt(e,{strict:!1})?go(e):e);return r==="bytes"?n:ht(n)}var w2=C(()=>{b2();xn();rr();xe()});function x2(e){let{commitment:t,version:r=1}=e,n=e.to??(typeof t=="string"?"hex":"bytes"),o=g2(t,"bytes");return o.set([r],0),n==="bytes"?o:Me(o)}var v2=C(()=>{xe();w2()});function el(e){let{commitments:t,version:r}=e,n=e.to??(typeof t[0]=="string"?"hex":"bytes"),o=[];for(let i of t)o.push(x2({commitment:i,to:n,version:r}));return o}var gh=C(()=>{v2()});var tl,zs,rl,nl,wh=C(()=>{le();tl=class extends L{constructor({maxSize:t,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${t} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}},zs=class extends L{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}},rl=class extends L{constructor({hash:t,size:r}){super(`Versioned hash "${t}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}},nl=class extends L{constructor({hash:t,version:r}){super(`Versioned hash "${t}" version is invalid.`,{metaMessages:[`Expected: ${1}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}});function S2(e){let t=e.to??(typeof e.data=="string"?"hex":"bytes"),r=typeof e.data=="string"?Pt(e.data):e.data,n=ge(r);if(!n)throw new zs;if(n>761855)throw new tl({maxSize:761855,size:n});let o=[],i=!0,s=0;for(;i;){let a=xs(new Uint8Array(131072)),c=0;for(;c<4096;){let d=r.slice(s,s+31);if(a.pushByte(0),a.pushBytes(d),d.length<31){a.pushByte(128),i=!1;break}c++,s+=31}o.push(a)}return t==="bytes"?o.map(a=>a.bytes):o.map(a=>Me(a.bytes))}var E2=C(()=>{wh();xu();wr();rr();xe()});function ol(e){let{data:t,kzg:r,to:n}=e,o=e.blobs??S2({data:t,to:n}),i=e.commitments??Ms({blobs:o,kzg:r,to:n}),s=e.proofs??Hs({blobs:o,commitments:i,kzg:r,to:n}),a=[];for(let c=0;c<o.length;c++)a.push({blob:o[c],commitment:i[c],proof:s[c]});return a}var xh=C(()=>{Ju();Qu();E2()});var sO,aO,cO,dO,fO,uO,lO,pO,mO,hO,yO,bO,gO,wO,xO,vO,SO,EO,_O,AO,TO,IO,kO,BO,PO,RO,OO,CO,UO,NO,FO,MO,HO,zO,$O,LO,DO,qO,jO,GO,VO,KO,WO,ZO,YO,XO,JO,QO,eC,tC,rC,nC,oC,iC,sC,aC,cC,dC,fC,uC,lC,pC,mC,hC,yC,bC,gC,wC,xC,vC,SC,EC,_C,AC,TC,IC,kC,BC,PC,RC,OC,CC,UC,NC,FC,MC,HC,zC,$C,LC,DC,qC,jC,GC,VC,$s,vh=C(()=>{sO=2n**(8n-1n)-1n,aO=2n**(16n-1n)-1n,cO=2n**(24n-1n)-1n,dO=2n**(32n-1n)-1n,fO=2n**(40n-1n)-1n,uO=2n**(48n-1n)-1n,lO=2n**(56n-1n)-1n,pO=2n**(64n-1n)-1n,mO=2n**(72n-1n)-1n,hO=2n**(80n-1n)-1n,yO=2n**(88n-1n)-1n,bO=2n**(96n-1n)-1n,gO=2n**(104n-1n)-1n,wO=2n**(112n-1n)-1n,xO=2n**(120n-1n)-1n,vO=2n**(128n-1n)-1n,SO=2n**(136n-1n)-1n,EO=2n**(144n-1n)-1n,_O=2n**(152n-1n)-1n,AO=2n**(160n-1n)-1n,TO=2n**(168n-1n)-1n,IO=2n**(176n-1n)-1n,kO=2n**(184n-1n)-1n,BO=2n**(192n-1n)-1n,PO=2n**(200n-1n)-1n,RO=2n**(208n-1n)-1n,OO=2n**(216n-1n)-1n,CO=2n**(224n-1n)-1n,UO=2n**(232n-1n)-1n,NO=2n**(240n-1n)-1n,FO=2n**(248n-1n)-1n,MO=2n**(256n-1n)-1n,HO=-(2n**(8n-1n)),zO=-(2n**(16n-1n)),$O=-(2n**(24n-1n)),LO=-(2n**(32n-1n)),DO=-(2n**(40n-1n)),qO=-(2n**(48n-1n)),jO=-(2n**(56n-1n)),GO=-(2n**(64n-1n)),VO=-(2n**(72n-1n)),KO=-(2n**(80n-1n)),WO=-(2n**(88n-1n)),ZO=-(2n**(96n-1n)),YO=-(2n**(104n-1n)),XO=-(2n**(112n-1n)),JO=-(2n**(120n-1n)),QO=-(2n**(128n-1n)),eC=-(2n**(136n-1n)),tC=-(2n**(144n-1n)),rC=-(2n**(152n-1n)),nC=-(2n**(160n-1n)),oC=-(2n**(168n-1n)),iC=-(2n**(176n-1n)),sC=-(2n**(184n-1n)),aC=-(2n**(192n-1n)),cC=-(2n**(200n-1n)),dC=-(2n**(208n-1n)),fC=-(2n**(216n-1n)),uC=-(2n**(224n-1n)),lC=-(2n**(232n-1n)),pC=-(2n**(240n-1n)),mC=-(2n**(248n-1n)),hC=-(2n**(256n-1n)),yC=2n**8n-1n,bC=2n**16n-1n,gC=2n**24n-1n,wC=2n**32n-1n,xC=2n**40n-1n,vC=2n**48n-1n,SC=2n**56n-1n,EC=2n**64n-1n,_C=2n**72n-1n,AC=2n**80n-1n,TC=2n**88n-1n,IC=2n**96n-1n,kC=2n**104n-1n,BC=2n**112n-1n,PC=2n**120n-1n,RC=2n**128n-1n,OC=2n**136n-1n,CC=2n**144n-1n,UC=2n**152n-1n,NC=2n**160n-1n,FC=2n**168n-1n,MC=2n**176n-1n,HC=2n**184n-1n,zC=2n**192n-1n,$C=2n**200n-1n,LC=2n**208n-1n,DC=2n**216n-1n,qC=2n**224n-1n,jC=2n**232n-1n,GC=2n**240n-1n,VC=2n**248n-1n,$s=2n**256n-1n});var Pi,il,sl,Kc,Ri,Wc=C(()=>{le();Pi=class extends L{constructor({blockNumber:t,chain:r,contract:n}){super(`Chain "${r.name}" does not support contract "${n.name}".`,{metaMessages:["This could be due to any of the following:",...t&&n.blockCreated&&n.blockCreated>t?[`- The contract "${n.name}" was not deployed until block ${n.blockCreated} (current block ${t}).`]:[`- The chain does not have the contract "${n.name}" configured.`]],name:"ChainDoesNotSupportContract"})}},il=class extends L{constructor({chain:t,currentChainId:r}){super(`The current chain of the wallet (id: ${r}) does not match the target chain for the transaction (id: ${t.id} \u2013 ${t.name}).`,{metaMessages:[`Current Chain ID: ${r}`,`Expected Chain ID: ${t.id} \u2013 ${t.name}`],name:"ChainMismatchError"})}},sl=class extends L{constructor(){super(["No chain was provided to the request.","Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient."].join(`
23
+ `),{name:"ChainNotFoundError"})}},Kc=class extends L{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}},Ri=class extends L{constructor({chainId:t}){super(typeof t=="number"?`Chain ID "${t}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}});var On,ir,Ls,Ds,qs,js,Gs,Vs,Ks,Ws,en,tn,Oi=C(()=>{Cs();le();On=class extends L{constructor({cause:t,message:r}={}){let n=r?.replace("execution reverted: ","")?.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:t,name:"ExecutionRevertedError"})}};Object.defineProperty(On,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(On,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});ir=class extends L{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${ot(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:t,name:"FeeCapTooHighError"})}};Object.defineProperty(ir,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});Ls=class extends L{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${ot(r)}`:""} gwei) cannot be lower than the block base fee.`,{cause:t,name:"FeeCapTooLowError"})}};Object.defineProperty(Ls,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});Ds=class extends L{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}is higher than the next one expected.`,{cause:t,name:"NonceTooHighError"})}};Object.defineProperty(Ds,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});qs=class extends L{constructor({cause:t,nonce:r}={}){super([`Nonce provided for the transaction ${r?`(${r}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(`
24
+ `),{cause:t,name:"NonceTooLowError"})}};Object.defineProperty(qs,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});js=class extends L{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}exceeds the maximum allowed nonce.`,{cause:t,name:"NonceMaxValueError"})}};Object.defineProperty(js,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});Gs=class extends L{constructor({cause:t}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
25
+ `),{cause:t,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}};Object.defineProperty(Gs,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});Vs=class extends L{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:t,name:"IntrinsicGasTooHighError"})}};Object.defineProperty(Vs,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});Ks=class extends L{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction is too low.`,{cause:t,name:"IntrinsicGasTooLowError"})}};Object.defineProperty(Ks,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});Ws=class extends L{constructor({cause:t}){super("The transaction type is not supported for this chain.",{cause:t,name:"TransactionTypeNotSupportedError"})}};Object.defineProperty(Ws,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});en=class extends L{constructor({cause:t,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${r?` = ${ot(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${ot(n)} gwei`:""}).`].join(`
26
+ `),{cause:t,name:"TipAboveFeeCapError"})}};Object.defineProperty(en,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});tn=class extends L{constructor({cause:t}){super(`An error occurred while executing: ${t?.shortMessage}`,{cause:t,name:"UnknownNodeError"})}}});function _2(e){let{authorizationList:t}=e;if(t)for(let r of t){let{chainId:n}=r,o=r.address;if(!pe(o))throw new Ce({address:o});if(n<0)throw new Ri({chainId:n})}al(e)}function A2(e){let{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new zs;for(let r of t){let n=ge(r),o=Xe(nr(r,0,1));if(n!==32)throw new rl({hash:r,size:n});if(o!==1)throw new nl({hash:r,version:o})}}al(e)}function al(e){let{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:o}=e;if(t<=0)throw new Ri({chainId:t});if(o&&!pe(o))throw new Ce({address:o});if(n&&n>$s)throw new ir({maxFeePerGas:n});if(r&&n&&r>n)throw new en({maxFeePerGas:n,maxPriorityFeePerGas:r})}function T2(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:i}=e;if(t<=0)throw new Ri({chainId:t});if(i&&!pe(i))throw new Ce({address:i});if(r||o)throw new L("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>$s)throw new ir({maxFeePerGas:n})}function I2(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:i}=e;if(i&&!pe(i))throw new Ce({address:i});if(typeof t<"u"&&t<=0)throw new Ri({chainId:t});if(r||o)throw new L("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>$s)throw new ir({maxFeePerGas:n})}var k2=C(()=>{vh();Gr();le();wh();Wc();Oi();Zt();wr();Eo();Bt()});function cl(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u")return typeof e.accessList<"u"?"eip2930":"legacy";throw new Wu({transaction:e})}var Sh=C(()=>{$t()});function Zc(e){if(!e||e.length===0)return[];let t=[];for(let r=0;r<e.length;r++){let{address:n,storageKeys:o}=e[r];for(let i=0;i<o.length;i++)if(o[i].length-2!==64)throw new Zu({storageKey:o[i]});if(!pe(n,{strict:!1}))throw new Ce({address:n});t.push([n,o])}return t}var B2=C(()=>{Gr();$t();Zt()});function P2(e,t){let r=cl(e);return r==="eip1559"?z3(e,t):r==="eip2930"?$3(e,t):r==="eip4844"?H3(e,t):r==="eip7702"?M3(e,t):L3(e,t)}function M3(e,t){let{authorizationList:r,chainId:n,gas:o,nonce:i,to:s,value:a,maxFeePerGas:c,maxPriorityFeePerGas:d,accessList:f,data:u}=e;_2(e);let l=Zc(f),p=R2(r);return Le(["0x04",Ar([V(n),i?V(i):"0x",d?V(d):"0x",c?V(c):"0x",o?V(o):"0x",s??"0x",a?V(a):"0x",u??"0x",l,p,...Zs(e,t)])])}function H3(e,t){let{chainId:r,gas:n,nonce:o,to:i,value:s,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:d,accessList:f,data:u}=e;A2(e);let l=e.blobVersionedHashes,p=e.sidecars;if(e.blobs&&(typeof l>"u"||typeof p>"u")){let g=typeof e.blobs[0]=="string"?e.blobs:e.blobs.map(E=>Me(E)),w=e.kzg,v=Ms({blobs:g,kzg:w});if(typeof l>"u"&&(l=el({commitments:v})),typeof p>"u"){let E=Hs({blobs:g,commitments:v,kzg:w});p=ol({blobs:g,commitments:v,proofs:E})}}let m=Zc(f),h=[V(r),o?V(o):"0x",d?V(d):"0x",c?V(c):"0x",n?V(n):"0x",i??"0x",s?V(s):"0x",u??"0x",m,a?V(a):"0x",l??[],...Zs(e,t)],y=[],b=[],x=[];if(p)for(let g=0;g<p.length;g++){let{blob:w,commitment:v,proof:E}=p[g];y.push(w),b.push(v),x.push(E)}return Le(["0x03",p?Ar([h,y,b,x]):Ar(h)])}function z3(e,t){let{chainId:r,gas:n,nonce:o,to:i,value:s,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:d,data:f}=e;al(e);let u=Zc(d),l=[V(r),o?V(o):"0x",c?V(c):"0x",a?V(a):"0x",n?V(n):"0x",i??"0x",s?V(s):"0x",f??"0x",u,...Zs(e,t)];return Le(["0x02",Ar(l)])}function $3(e,t){let{chainId:r,gas:n,data:o,nonce:i,to:s,value:a,accessList:c,gasPrice:d}=e;T2(e);let f=Zc(c),u=[V(r),i?V(i):"0x",d?V(d):"0x",n?V(n):"0x",s??"0x",a?V(a):"0x",o??"0x",f,...Zs(e,t)];return Le(["0x01",Ar(u)])}function L3(e,t){let{chainId:r=0,gas:n,data:o,nonce:i,to:s,value:a,gasPrice:c}=e;I2(e);let d=[i?V(i):"0x",c?V(c):"0x",n?V(n):"0x",s??"0x",a?V(a):"0x",o??"0x"];if(t){let f=(()=>{if(t.v>=35n)return(t.v-35n)/2n>0?t.v:27n+(t.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);let p=27n+(t.v===27n?0n:1n);if(t.v!==p)throw new Ku({v:t.v});return p})(),u=Vr(t.r),l=Vr(t.s);d=[...d,V(f),u==="0x00"?"0x":u,l==="0x00"?"0x":l]}else r>0&&(d=[...d,V(r),"0x","0x"]);return Ar(d)}function Zs(e,t){let r=t??e,{v:n,yParity:o}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof o>"u")return[];let i=Vr(r.r),s=Vr(r.s);return[typeof o=="number"?o?V(1):"0x":n===0n?"0x":n===1n?V(1):n===27n?"0x":V(1),i==="0x00"?"0x":i,s==="0x00"?"0x":s]}var Eh=C(()=>{$t();O2();Ju();Qu();gh();xh();or();Qf();xe();Ru();k2();Sh();B2()});function R2(e){if(!e||e.length===0)return[];let t=[];for(let r of e){let{chainId:n,nonce:o,...i}=r,s=r.address;t.push([n?ht(n):"0x",s,o?ht(o):"0x",...Zs({},i)])}return t}var O2=C(()=>{xe();Eh()});function gt(e){if(e?.reason)return e.reason;if(typeof DOMException=="function")return new DOMException("This operation was aborted","AbortError");let t=new Error("This operation was aborted");return t.name="AbortError",t}function rn(e){return typeof e=="object"&&e!==null&&"name"in e&&e.name==="AbortError"}var C2,Ys,Cn=C(()=>{C2=e=>e;Ys=e=>{try{let t=new URL(e);return!t.username&&!t.password?e:(t.username="",t.password="",t.toString())}catch{return e}}});var ko,Xs,Yc=C(()=>{_r();le();Cn();ko=class extends L{constructor({body:t,cause:r,details:n,headers:o,status:i,url:s}){super("HTTP request failed.",{cause:r,details:n,metaMessages:[i&&`Status: ${i}`,`URL: ${Ys(s)}`,t&&`Request body: ${qe(t)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=t,this.headers=o,this.status=i,this.url=s}},Xs=class extends L{constructor({body:t,error:r,url:n}){super("RPC Request failed.",{cause:r,details:r.message,metaMessages:[`URL: ${Ys(n)}`,`Request body: ${qe(t)}`],name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=r.code,this.data=r.data,this.url=n}}});var D3,wt,xt,Js,Qs,ea,ta,Un,Bo,ra,na,oa,Po,Ci,ia,Ui,sa,aa,ca,da,fa,Ro,ua,la,pa,ma,ha,Oo,ya,dl,fl=C(()=>{le();Yc();D3=-1,wt=class extends L{constructor(t,{code:r,docsPath:n,metaMessages:o,name:i,shortMessage:s}){super(s,{cause:t,docsPath:n,metaMessages:o||t?.metaMessages,name:i||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i||t.name,this.code=t instanceof Xs?t.code:r??D3}},xt=class extends wt{constructor(t,r){super(t,r),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=r.data}},Js=class e extends wt{constructor(t){super(t,{code:e.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}};Object.defineProperty(Js,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});Qs=class e extends wt{constructor(t){super(t,{code:e.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}};Object.defineProperty(Qs,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});ea=class e extends wt{constructor(t,{method:r}={}){super(t,{code:e.code,name:"MethodNotFoundRpcError",shortMessage:`The method${r?` "${r}"`:""} does not exist / is not available.`})}};Object.defineProperty(ea,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});ta=class e extends wt{constructor(t){super(t,{code:e.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
27
+ `)})}};Object.defineProperty(ta,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});Un=class e extends wt{constructor(t){super(t,{code:e.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}};Object.defineProperty(Un,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});Bo=class e extends wt{constructor(t){super(t,{code:e.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
28
+ `)})}};Object.defineProperty(Bo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});ra=class e extends wt{constructor(t){super(t,{code:e.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}};Object.defineProperty(ra,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});na=class e extends wt{constructor(t){super(t,{code:e.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}};Object.defineProperty(na,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});oa=class e extends wt{constructor(t){super(t,{code:e.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}};Object.defineProperty(oa,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});Po=class e extends wt{constructor(t,{method:r}={}){super(t,{code:e.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${r?` "${r}"`:""} is not supported.`})}};Object.defineProperty(Po,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});Ci=class e extends wt{constructor(t){super(t,{code:e.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}};Object.defineProperty(Ci,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});ia=class e extends wt{constructor(t){super(t,{code:e.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}};Object.defineProperty(ia,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});Ui=class e extends xt{constructor(t){super(t,{code:e.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}};Object.defineProperty(Ui,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});sa=class e extends xt{constructor(t){super(t,{code:e.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}};Object.defineProperty(sa,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});aa=class e extends xt{constructor(t,{method:r}={}){super(t,{code:e.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${r?` " ${r}"`:""}.`})}};Object.defineProperty(aa,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});ca=class e extends xt{constructor(t){super(t,{code:e.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}};Object.defineProperty(ca,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});da=class e extends xt{constructor(t){super(t,{code:e.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}};Object.defineProperty(da,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});fa=class e extends xt{constructor(t){super(t,{code:e.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}};Object.defineProperty(fa,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});Ro=class e extends xt{constructor(t){super(t,{code:e.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}};Object.defineProperty(Ro,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});ua=class e extends xt{constructor(t){super(t,{code:e.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}};Object.defineProperty(ua,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});la=class e extends xt{constructor(t){super(t,{code:e.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}};Object.defineProperty(la,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});pa=class e extends xt{constructor(t){super(t,{code:e.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}};Object.defineProperty(pa,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});ma=class e extends xt{constructor(t){super(t,{code:e.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}};Object.defineProperty(ma,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});ha=class e extends xt{constructor(t){super(t,{code:e.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}};Object.defineProperty(ha,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});Oo=class e extends xt{constructor(t){super(t,{code:e.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}};Object.defineProperty(Oo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});ya=class e extends xt{constructor(t){super(t,{code:e.code,name:"WalletConnectSessionSettlementError",shortMessage:"WalletConnect session settlement failed."})}};Object.defineProperty(ya,"code",{enumerable:!0,configurable:!0,writable:!0,value:7e3});dl=class extends wt{constructor(t){super(t,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}});function U2(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(ul.get(r))return ul.get(r);let n=e().finally(()=>ul.delete(r));return ul.set(r,n),n}var ul,N2=C(()=>{xi();ul=new Mt(8192)});async function Xc(e,{signal:t}={}){return new Promise((r,n)=>{if(t?.aborted){n(gt(t));return}let o=()=>t?.removeEventListener("abort",s),i=setTimeout(()=>{o(),r()},e),s=()=>{clearTimeout(i),o(),n(gt(t))};t?.addEventListener("abort",s,{once:!0})})}var _h=C(()=>{Cn()});function Ni(e,{delay:t=100,retryCount:r=2,shouldRetry:n=()=>!0,signal:o}={}){return new Promise((i,s)=>{let a=()=>s(gt(o));o?.addEventListener("abort",a,{once:!0});let c=async({count:d=0}={})=>{if(o?.aborted){s(gt(o));return}let f=async({error:u})=>{let l=typeof t=="function"?t({count:d,error:u}):t;if(l)try{await Xc(l,{signal:o})}catch(p){s(p);return}return c({count:d+1})};try{let u=await e();i(u)}catch(u){if(o?.aborted){s(gt(o));return}if(rn(u)){s(u);return}if(d<r&&await n({count:d,error:u}))return f({error:u});s(u)}};c().catch(s).finally(()=>o?.removeEventListener("abort",a))})}var ll=C(()=>{Cn();_h()});function F2(e,t={}){return async(r,n={})=>{let{dedupe:o=!1,methods:i,retryDelay:s=150,retryCount:a=3,signal:c,uid:d}={...t,...n},{method:f}=r;if(i?.exclude?.includes(f))throw new Po(new Error("method not supported"),{method:f});if(i?.include&&!i.include.includes(f))throw new Po(new Error("method not supported"),{method:f});if(c?.aborted)throw gt(c);let u=o?j3(`${d}.${qe(r)}`):void 0;return U2(()=>Ni(async()=>{try{return await e(r,c?{signal:c}:void 0)}catch(l){if(c?.aborted)throw gt(c);if(rn(l))throw l;let p=l;switch(p.code){case Js.code:throw new Js(p);case Qs.code:throw new Qs(p);case ea.code:throw new ea(p,{method:r.method});case ta.code:throw new ta(p);case Un.code:throw new Un(p);case Bo.code:throw new Bo(p);case ra.code:throw new ra(p);case na.code:throw new na(p);case oa.code:throw new oa(p);case Po.code:throw new Po(p,{method:r.method});case Ci.code:throw new Ci(p);case ia.code:throw new ia(p);case Ui.code:throw new Ui(p);case sa.code:throw new sa(p);case aa.code:throw new aa(p);case ca.code:throw new ca(p);case da.code:throw new da(p);case fa.code:throw new fa(p);case Ro.code:throw new Ro(p);case ua.code:throw new ua(p);case la.code:throw new la(p);case pa.code:throw new pa(p);case ma.code:throw new ma(p);case ha.code:throw new ha(p);case Oo.code:throw new Oo(p);case 5e3:throw new Ui(p);case ya.code:throw new ya(p);default:throw l instanceof L?l:new dl(p)}}},{delay:({count:l,error:p})=>{if(p&&p instanceof ko){let m=p?.headers?.get("Retry-After");if(m?.match(/\d/))return Number.parseInt(m,10)*1e3}return~~(1<<l)*s},retryCount:a,signal:c,shouldRetry:({error:l})=>q3(l)}),{enabled:o,id:u})}}function q3(e){return rn(e)?!1:"code"in e&&typeof e.code=="number"?e.code===-1||e.code===Ci.code||e.code===Un.code||e.code===429||e.code===-32007:e instanceof ko&&e.status?e.status===403||e.status===408||e.status===413||e.status===429||e.status===500||e.status===502||e.status===503||e.status===504:!0}function j3(e,t=0){let r=3735928559^t,n=1103547991^t;for(let o=0;o<e.length;o++){let i=e.charCodeAt(o);r=Math.imul(r^i,2654435761),n=Math.imul(n^i,1597334677)}return r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>16,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>16,3266489909),(4294967296*(2097151&n)+(r>>>0)).toString(36)}var M2=C(()=>{le();Yc();fl();Cn();N2();ll();_r()});var H2,z2=C(()=>{H2="0.1.1"});function $2(){return H2}var L2=C(()=>{z2()});function D2(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?D2(e.cause,t):t?null:e}var Co,q2=C(()=>{L2();Co=class e extends Error{static setStaticOptions(t){e.prototype.docsOrigin=t.docsOrigin,e.prototype.showVersion=t.showVersion,e.prototype.version=t.version}constructor(t,r={}){let n=(()=>{if(r.cause instanceof e){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:r.cause?.message?r.cause.message:r.details})(),o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,i=r.docsOrigin??e.prototype.docsOrigin,s=`${i}${o??""}`,a=!!(r.version??e.prototype.showVersion),c=r.version??e.prototype.version,d=[t||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||o||a?["",n?`Details: ${n}`:void 0,o?`See: ${s}`:void 0,a?`Version: ${c}`:void 0]:[]].filter(f=>typeof f=="string").join(`
29
+ `);super(d,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsOrigin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"showVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.cause=r.cause,this.details=n,this.docs=s,this.docsOrigin=i,this.docsPath=o,this.shortMessage=t,this.showVersion=a,this.version=c}walk(t){return D2(this,t)}};Object.defineProperty(Co,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:"https://oxlib.sh",showVersion:!1,version:`ox@${$2()}`}});Co.setStaticOptions(Co.defaultStaticOptions)});function j2(e,t={}){let{dir:r,size:n=32}=t;if(n===0)return e;let o=e.replace("0x","");if(o.length>n*2)throw new pl({size:Math.ceil(o.length/2),targetSize:n,type:"Hex"});return`0x${o[r==="right"?"padEnd":"padStart"](n*2,"0")}`}var G2=C(()=>{ml()});function Ir(e,t={}){let{signed:r,size:n}=t,o=BigInt(e),i;n?r?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));let s=typeof i=="bigint"&&r?-i-1n:0;if(i&&o>i||o<s){let d=typeof e=="bigint"?"n":"";throw new Th({max:i?`${i}${d}`:void 0,min:`${s}${d}`,signed:r,size:n,value:`${e}${d}`})}let c=`0x${(r&&o<0?BigInt.asUintN(n*8,BigInt(o)):o).toString(16)}`;return n?K3(c,n):c}function K3(e,t){return j2(e,{dir:"left",size:t})}var Th,pl,ml=C(()=>{q2();G2();Th=class extends Co{constructor({max:t,min:r,signed:n,size:o,value:i}){super(`Number \`${i}\` is not in safe${o?` ${o*8}-bit`:""}${n?" signed":" unsigned"} integer range ${t?`(\`${r}\` to \`${t}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}},pl=class extends Co{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}});function V2(e){return{address:e.address,amount:Ir(e.amount),index:Ir(e.index),validatorIndex:Ir(e.validatorIndex)}}var K2=C(()=>{ml()});function W2(e){return{...typeof e.baseFeePerGas=="bigint"&&{baseFeePerGas:Ir(e.baseFeePerGas)},...typeof e.blobBaseFee=="bigint"&&{blobBaseFee:Ir(e.blobBaseFee)},...typeof e.feeRecipient=="string"&&{feeRecipient:e.feeRecipient},...typeof e.gasLimit=="bigint"&&{gasLimit:Ir(e.gasLimit)},...typeof e.number=="bigint"&&{number:Ir(e.number)},...typeof e.prevRandao=="bigint"&&{prevRandao:Ir(e.prevRandao)},...typeof e.time=="bigint"&&{time:Ir(e.time)},...e.withdrawals&&{withdrawals:e.withdrawals.map(V2)}}}var Z2=C(()=>{ml();K2()});var Ih,hl,Y2,mN,hN,Fi,Jc=C(()=>{Ih=[{inputs:[{components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}],name:"returnData",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{name:"addr",type:"address"}],name:"getEthBalance",outputs:[{name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"}],hl=[{name:"query",type:"function",stateMutability:"view",inputs:[{type:"tuple[]",name:"queries",components:[{type:"address",name:"sender"},{type:"string[]",name:"urls"},{type:"bytes",name:"data"}]}],outputs:[{type:"bool[]",name:"failures"},{type:"bytes[]",name:"responses"}]},{name:"HttpError",type:"error",inputs:[{type:"uint16",name:"status"},{type:"string",name:"message"}]}],Y2=[{inputs:[{name:"dns",type:"bytes"}],name:"DNSDecodingFailed",type:"error"},{inputs:[{name:"ens",type:"string"}],name:"DNSEncodingFailed",type:"error"},{inputs:[],name:"EmptyAddress",type:"error"},{inputs:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"HttpError",type:"error"},{inputs:[],name:"InvalidBatchGatewayResponse",type:"error"},{inputs:[{name:"errorData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{name:"name",type:"bytes"},{name:"resolver",type:"address"}],name:"ResolverNotContract",type:"error"},{inputs:[{name:"name",type:"bytes"}],name:"ResolverNotFound",type:"error"},{inputs:[{name:"primary",type:"string"},{name:"primaryAddress",type:"bytes"}],name:"ReverseAddressMismatch",type:"error"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"}],name:"UnsupportedResolverProfile",type:"error"}],mN=[...Y2,{name:"resolveWithGateways",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}],hN=[...Y2,{name:"reverseWithGateways",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"uint256",name:"coinType"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolver"},{type:"address",name:"reverseResolver"}]}],Fi=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{type:"uint8"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}]});var X2,J2=C(()=>{X2="0x82ad56cb"});var Q2,e6,t6,r6=C(()=>{Q2="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",e6="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",t6="0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033"});function n6(e){return e.reduce((t,{slot:r,value:n})=>`${t} ${r}: ${n}
30
+ `,"")}function o6(e){return e.reduce((t,{address:r,...n})=>{let o=`${t} ${r}:
31
31
  `;return n.nonce&&(o+=` nonce: ${n.nonce}
32
32
  `),n.balance&&(o+=` balance: ${n.balance}
33
33
  `),n.code&&(o+=` code: ${n.code}
34
34
  `),n.state&&(o+=` state:
35
- `,o+=J2(n.state)),n.stateDiff&&(o+=` stateDiff:
36
- `,o+=J2(n.stateDiff)),o},` State Override:
37
- `).slice(0,-1)}var bl,gl,Bh=C(()=>{le();bl=class extends L{constructor({address:t}){super(`State for account "${t}" is set multiple times.`,{name:"AccountStateConflictError"})}},gl=class extends L{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}});var wl,xl,vl,Sl,El,ga,_l=C(()=>{Ye();Au();Rm();vo();ux();As();Ku();Us();yt();le();Bh();Lt();Un();wl=class extends L{constructor(t,{account:r,docsPath:n,chain:o,data:i,gas:s,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:d,nonce:f,to:u,value:l,stateOverride:p}){let m=r?ce(r):void 0,h=ki({from:m?.address,to:u,value:typeof l<"u"&&`${Cs(l)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:i,gas:s,gasPrice:typeof a<"u"&&`${ot(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${ot(c)} gwei`,maxPriorityFeePerGas:typeof d<"u"&&`${ot(d)} gwei`,nonce:f});p&&(h+=`
38
- ${Q2(p)}`),super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Raw Call Arguments:",h].filter(Boolean),name:"CallExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}},xl=class extends L{constructor(t,{abi:r,args:n,contractAddress:o,docsPath:i,functionName:s,sender:a}){let c=Qr({abi:r,args:n,name:s}),d=c?Lm({abiItem:c,args:n,includeFunctionName:!1,includeName:!1}):void 0,f=c?dt(c,{includeName:!0}):void 0,u=ki({address:o&&k2(o),function:f,args:d&&d!=="()"&&`${[...Array(s?.length??0).keys()].map(()=>" ").join("")}${d}`,sender:a});super(t.shortMessage||`An unknown error occurred while executing the contract function "${s}".`,{cause:t,docsPath:i,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],u&&"Contract Call:",u].filter(Boolean),name:"ContractFunctionExecutionError"}),Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=r,this.args=n,this.cause=t,this.contractAddress=o,this.functionName=s,this.sender=a}},vl=class extends L{constructor({abi:t,data:r,functionName:n,message:o,cause:i}){let s,a,c,d;if(r&&r!=="0x")try{a=Iu({abi:t,data:r,cause:i});let{abiItem:u,errorName:l,args:p}=a;if(l==="Error")d=p[0];else if(l==="Panic"){let[m]=p;d=V1[m]}else{let m=u?dt(u,{includeName:!0}):void 0,h=u&&p?Lm({abiItem:u,args:p,includeFunctionName:!1,includeName:!1}):void 0;c=[m?`Error: ${m}`:"",h&&h!=="()"?` ${[...Array(l?.length??0).keys()].map(()=>" ").join("")}${h}`:""]}}catch(u){s=u}else o&&(d=o);let f;s instanceof bs&&(f=s.signature,c=[`Unable to decode signature "${f}" as it was not found on the provided ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${f}.`]),super(d&&d!=="execution reverted"||f?[`The contract function "${n}" reverted with the following ${f?"signature":"reason"}:`,d||f].join(`
39
- `):`The contract function "${n}" reverted.`,{cause:s??i,metaMessages:c,name:"ContractFunctionRevertedError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=a,this.raw=r,this.reason=d,this.signature=f}},Sl=class extends L{constructor({functionName:t,cause:r}){super(`The contract function "${t}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${t}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError",cause:r})}},El=class extends L{constructor({factory:t}){super(`Deployment for counterfactual contract call failed${t?` for factory "${t}".`:""}`,{metaMessages:["Please ensure:","- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).","- The `factoryData` is a valid encoded function call for contract deployment function on the factory."],name:"CounterfactualDeploymentFailedError"})}},ga=class extends L{constructor({data:t,message:r}){super(r||"",{name:"RawContractError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t}}});function Qc(e){let{blockHash:t,blockNumber:r,blockTag:n,requireCanonical:o}=e;if(o!==void 0&&!t)throw new L("`requireCanonical` can only be provided when `blockHash` is set.");return t?o?{blockHash:t,requireCanonical:o}:{blockHash:t}:typeof r=="bigint"?V(r):n??"latest"}var Ph=C(()=>{le();xe()});function e6({blockNumber:e,chain:t,contract:r}){let n=t?.contracts?.[r];if(!n)throw new Bi({chain:t,contract:{name:r}});if(e&&n.blockCreated&&n.blockCreated>e)throw new Bi({blockNumber:e,chain:t,contract:{name:r,blockCreated:n.blockCreated}});return n.address}var t6=C(()=>{Wc()});function wa(e,t){let r=(e.details||"").toLowerCase(),n=e instanceof L?e.walk(o=>o?.code===Cn.code):e;return n instanceof L?new Cn({cause:e,message:n.details}):Cn.nodeMessage.test(r)?new Cn({cause:e,message:e.details}):ir.nodeMessage.test(r)?new ir({cause:e,maxFeePerGas:t?.maxFeePerGas}):Ds.nodeMessage.test(r)?new Ds({cause:e,maxFeePerGas:t?.maxFeePerGas}):qs.nodeMessage.test(r)?new qs({cause:e,nonce:t?.nonce}):js.nodeMessage.test(r)?new js({cause:e,nonce:t?.nonce}):Gs.nodeMessage.test(r)?new Gs({cause:e,nonce:t?.nonce}):Vs.nodeMessage.test(r)?new Vs({cause:e}):Ks.nodeMessage.test(r)?new Ks({cause:e,gas:t?.gas}):Ws.nodeMessage.test(r)?new Ws({cause:e,gas:t?.gas}):Zs.nodeMessage.test(r)?new Zs({cause:e}):tn.nodeMessage.test(r)?new tn({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas}):new rn({cause:e})}var Al=C(()=>{le();Ri()});function r6(e,{docsPath:t,...r}){let n=(()=>{let o=wa(e,r);return o instanceof rn?e:o})();return new wl(n,{docsPath:t,...r})}var n6=C(()=>{_l();Ri();Al()});function on(e,{format:t}){if(!t)return{};let r={};function n(i){let s=Object.keys(i);for(let a of s)a in e&&(r[a]=e[a]),i[a]&&typeof i[a]=="object"&&!Array.isArray(i[a])&&n(i[a])}let o=t(e||{});return n(o),r}var xa=C(()=>{});function va(e,t){return({exclude:r,format:n})=>({exclude:r,format:(o,i)=>{let s=t(o,i);if(r)for(let a of r)delete s[a];return{...s,...n(o,i)}},type:e})}var Tl=C(()=>{});function sr(e,t){let r={};return typeof e.authorizationList<"u"&&(r.authorizationList=G3(e.authorizationList)),typeof e.accessList<"u"&&(r.accessList=e.accessList),typeof e.blobVersionedHashes<"u"&&(r.blobVersionedHashes=e.blobVersionedHashes),typeof e.blobs<"u"&&(typeof e.blobs[0]!="string"?r.blobs=e.blobs.map(n=>Me(n)):r.blobs=e.blobs),typeof e.data<"u"&&(r.data=e.data),e.account&&(r.from=e.account.address),typeof e.from<"u"&&(r.from=e.from),typeof e.gas<"u"&&(r.gas=V(e.gas)),typeof e.gasPrice<"u"&&(r.gasPrice=V(e.gasPrice)),typeof e.maxFeePerBlobGas<"u"&&(r.maxFeePerBlobGas=V(e.maxFeePerBlobGas)),typeof e.maxFeePerGas<"u"&&(r.maxFeePerGas=V(e.maxFeePerGas)),typeof e.maxPriorityFeePerGas<"u"&&(r.maxPriorityFeePerGas=V(e.maxPriorityFeePerGas)),typeof e.nonce<"u"&&(r.nonce=V(e.nonce)),typeof e.to<"u"&&(r.to=e.to),typeof e.type<"u"&&(r.type=j3[e.type]),typeof e.value<"u"&&(r.value=V(e.value)),r}function G3(e){return e.map(t=>({address:t.address,r:t.r?V(BigInt(t.r)):t.r,s:t.s?V(BigInt(t.s)):t.s,chainId:V(t.chainId),nonce:V(t.nonce),...typeof t.yParity<"u"?{yParity:V(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:V(t.v)}:{}}))}var j3,Fi=C(()=>{xe();j3={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"}});function Sa(){let e=()=>{},t=()=>{};return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}var Il=C(()=>{});function o6({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:o}){let i=async()=>{let f=c();s();let u=f.map(({args:l})=>l);u.length!==0&&e(u).then(l=>{o&&Array.isArray(l)&&l.sort(o);for(let p=0;p<f.length;p++){let{resolve:m}=f[p];m?.([l[p],l])}}).catch(l=>{for(let p=0;p<f.length;p++){let{reject:m}=f[p];m?.(l)}})},s=()=>Rh.delete(t),a=()=>c().map(({args:f})=>f),c=()=>Rh.get(t)||[],d=f=>Rh.set(t,[...c(),f]);return{flush:s,async schedule(f){let{promise:u,resolve:l,reject:p}=Sa();return r?.([...a(),f])&&i(),c().length>0?(d({args:f,resolve:l,reject:p}),u):(d({args:f,resolve:l,reject:p}),setTimeout(i,n),u)}}}var Rh,i6=C(()=>{Il();Rh=new Map});function s6(e){if(!(!e||e.length===0))return e.reduce((t,{slot:r,value:n})=>{if(r.length!==66)throw new Sc({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new Sc({size:n.length,targetSize:66,type:"hex"});return t[r]=n,t},{})}function V3(e){let{balance:t,nonce:r,state:n,stateDiff:o,code:i}=e,s={};if(i!==void 0&&(s.code=i),t!==void 0&&(s.balance=V(t)),r!==void 0&&(s.nonce=V(r)),n!==void 0&&(s.state=s6(n)),o!==void 0){if(s.state)throw new gl;s.stateDiff=s6(o)}return s}function kl(e){if(!e)return;let t={};for(let{address:r,...n}of e){if(!pe(r,{strict:!1}))throw new Ce({address:r});if(t[r])throw new bl({address:r});t[r]=V3(n)}return t}var Oh=C(()=>{Vr();Yf();Bh();Zt();xe()});function Dt(e){let{account:t,maxFeePerGas:r,maxPriorityFeePerGas:n,to:o}=e,i=t?ce(t):void 0;if(i&&!pe(i.address))throw new Ce({address:i.address});if(o&&!pe(o))throw new Ce({address:o});if(r&&r>Ls)throw new ir({maxFeePerGas:r});if(n&&r&&n>r)throw new tn({maxFeePerGas:r,maxPriorityFeePerGas:n})}var Uo=C(()=>{Ye();Sh();Vr();Ri();Zt()});async function Bl(e,t){let{account:r=e.account,authorizationList:n,batch:o=!!e.batch?.multicall,blockHash:i,blockNumber:s,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,accessList:d,blobs:f,blockOverrides:u,code:l,data:p,factory:m,factoryData:h,gas:y,gasPrice:b,maxFeePerBlobGas:x,maxFeePerGas:g,maxPriorityFeePerGas:w,nonce:v,requestOptions:E,to:B,value:N,stateOverride:U,...R}=t,T=r?ce(r):void 0;if(l&&(m||h))throw new L("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(l&&B)throw new L("Cannot provide both `code` & `to` as parameters.");let O=l&&p,z=m&&h&&B&&p,P=O||z,_=O?d6({code:l,data:p}):z?J3({data:p,factory:m,factoryData:h,to:B}):p;try{Dt(t);let I=Qc({blockHash:i,blockNumber:s,blockTag:a,requireCanonical:c}),k=u?q2(u):void 0,M=kl(U),$=e.chain?.formatters?.transactionRequest?.format,A=($||sr)({...on(R,{format:$}),accessList:d,account:T,authorizationList:n,blobs:f,data:_,gas:y,gasPrice:b,maxFeePerBlobGas:x,maxFeePerGas:g,maxPriorityFeePerGas:w,nonce:v,to:P?void 0:B,value:N},"call");if(o&&K3({request:A})&&!k&&i===void 0)try{let{deployless:q=!1}=typeof e.batch?.multicall=="object"?e.batch.multicall:{},j=c6(e,{blockNumber:s,deployless:q});if(!j||!X3(M,j))return await Y3(e,{...A,blockHash:i,blockNumber:s,blockTag:a,multicallAddress:j,requestOptions:E,requireCanonical:c,rpcStateOverride:M})}catch(q){if(!(q instanceof Kc)&&!(q instanceof Bi))throw q}let H=(()=>{let q=[A,I];return M&&k?[...q,M,k]:M?[...q,M]:k?[...q,{},k]:q})(),D=await e.request({method:"eth_call",params:H},E);return D==="0x"?{data:void 0}:{data:D}}catch(I){if(E?.signal?.aborted)throw gt(E.signal);if(nn(I))throw I;let k=Q3(I),{offchainLookup:M,offchainLookupSignature:$}=await Promise.resolve().then(()=>(u6(),f6));if(e.ccipRead!==!1&&k?.slice(0,10)===$&&B)return{data:await M(e,{data:k,requestOptions:E,to:B})};throw P&&k?.slice(0,10)==="0x101bb98d"?new El({factory:m}):r6(I,{...t,account:T,chain:e.chain})}}function K3({request:e}){let{data:t,to:r,...n}=e;return!(!t||t.startsWith(V2)||!r||Object.values(n).filter(o=>typeof o<"u").length>0)}function Z3(e){if(!e)return"default";let t=a6.get(e);if(t!==void 0)return t;let r=W3++;return a6.set(e,r),r}async function Y3(e,t){let{batchSize:r=1024,deployless:n=!1,wait:o=0}=typeof e.batch?.multicall=="object"?e.batch.multicall:{},{blockHash:i,blockNumber:s,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,data:d,multicallAddress:f,requestOptions:u,rpcStateOverride:l,to:p}=t,m=f!==void 0?f:c6(e,{blockNumber:s,deployless:n}),h=Qc({blockHash:i,blockNumber:s,blockTag:a,requireCanonical:c}),y=typeof h=="string"?h:JSON.stringify(h),b=l?`.${JSON.stringify(l)}`:"",{schedule:x}=o6({id:`${e.uid}.${y}.${Z3(u)}${b}`,wait:o,shouldSplitBatch(v){return v.reduce((B,{data:N})=>B+(N.length-2),0)>r*2},fn:async v=>{let E=v.map(R=>({allowFailure:!0,callData:R.data,target:R.to})),B=Yt({abi:kh,args:[E],functionName:"aggregate3"}),N={...m===null?{data:d6({code:Y2,data:B})}:{to:m,data:B}},U=await e.request({method:"eth_call",params:l?[N,h,l]:[N,h]},u);return Bu({abi:kh,args:[E],functionName:"aggregate3",data:U||"0x"})}}),[{returnData:g,success:w}]=await x({data:d,to:p});if(!w)throw new ga({data:g});return g==="0x"?{data:void 0}:{data:g}}function c6(e,t){let{blockNumber:r,deployless:n}=t;if(n)return null;if(e.chain)return e6({blockNumber:r,chain:e.chain,contract:"multicall3"});throw new Kc}function X3(e,t){return e?Object.keys(e).some(r=>Ht(r,t)):!1}function d6(e){let{code:t,data:r}=e;return Nc({abi:Zf(["constructor(bytes, bytes)"]),bytecode:W2,args:[t,r]})}function J3(e){let{data:t,factory:r,factoryData:n,to:o}=e;return Nc({abi:Zf(["constructor(address, bytes, address, bytes)"]),bytecode:Z2,args:[o,t,r,n]})}function Q3(e){if(!(e instanceof L))return;let t=e.walk();return typeof t?.data=="object"?t.data?.data:t.data}var W3,a6,Ch=C(()=>{hm();j2();Ye();Jc();K2();X2();le();Wc();_l();Un();Nm();Mm();vi();Si();Ph();t6();n6();xa();Fi();i6();Oh();Uo();W3=0,a6=new WeakMap});var Pl,Rl,Ol,l6=C(()=>{Ar();le();Un();Pl=class extends L{constructor({callbackSelector:t,cause:r,data:n,extraData:o,sender:i,urls:s}){super(r.shortMessage||"An error occurred while fetching for an offchain result.",{cause:r,metaMessages:[...r.metaMessages||[],r.metaMessages?.length?"":[],"Offchain Gateway Call:",s&&[" Gateway URL(s):",...s.map(a=>` ${Xs(a)}`)],` Sender: ${i}`,` Data: ${n}`,` Callback selector: ${t}`,` Extra data: ${o}`].flat(),name:"OffchainLookupError"})}},Rl=class extends L{constructor({result:t,url:r}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${Xs(r)}`,`Response: ${qe(t)}`],name:"OffchainLookupResponseMalformedError"})}},Ol=class extends L{constructor({sender:t,to:r}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${r}`,`OffchainLookup sender address: ${t}`],name:"OffchainLookupSenderMismatchError"})}}});async function Nh(e){let{data:t,ccipRequest:r}=e,{args:[n]}=rx({abi:yl,data:t}),o=[],i=[];return await Promise.all(n.map(async(s,a)=>{try{i[a]=s.urls.includes(Uh)?await Nh({data:s.data,ccipRequest:r}):await r(s),o[a]=!1}catch(c){o[a]=!0,i[a]=e4(c)}})),dx({abi:yl,functionName:"query",result:[o,i]})}function e4(e){return e.name==="HttpRequestError"&&e.status?Hm({abi:yl,errorName:"HttpError",args:[e.status,e.shortMessage]}):Hm({abi:[_u],errorName:"Error",args:["shortMessage"in e?e.shortMessage:e.message]})}var Uh,p6=C(()=>{Jc();Au();nx();ix();fx();Uh="x-batch-gateway:true"});var f6={};Iy(f6,{ccipRequest:()=>h6,offchainLookup:()=>r4,offchainLookupAbiItem:()=>m6,offchainLookupSignature:()=>t4});async function r4(e,{blockNumber:t,blockTag:r,data:n,requestOptions:o,to:i}){let{args:s}=Iu({data:n,abi:[m6]}),[a,c,d,f,u]=s,{ccipRead:l}=e,p=l&&typeof l?.request=="function"?l.request:h6;try{if(!Ht(i,a))throw new Ol({sender:a,to:i});let m=c.includes(Uh)?await Nh({data:d,ccipRequest:y=>p({...y,requestOptions:o})}):await p({data:d,requestOptions:o,sender:a,urls:c}),{data:h}=await Bl(e,{blockNumber:t,blockTag:r,data:_r([f,Xr([{type:"bytes"},{type:"bytes"}],[m,u])]),requestOptions:o,to:i});return h}catch(m){throw o?.signal?.aborted?gt(o.signal):nn(m)?m:new Pl({callbackSelector:f,cause:m,data:n,extraData:u,sender:a,urls:c})}}async function h6({data:e,requestOptions:t,sender:r,urls:n}){let o=new Error("An unknown error occurred.");for(let i=0;i<n.length;i++){if(t?.signal?.aborted)throw gt(t.signal);let s=n[i],a=s.includes("{data}")?"GET":"POST",c=a==="POST"?{data:e,sender:r}:void 0,d=a==="POST"?{"Content-Type":"application/json"}:{};try{let f=await fetch(s.replace("{sender}",r.toLowerCase()).replace("{data}",e),{body:JSON.stringify(c),headers:d,method:a,...t?.signal?{signal:t.signal}:{}}),u;if(f.headers.get("Content-Type")?.startsWith("application/json")?u=(await f.json()).data:u=await f.text(),!f.ok){o=new ko({body:c,details:u?.error?qe(u.error):f.statusText,headers:f.headers,status:f.status,url:s});continue}if(!ct(u)){o=new Rl({result:u,url:s});continue}return u}catch(f){if(t?.signal?.aborted)throw gt(t.signal);if(nn(f))throw f;o=new ko({body:c,details:f.message,url:s})}}throw o}var t4,m6,u6=C(()=>{Ch();l6();Yc();Un();Rm();xi();Si();or();vn();p6();Ar();t4="0x556f1830",m6={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]}});function Ea({chain:e,currentChainId:t}){if(!e)throw new al;if(t!==e.id)throw new sl({chain:e,currentChainId:t})}var Cl=C(()=>{Wc()});function Fh(e){let t={formatters:void 0,fees:void 0,serializers:void 0,...e};function r(n){return o=>{let i=typeof o=="function"?o(n):o,s={...n,...i};return Object.assign(s,{extend:r(s)})}}return Object.assign(t,{extend:r(t)})}var y6=C(()=>{});function _a(e,{abi:t,address:r,args:n,docsPath:o,functionName:i,sender:s}){let a=e instanceof ga?e:e instanceof L?e.walk(m=>typeof m=="object"&&m!==null&&"data"in m)||e.walk():{},{code:c,data:d,details:f,message:u,shortMessage:l}=a,p=e instanceof So?new Sl({functionName:i,cause:e}):[n4,Nn.code].includes(c)&&(d||f||u||l)||c===Bo.code&&f==="execution reverted"&&d?new vl({abi:t,data:typeof d=="object"?d.data:d,functionName:i,message:a instanceof Js?f:l??u,cause:e}):e;return new xl(p,{abi:t,args:n,contractAddress:r,docsPath:o,functionName:i,sender:s})}var n4,Ul=C(()=>{yt();le();_l();Yc();ul();n4=3});var Nl,b6=C(()=>{Ku();Us();le();Lt();Nl=class extends L{constructor(t,{account:r,docsPath:n,chain:o,data:i,gas:s,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:d,nonce:f,to:u,value:l}){let p=ki({from:r?.address,to:u,value:typeof l<"u"&&`${Cs(l)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:i,gas:s,gasPrice:typeof a<"u"&&`${ot(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${ot(c)} gwei`,maxPriorityFeePerGas:typeof d<"u"&&`${ot(d)} gwei`,nonce:f});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Estimate Gas Arguments:",p].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}}});function g6(e,{docsPath:t,...r}){let n=(()=>{let o=wa(e,r);return o instanceof rn?e:o})();return new Nl(n,{docsPath:t,...r})}var w6=C(()=>{b6();Ri();Al()});function No(e,{docsPath:t,...r}){let n=(()=>{let o=wa(e,r);return o instanceof rn?e:o})();return new Xu(n,{docsPath:t,...r})}var ed=C(()=>{Ri();Lt();Al()});function Fn(e,t){let r={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,...e.blockTimestamp!=null&&{blockTimestamp:BigInt(e.blockTimestamp)},chainId:e.chainId?Xe(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?Xe(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?Mh[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};return e.authorizationList&&(r.authorizationList=o4(e.authorizationList)),r.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof r.v=="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}})(),r.type==="legacy"&&(delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity),r.type==="eip2930"&&(delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas),r.type==="eip1559"&&delete r.maxFeePerBlobGas,r}function o4(e){return e.map(t=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}var Mh,x6,Aa=C(()=>{Pt();Tl();Mh={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};x6=va("transaction",Fn)});function zh(e,t){let r=(e.transactions??[]).map(n=>typeof n=="string"?n:Fn(n));return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:r,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}var v6,Hh=C(()=>{Tl();Aa();v6=va("block",zh)});function td(e,t){let r={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map(n=>Pu(n)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Xe(e.transactionIndex):null,status:e.status?$h[e.status]:null,type:e.type?Mh[e.type]||e.type:null};return e.blobGasPrice&&(r.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(r.blobGasUsed=BigInt(e.blobGasUsed)),r}var $h,S6,rd=C(()=>{Pt();Tl();Dm();Aa();$h={"0x0":"reverted","0x1":"success"};S6=va("transactionReceipt",td)});function oe(e,t,r){let n=e[t.name];if(typeof n=="function")return n;let o=e[r];return typeof o=="function"?o:i=>t(e,i)}var vt=C(()=>{});async function Fl(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:i}){let s=Qc({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i}),a=await e.request({method:"eth_getTransactionCount",params:[t,s]},{dedupe:typeof n=="bigint"||r!==void 0});return Xe(a)}var Lh=C(()=>{Ph();Pt()});var Ml,zl,Hl,$l,E6=C(()=>{Ar();le();Ml=class extends L{constructor({domain:t}){super(`Invalid domain "${qe(t)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}},zl=class extends L{constructor({primaryType:t,types:r}){super(`Invalid primary type \`${t}\` must be one of \`${JSON.stringify(Object.keys(r))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}},Hl=class extends L{constructor({type:t}){super(`Struct type "${t}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}},$l=class extends L{constructor({type:t}){let r=t.replace(/^(u?int)/,"$&256");super(`Type "${t}" is not a valid EIP-712 type.`,{metaMessages:[`Use "${r}" instead.`],name:"InvalidTypedDataTypeError"})}}});function _6(e){let{domain:t,message:r,primaryType:n,types:o}=e,i=(c,d)=>{let f={...d};for(let u of c){let{name:l,type:p}=u;p==="address"&&(f[l]=f[l].toLowerCase())}return f},s=o.EIP712Domain?t?i(o.EIP712Domain,t):{}:{},a=(()=>{if(n!=="EIP712Domain")return i(o[n],r)})();return qe({domain:s,message:a,primaryType:n,types:o})}function A6(e){let{domain:t,message:r,primaryType:n,types:o}=e,i=(s,a)=>{for(let c of s){let{name:d,type:f}=c,u=a[d],l=f.replace(/(\[[0-9]*\])+$/,"");if(l==="int"||l==="uint")throw new $l({type:f});let p=f.match(Eu);if(p&&(typeof u=="number"||typeof u=="bigint")){let[y,b,x]=p;V(u,{signed:b==="int",size:Number.parseInt(x,10)/8})}if(f==="address"&&typeof u=="string"&&!pe(u))throw new Ce({address:u});let m=f.match(j1);if(m){let[y,b]=m;if(b&&ge(u)!==Number.parseInt(b,10))throw new yu({expectedSize:Number.parseInt(b,10),givenSize:ge(u)})}let h=o[f];h&&(i4(f),i(h,u))}};if(o.EIP712Domain&&t){if(typeof t!="object")throw new Ml({domain:t});i(o.EIP712Domain,t)}if(n!=="EIP712Domain")if(o[n])i(o[n],r);else throw new zl({primaryType:n,types:o})}function T6({domain:e}){return[typeof e?.name=="string"&&{name:"name",type:"string"},typeof e?.version=="string"&&{name:"version",type:"string"},(typeof e?.chainId=="number"||typeof e?.chainId=="bigint")&&{name:"chainId",type:"uint256"},e?.verifyingContract&&{name:"verifyingContract",type:"address"},e?.salt&&{name:"salt",type:"bytes32"}].filter(Boolean)}function i4(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new Hl({type:e})}var I6=C(()=>{yt();Vr();E6();Zt();xr();xe();Am();Ar()});function Ll(e,t){return Gu(e,t)}var Dh=C(()=>{Vc()});function k6(e,t){return f2(e,t)}var B6=C(()=>{Vc()});var qh=C(()=>{vi();Zt()});var Ta,Fo,Kl,sd=C(()=>{Us();le();Ta=class extends L{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}},Fo=class extends L{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}},Kl=class extends L{constructor({maxPriorityFeePerGas:t}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${ot(t)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}});var Ia,Zh=C(()=>{le();Ia=class extends L{constructor({blockHash:t,blockNumber:r}){let n="Block";t&&(n=`Block at hash "${t}"`),r&&(n=`Block at number "${r}"`),super(`${n} could not be found.`,{name:"BlockNotFoundError"})}}});async function Br(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",includeTransactions:o}={}){let i=o??!1,s=r!==void 0?V(r):void 0,a=null;if(t?a=await e.request({method:"eth_getBlockByHash",params:[t,i]},{dedupe:!0}):a=await e.request({method:"eth_getBlockByNumber",params:[s||n,i]},{dedupe:!!s}),!a)throw new Ia({blockHash:t,blockNumber:r});return(e.chain?.formatters?.block?.format||zh)(a,"getBlock")}var ka=C(()=>{Zh();xe();Hh()});async function Wl(e){let t=await e.request({method:"eth_gasPrice"});return BigInt(t)}var Yh=C(()=>{});async function V6(e,t){let{block:r,chain:n=e.chain,request:o}=t||{};try{let i=n?.fees?.maxPriorityFeePerGas??n?.fees?.defaultPriorityFee;if(typeof i=="function"){let a=r||await oe(e,Br,"getBlock")({}),c=await i({block:a,client:e,request:o});if(c===null)throw new Error;return c}if(typeof i<"u")return i;let s=await e.request({method:"eth_maxPriorityFeePerGas"});return De(s)}catch{let[i,s]=await Promise.all([r?Promise.resolve(r):oe(e,Br,"getBlock")({}),oe(e,Wl,"getGasPrice")({})]);if(typeof i.baseFeePerGas!="bigint")throw new Fo;let a=s-i.baseFeePerGas;return a<0n?0n:a}}var K6=C(()=>{sd();Pt();vt();ka();Yh()});async function Xh(e,t){let{block:r,chain:n=e.chain,request:o,type:i="eip1559"}=t||{},s=await(async()=>typeof n?.fees?.baseFeeMultiplier=="function"?n.fees.baseFeeMultiplier({block:r,client:e,request:o}):n?.fees?.baseFeeMultiplier??1.2)();if(s<1)throw new Ta;let c=10**(s.toString().split(".")[1]?.length??0),d=l=>l*BigInt(Math.round(s*c))/BigInt(c),f=r||await oe(e,Br,"getBlock")({});if(typeof n?.fees?.estimateFeesPerGas=="function"){let l=await n.fees.estimateFeesPerGas({block:r,client:e,multiply:d,request:o,type:i});if(l!==null)return l}if(i==="eip1559"){if(typeof f.baseFeePerGas!="bigint")throw new Fo;let l=typeof o?.maxPriorityFeePerGas=="bigint"?o.maxPriorityFeePerGas:await V6(e,{block:f,chain:n,request:o}),p=d(f.baseFeePerGas);return{maxFeePerGas:o?.maxFeePerGas??p+l,maxPriorityFeePerGas:l}}return{gasPrice:o?.gasPrice??d(await oe(e,Wl,"getGasPrice")({}))}}var W6=C(()=>{sd();vt();K6();ka();Yh()});async function qt(e){let t=await e.request({method:"eth_chainId"},{dedupe:!0});return Xe(t)}var Mo=C(()=>{Pt()});async function Zl(e,t){let{account:r=e.account,accessList:n,authorizationList:o,chain:i=e.chain,blobVersionedHashes:s,blobs:a,data:c,gas:d,gasPrice:f,maxFeePerBlobGas:u,maxFeePerGas:l,maxPriorityFeePerGas:p,nonce:m,nonceManager:h,to:y,type:b,value:x,...g}=t,w=await(async()=>{if(!r||!h||typeof m<"u")return m;let N=ce(r),U=i?i.id:await oe(e,qt,"getChainId")({});return await h.consume({address:N.address,chainId:U,client:e})})();Dt(t);let v=i?.formatters?.transactionRequest?.format,B=(v||sr)({...on(g,{format:v}),account:r?ce(r):void 0,accessList:n,authorizationList:o,blobs:a,blobVersionedHashes:s,data:c,gas:d,gasPrice:f,maxFeePerBlobGas:u,maxFeePerGas:l,maxPriorityFeePerGas:p,nonce:w,to:y,type:b,value:x},"fillTransaction");try{let N=await e.request({method:"eth_fillTransaction",params:[B]}),R=(i?.formatters?.transaction?.format||Fn)(N.tx);delete R.blockHash,delete R.blockNumber,delete R.r,delete R.s,delete R.transactionIndex,delete R.v,delete R.yParity,R.data=R.input;let T=typeof R.feePayerSignature<"u"&&R.feePayerSignature!==null;if(T&&typeof w<"u"&&R.nonce!==w)throw new Ns({filledNonce:R.nonce,requestedNonce:w});if(!T){R.gas&&(R.gas=t.gas??R.gas),R.gasPrice&&(R.gasPrice=t.gasPrice??R.gasPrice),R.maxFeePerBlobGas&&(R.maxFeePerBlobGas=t.maxFeePerBlobGas??R.maxFeePerBlobGas),R.maxFeePerGas&&(R.maxFeePerGas=t.maxFeePerGas??R.maxFeePerGas),R.maxPriorityFeePerGas&&(R.maxPriorityFeePerGas=t.maxPriorityFeePerGas??R.maxPriorityFeePerGas),typeof R.nonce<"u"&&(R.nonce=t.nonce??R.nonce);let O=await(async()=>{if(typeof i?.fees?.baseFeeMultiplier=="function"){let I=await oe(e,Br,"getBlock")({});return i.fees.baseFeeMultiplier({block:I,client:e,request:t})}return i?.fees?.baseFeeMultiplier??1.2})();if(O<1)throw new Ta;let P=10**(O.toString().split(".")[1]?.length??0),_=I=>I*BigInt(Math.round(O*P))/BigInt(P);R.maxFeePerGas&&!t.maxFeePerGas&&(R.maxFeePerGas=_(R.maxFeePerGas)),R.gasPrice&&!t.gasPrice&&(R.gasPrice=_(R.gasPrice))}return{raw:N.raw,transaction:{from:B.from,...R},...N.capabilities?{capabilities:N.capabilities}:{}}}catch(N){throw No(N,{...t,chain:e.chain})}}var Jh=C(()=>{Ye();sd();Lt();ed();xa();Aa();Fi();vt();Uo();ka();Mo()});async function zo(e,t){let r=t;r.account??=e.account,r.parameters??=ad;let{account:n,chain:o=e.chain,nonceManager:i,parameters:s}=r,a=(()=>{if(typeof o?.prepareTransactionRequest=="function")return{fn:o.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(o?.prepareTransactionRequest))return{fn:o.prepareTransactionRequest[0],runAt:o.prepareTransactionRequest[1].runAt}})(),c;async function d(){return c||(typeof r.chainId<"u"?r.chainId:o?o.id:(c=await oe(e,qt,"getChainId")({}),c))}let f=n&&ce(n),u=r.nonce;if(a?.fn&&a.runAt?.includes("beforeFillTransaction")){r=await a.fn({...r,chain:o},{client:e,phase:"beforeFillTransaction"}),u??=r.nonce;let w=r.account??r.from;f=w?ce(w):void 0}if(s.includes("nonce")&&typeof u>"u"&&f&&i){let w=await d();u=await i.consume({address:f.address,chainId:w,client:e})}let p=((s.includes("blobVersionedHashes")||s.includes("sidecars"))&&r.kzg&&r.blobs?!1:s.length>0&&"feePayer"in r&&r.feePayer&&!("feePayerSignature"in r&&r.feePayerSignature)?!0:Qh.get(e.uid)===!1||!["fees","gas"].some(v=>s.includes(v))?!1:!!(s.includes("chainId")&&typeof r.chainId!="number"||s.includes("nonce")&&typeof u!="number"||s.includes("fees")&&typeof r.gasPrice!="bigint"&&(typeof r.maxFeePerGas!="bigint"||typeof r.maxPriorityFeePerGas!="bigint")||s.includes("gas")&&typeof r.gas!="bigint"))?await oe(e,Zl,"fillTransaction")({...r,nonce:u}).then(w=>{let{chainId:v,from:E,gas:B,gasPrice:N,nonce:U,maxFeePerBlobGas:R,maxFeePerGas:T,maxPriorityFeePerGas:O,type:z,...P}=w.transaction,_="feeToken"in P?P.feeToken:void 0,I="feePayerSignature"in P&&P.feePayerSignature!==null&&typeof P.feePayerSignature<"u",k=typeof _<"u"&&_!==null&&(!("feeToken"in r)||I);return Qh.set(e.uid,!0),{...r,...E?{from:E}:{},...z&&!r.type?{type:z}:{},...typeof v<"u"?{chainId:v}:{},...typeof B<"u"?{gas:B}:{},...typeof N<"u"?{gasPrice:N}:{},...typeof U<"u"?{nonce:U}:{},...typeof R<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerBlobGas:R}:{},...typeof T<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerGas:T}:{},...typeof O<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxPriorityFeePerGas:O}:{},..."nonceKey"in P&&typeof P.nonceKey<"u"?{nonceKey:P.nonceKey}:{},..."validBefore"in P&&P.validBefore!==null&&typeof P.validBefore<"u"?{validBefore:P.validBefore}:{},..."validAfter"in P&&P.validAfter!==null&&typeof P.validAfter<"u"?{validAfter:P.validAfter}:{},..."keyAuthorization"in P&&typeof P.keyAuthorization<"u"&&P.keyAuthorization!==null&&!("keyAuthorization"in r)?{keyAuthorization:P.keyAuthorization}:{},..."feePayerSignature"in P&&typeof P.feePayerSignature<"u"&&P.feePayerSignature!==null?{feePayerSignature:P.feePayerSignature}:{},...k?{feeToken:_}:{},...w.capabilities?{_capabilities:w.capabilities}:{}}}).catch(w=>{let v=w;if(v.name!=="TransactionExecutionError")return r;if(v.walk?.(U=>U instanceof Ns)||v.walk?.(U=>U.name==="ExecutionRevertedError"))throw w;return v.walk?.(U=>{let R=U;return R.name==="MethodNotFoundRpcError"||R.name==="MethodNotSupportedRpcError"||R.message?.includes("eth_fillTransaction is not available")})&&Qh.set(e.uid,!1),r}):r;u??=p.nonce,r={...p,...f?{from:f?.address}:{},...typeof u<"u"?{nonce:u}:{}};let{blobs:m,gas:h,kzg:y,type:b}=r;a?.fn&&a.runAt?.includes("beforeFillParameters")&&(r=await a.fn({...r,chain:o},{client:e,phase:"beforeFillParameters"}));let x;async function g(){return x||(x=await oe(e,Br,"getBlock")({blockTag:"latest"}),x)}if(s.includes("nonce")&&typeof u>"u"&&f&&!i&&(r.nonce=await oe(e,Fl,"getTransactionCount")({address:f.address,blockTag:"pending"})),(s.includes("blobVersionedHashes")||s.includes("sidecars"))&&m&&y){let w=zs({blobs:m,kzg:y});if(s.includes("blobVersionedHashes")){let v=tl({commitments:w,to:"hex"});r.blobVersionedHashes=v}if(s.includes("sidecars")){let v=Hs({blobs:m,commitments:w,kzg:y}),E=il({blobs:m,commitments:w,proofs:v,to:"hex"});r.sidecars=E}}if(s.includes("chainId")&&(r.chainId=await d()),(s.includes("fees")||s.includes("type"))&&typeof b>"u")try{r.type=dl(r)}catch{let w=Z6.get(e.uid);typeof w>"u"&&(w=typeof(await g())?.baseFeePerGas=="bigint",Z6.set(e.uid,w)),r.type=w?"eip1559":"legacy"}if(s.includes("fees"))if(r.type!=="legacy"&&r.type!=="eip2930"){if(typeof r.maxFeePerGas>"u"||typeof r.maxPriorityFeePerGas>"u"){let w=await g(),{maxFeePerGas:v,maxPriorityFeePerGas:E}=await Xh(e,{block:w,chain:o,request:r});if(typeof r.maxPriorityFeePerGas>"u"&&r.maxFeePerGas&&r.maxFeePerGas<E)throw new Kl({maxPriorityFeePerGas:E});r.maxPriorityFeePerGas=E,r.maxFeePerGas=v}}else{if(typeof r.maxFeePerGas<"u"||typeof r.maxPriorityFeePerGas<"u")throw new Fo;if(typeof r.gasPrice>"u"){let w=await g(),{gasPrice:v}=await Xh(e,{block:w,chain:o,request:r,type:"legacy"});r.gasPrice=v}}return s.includes("gas")&&typeof h>"u"&&(r.gas=await oe(e,Yl,"estimateGas")({...r,account:f,prepare:f?.type==="local"?[]:["blobVersionedHashes"]})),a?.fn&&a.runAt?.includes("afterFillParameters")&&(r=await a.fn({...r,chain:o},{client:e,phase:"afterFillParameters"})),Dt(r),delete r.parameters,r}var ad,Z6,Qh,cd=C(()=>{Ye();W6();ey();ka();Lh();sd();Lt();Qu();el();wh();vh();vt();wi();Uo();Eh();Jh();Mo();ad=["blobVersionedHashes","chainId","fees","gas","nonce","type"],Z6=new Map,Qh=new zt(128)});async function Yl(e,t){let{account:r=e.account,prepare:n=!0}=t,o=r?ce(r):void 0,i=(()=>{if(Array.isArray(n))return n;if(o?.type!=="local")return["blobVersionedHashes"]})();try{let s=await(async()=>{if(t.to)return t.to;if(t.authorizationList&&t.authorizationList.length>0)return await Os({authorization:t.authorizationList[0]}).catch(()=>{throw new L("`to` is required. Could not infer from `authorizationList`")})})(),{accessList:a,authorizationList:c,blobs:d,blobVersionedHashes:f,blockNumber:u,blockTag:l,data:p,gas:m,gasPrice:h,maxFeePerBlobGas:y,maxFeePerGas:b,maxPriorityFeePerGas:x,nonce:g,value:w,stateOverride:v,...E}=n?await zo(e,{...t,parameters:i,to:s}):t;if(m&&t.gas!==m)return m;let N=(typeof u=="bigint"?V(u):void 0)||l,U=kl(v);Dt(t);let R=e.chain?.formatters?.transactionRequest?.format,O=(R||sr)({...on(E,{format:R}),account:o,accessList:a,authorizationList:c,blobs:d,blobVersionedHashes:f,data:p,gasPrice:h,maxFeePerBlobGas:y,maxFeePerGas:b,maxPriorityFeePerGas:x,nonce:g,to:s,value:w},"estimateGas");return BigInt(await e.request({method:"eth_estimateGas",params:U?[O,N??e.experimental_blockTag??"latest",U]:N?[O,N]:[O]}))}catch(s){throw g6(s,{...t,account:o,chain:e.chain})}}var ey=C(()=>{Ye();le();Du();xe();w6();xa();Fi();Oh();Uo();cd()});async function Xl(e,t){let{abi:r,address:n,args:o,functionName:i,dataSuffix:s=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=Yt({abi:r,args:o,functionName:i});try{return await oe(e,Yl,"estimateGas")({data:`${c}${s?s.replace("0x",""):""}`,to:n,...a})}catch(d){let f=a.account?ce(a.account):void 0;throw _a(d,{abi:r,address:n,args:o,docsPath:"/docs/contract/estimateContractGas",functionName:i,sender:f?.address})}}var ty=C(()=>{Ye();vi();Ul();vt();ey()});async function Jl(e,t){let{abi:r,address:n,args:o,functionName:i,dataSuffix:s=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=a.account?ce(a.account):e.account,d=Yt({abi:r,args:o,functionName:i});try{let{data:f}=await oe(e,Bl,"call")({batch:!1,data:`${d}${s?s.replace("0x",""):""}`,to:n,...a,account:c}),u=Bu({abi:r,args:o,functionName:i,data:f||"0x"}),l=r.filter(p=>"name"in p&&p.name===t.functionName);return{result:u,request:{abi:l,address:n,args:o,dataSuffix:s,functionName:i,...a,account:c}}}catch(f){throw _a(f,{abi:r,address:n,args:o,docsPath:"/docs/contract/simulateContract",functionName:i,sender:c?.address})}}var ry=C(()=>{Ye();Nm();vi();Ul();vt();Ch()});function zi(e,t,r){let n=++E4,o=()=>Ql.get(e)||[],i=()=>{let u=o().filter(l=>l.id!==n);if(u.length===0){Ql.delete(e),ny.delete(e);return}Ql.set(e,u)},s=()=>{let f=o();if(!f.some(l=>l.id===n))return;let u=ny.get(e);if(f.length===1&&u){let l=u();l instanceof Promise&&l.catch(()=>{})}i()},a=o();if(Ql.set(e,[...a,{id:n,fns:t}]),a&&a.length>0)return s;let c={};for(let f in t)c[f]=((...u)=>{let l=o();if(l.length!==0)for(let p of l)p.fns[f]?.(...u)});let d=r(c);return typeof d=="function"&&ny.set(e,d),s}var Ql,ny,E4,ep=C(()=>{Ql=new Map,ny=new Map,E4=0});function tp(e,{emitOnBegin:t,initialWaitTime:r,interval:n}){let o=!0,i=()=>o=!1;return(async()=>{let a;t&&(a=await e({unpoll:i}));let c=await r?.(a)??n;await Xc(c);let d=async()=>{o&&(await e({unpoll:i}),await Xc(n),d())};d()})(),i}var oy=C(()=>{Ah()});function Y6(e){let t=(o,i)=>({clear:()=>i.delete(o),get:()=>i.get(o),set:s=>i.set(o,s)}),r=t(e,_4),n=t(e,A4);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function X6(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){let n=Y6(t),o=n.response.get();if(o&&r>0&&Date.now()-o.created.getTime()<r)return o.data;let i=n.promise.get();i||(i=e(),n.promise.set(i));try{let s=await i;return n.response.set({created:new Date,data:s}),s}finally{n.promise.clear()}}var _4,A4,J6=C(()=>{_4=new Map,A4=new Map});async function Q6(e,{cacheTime:t=e.cacheTime}={}){let r=await X6(()=>e.request({method:"eth_blockNumber"}),{cacheKey:T4(e.uid),cacheTime:t});return BigInt(r)}var T4,e5=C(()=>{J6();T4=e=>`blockNumber.${e}`});var it,ar,Mn=C(()=>{le();it=class extends L{constructor({docsPath:t}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(`
40
- `),{docsPath:t,docsSlug:"account",name:"AccountNotFoundError"})}},ar=class extends L{constructor({docsPath:t,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:t,metaMessages:r,name:"AccountTypeNotSupportedError"})}}});async function rp(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}var iy=C(()=>{});async function Ho(e,t){let{account:r=e.account,assertChainId:n=!0,chain:o=e.chain,accessList:i,authorizationList:s,blobs:a,data:c,dataSuffix:d=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,gas:f,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:p,maxPriorityFeePerGas:m,nonce:h,type:y,value:b,...x}=t;if(typeof r>"u")throw new it({docsPath:"/docs/actions/wallet/sendTransaction"});let g=r?ce(r):null,w;try{Dt(t);let v=await(async()=>{if(t.to)return t.to;if(t.to!==null&&s&&s.length>0)return await Os({authorization:s[0]}).catch(()=>{throw new L("`to` is required. Could not infer from `authorizationList`.")})})();if(g?.type==="json-rpc"||g===null){let E;o!==null&&(E=await oe(e,qt,"getChainId")({}),n&&Ea({currentChainId:E,chain:o}));let B=e.chain?.formatters?.transactionRequest?.format,U=(B||sr)({...on(x,{format:B}),accessList:i,account:g,authorizationList:s,blobs:a,chainId:E,data:d?_r([c??"0x",d]):c,gas:f,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:p,maxPriorityFeePerGas:m,nonce:h,to:v,type:y,value:b},"sendTransaction"),R=sy.get(e.uid),T=R?"wallet_sendTransaction":"eth_sendTransaction";try{return await e.request({method:T,params:[U]},{retryCount:0})}catch(O){if(R===!1)throw O;let z=O;if(z.name==="InvalidInputRpcError"||z.name==="InvalidParamsRpcError"||z.name==="MethodNotFoundRpcError"||z.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[U]},{retryCount:0}).then(P=>(sy.set(e.uid,!0),P)).catch(P=>{let _=P;throw _.name==="MethodNotFoundRpcError"||_.name==="MethodNotSupportedRpcError"?(sy.set(e.uid,!1),z):_});throw z}}if(g?.type==="local"){let E=(()=>{if(!g.nonceManager||typeof h<"u")return g.nonceManager;let O=g.nonceManager;return{consume(z){return w={address:z.address,chainId:z.chainId},O.consume(z)},get(z){return O.get(z)},increment(z){return O.increment(z)},reset(z){return O.reset(z)}}})(),B=await oe(e,zo,"prepareTransactionRequest")({account:g,accessList:i,authorizationList:s,blobs:a,chain:o,data:d?_r([c??"0x",d]):c,gas:f,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:p,maxPriorityFeePerGas:m,nonce:h,nonceManager:E,parameters:[...ad,"sidecars"],type:y,value:b,...x,to:v}),N=o?.serializers?.transaction,U=await g.signTransaction(B,{serializer:N}),R=(o??e.chain)?.serializers?.transactionEnvelope,T=R?await R({serializedTransaction:U,transaction:B}):U;return await oe(e,rp,"sendRawTransaction")({serializedTransaction:T})}throw g?.type==="smart"?new ar({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new ar({docsPath:"/docs/actions/wallet/sendTransaction",type:g?.type})}catch(v){throw v instanceof ar?v:(w&&g?.nonceManager?.reset(w),No(v,{...t,account:g,chain:t.chain||void 0}))}}var sy,dd=C(()=>{Ye();Mn();le();Du();Cl();or();ed();xa();Fi();vt();wi();Uo();Mo();cd();iy();sy=new zt(128)});async function Pr(e,t){return Pr.internal(e,Ho,"sendTransaction",t)}var fd=C(()=>{Ye();Mn();vi();Ul();vt();dd();(function(e){async function t(r,n,o,i){let{abi:s,account:a=r.account,address:c,args:d,functionName:f,...u}=i;if(typeof a>"u")throw new it({docsPath:"/docs/contract/writeContract"});let l=a?ce(a):null,p=Yt({abi:s,args:d,functionName:f});try{return await oe(r,n,o)({data:p,to:c,account:l,...u})}catch(m){throw _a(m,{abi:s,address:c,args:d,docsPath:"/docs/contract/writeContract",functionName:f,sender:l?.address})}}e.internal=t})(Pr||(Pr={}))});async function a5(e,{blockHash:t,blockNumber:r,blockTag:n,hash:o,index:i,sender:s,nonce:a}){let c=n||"latest",d=r!==void 0?V(r):void 0,f=null;if(o?f=await e.request({method:"eth_getTransactionByHash",params:[o]},{dedupe:!0}):t?f=await e.request({method:"eth_getTransactionByBlockHashAndIndex",params:[t,V(i)]},{dedupe:!0}):(d||c)&&typeof i=="number"?f=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[d||c,V(i)]},{dedupe:!!d}):s&&typeof a=="number"&&(f=await e.request({method:"eth_getTransactionBySenderAndNonce",params:[s,V(a)]},{dedupe:!0})),!f)throw new Fs({blockHash:t,blockNumber:r,blockTag:c,hash:o,index:i});return(e.chain?.formatters?.transaction?.format||Fn)(f,"getTransaction")}var c5=C(()=>{Lt();xe();Aa()});async function fp(e,{hash:t}){let r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new Ms({hash:t});return(e.chain?.formatters?.transactionReceipt?.format||td)(r,"getTransactionReceipt")}var d5=C(()=>{Lt();rd()});function f5(e,{emitOnBegin:t=!1,emitMissed:r=!1,onBlockNumber:n,onError:o,poll:i,pollingInterval:s=e.pollingInterval}){let a=typeof i<"u"?i:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")),c;return a?(()=>{let u=qe(["watchBlockNumber",e.uid,t,r,s]);return zi(u,{onBlockNumber:n,onError:o},l=>tp(async()=>{try{let p=await oe(e,Q6,"getBlockNumber")({cacheTime:0});if(c!==void 0){if(p===c)return;if(p-c>1&&r)for(let m=c+1n;m<p;m++)l.onBlockNumber(m,c),c=m}(c===void 0||p>c)&&(l.onBlockNumber(p,c),c=p)}catch(p){l.onError?.(p)}},{emitOnBegin:t,interval:s}))})():(()=>{let u=qe(["watchBlockNumber",e.uid,t,r]);return zi(u,{onBlockNumber:n,onError:o},l=>{let p=!0,m=()=>p=!1;return(async()=>{try{let h=(()=>{if(e.transport.type==="fallback"){let b=e.transport.transports.find(x=>x.config.type==="webSocket"||x.config.type==="ipc");return b?b.value:e.transport}return e.transport})(),{unsubscribe:y}=await h.subscribe({params:["newHeads"],onData(b){if(!p)return;let x=De(b.result?.number);l.onBlockNumber(x,c),c=x},onError(b){l.onError?.(b)}});m=y,p||m()}catch(h){o?.(h)}})(),()=>m()})})()}var u5=C(()=>{Pt();vt();ep();oy();Ar();e5()});async function l5(e,t){let{checkReplacement:r=e.chain?.supportsTransactionReplacementDetection??!0,confirmations:n=1,hash:o,onReplaced:i,retryCount:s=6,retryDelay:a=({count:E})=>~~(1<<E)*200,timeout:c=18e4}=t,d=E=>e.chain?.transactionReplacement?.getKey?.(E)??String(E.nonce),f=t.pollingInterval?t.pollingInterval:e.chain?.experimental_preconfirmationTime?e.chain.experimental_preconfirmationTime:e.pollingInterval,u=qe(["waitForTransactionReceipt",e.uid,o,{checkReplacement:r,confirmations:n,pollingInterval:f,retryCount:s,timeout:c}]),l,p,m,h=!1,y,b,{promise:x,resolve:g,reject:w}=Sa(),v=c?setTimeout(()=>{b?.(),y?.(),w(new Ju({hash:o}))},c):void 0;return y=zi(u,{onReplaced:i,resolve:g,reject:w},async E=>{if(m=await oe(e,fp,"getTransactionReceipt")({hash:o}).catch(()=>{}),m&&n<=1){clearTimeout(v),E.resolve(m),y?.();return}b=oe(e,f5,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:f,async onBlockNumber(B){let N=R=>{clearTimeout(v),b?.(),R(),y?.()},U=B;if(!h)try{if(m){if(n>1&&(!m.blockNumber||U-m.blockNumber+1n<n))return;N(()=>E.resolve(m));return}if(r&&!l&&(h=!0,await Ui(async()=>{l=await oe(e,a5,"getTransaction")({hash:o}),l.blockNumber&&(U=l.blockNumber)},{delay:a,retryCount:s}),h=!1),m=await oe(e,fp,"getTransactionReceipt")({hash:o}),n>1&&(!m.blockNumber||U-m.blockNumber+1n<n))return;N(()=>E.resolve(m))}catch(R){if(R instanceof Fs||R instanceof Ms){if(!l){h=!1;return}if(l.blockNumber){h=!1;return}try{p=l,h=!0;let T=await Ui(()=>oe(e,Br,"getBlock")({blockNumber:U,includeTransactions:!0}),{delay:a,retryCount:s,shouldRetry:({error:_})=>_ instanceof Ia});h=!1;let O=d(p),z=T.transactions.find(_=>Ht(_.from,p.from)&&_.hash!==p.hash&&d(_)===O);if(!z||(m=await oe(e,fp,"getTransactionReceipt")({hash:z.hash}),n>1&&(!m.blockNumber||U-m.blockNumber+1n<n)))return;let P=e.chain?.transactionReplacement?.getReason?.({replaced:p,replacement:z})??B4(p,z);N(()=>{E.onReplaced?.({reason:P,replacedTransaction:p,transaction:z,transactionReceipt:m}),E.resolve(m)})}catch(T){N(()=>E.reject(T))}}else N(()=>E.reject(R))}}})}),x}function B4(e,t){return(t.to&&e.to?Ht(t.to,e.to):t.to===e.to)&&t.value===e.value&&t.input===e.input?"repriced":t.from===t.to&&t.value===0n?"cancelled":"replaced"}var p5=C(()=>{Zh();Lt();Si();vt();ep();Il();pl();Ar();ka();c5();d5();u5()});function up(e,t){if(typeof e=="bigint")return e;let r=e.decimals??t;return k6(e.formatted,P4(r))}function P4(e){if(e===void 0)throw new Error("Token decimals are required. Pass `amount.decimals` or select a declared token.");return e}function lp(e,t){return typeof e=="bigint"?t:e.decimals??t}function $o(e,t){let{decimals:r,token:n}=t,o=R4(e,n);if(o)return{address:o.address,decimals:r??o.decimals};if(pe(n,{strict:!1}))return{address:n,decimals:r??C4(e,n)};throw new Error(`Token "${n}" is not a declared ERC-20 token on the client's \`tokens\` array (with an address for the client's chain), and is not a valid address.`)}function R4(e,t){let r=e.tokens,n=e.chain?.id;if(!r||n===void 0)return;let o=O4(r,t);if(o)return fy(o,n);if(pe(t,{strict:!1}))for(let i of r){let s=fy(i,n);if(s&&Ht(s.address,t))return s}}function fy(e,t){let r=e.addresses[t];if(r)return{address:r,currency:e.currency,decimals:e.decimals,name:e.name,popular:e.popular,symbol:e.symbol}}function O4(e,t){let r=t.toLowerCase();for(let n of e)if(n.symbol?.toLowerCase()===r)return n}function C4(e,t){let r=e.tokens,n=e.chain?.id;if(r&&n!==void 0)for(let o of r){let i=fy(o,n);if(i&&Ht(i.address,t))return i.decimals}}function Ba(e){let{account:t,chain:r,gas:n,maxFeePerGas:o,maxPriorityFeePerGas:i,nonce:s}=e;return{account:t,chain:r,gas:n,maxFeePerGas:o,maxPriorityFeePerGas:i,nonce:s}}function pp(e){return{...e,data:Yt(e),to:e.address}}var ld=C(()=>{Zt();Si();qh();B6()});async function mp(e,{serializedTransaction:t,throwOnReceiptRevert:r,timeout:n}){let o=await e.request({method:"eth_sendRawTransactionSync",params:n?[t,n]:[t]},{retryCount:0}),s=(e.chain?.formatters?.transactionReceipt?.format||td)(o);if(s.status==="reverted"&&r)throw new Ii({receipt:s});return s}var uy=C(()=>{Lt();rd()});async function hp(e,t){let{account:r=e.account,assertChainId:n=!0,chain:o=e.chain,accessList:i,authorizationList:s,blobs:a,data:c,dataSuffix:d=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,gas:f,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:p,maxPriorityFeePerGas:m,nonce:h,pollingInterval:y,throwOnReceiptRevert:b,type:x,value:g,...w}=t,v=t.timeout??Math.max((o?.blockTime??0)*3,5e3);if(typeof r>"u")throw new it({docsPath:"/docs/actions/wallet/sendTransactionSync"});let E=r?ce(r):null,B;try{Dt(t);let N=await(async()=>{if(t.to)return t.to;if(t.to!==null&&s&&s.length>0)return await Os({authorization:s[0]}).catch(()=>{throw new L("`to` is required. Could not infer from `authorizationList`.")})})();if(E?.type==="json-rpc"||E===null){let U;o!==null&&(U=await oe(e,qt,"getChainId")({}),n&&Ea({currentChainId:U,chain:o}));let R=e.chain?.formatters?.transactionRequest?.format,O=(R||sr)({...on(w,{format:R}),accessList:i,account:E,authorizationList:s,blobs:a,chainId:U,data:d?_r([c??"0x",d]):c,gas:f,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:p,maxPriorityFeePerGas:m,nonce:h,to:N,type:x,value:g},"sendTransaction"),z=ly.get(e.uid),P=z?"wallet_sendTransaction":"eth_sendTransaction",_=await(async()=>{try{return await e.request({method:P,params:[O]},{retryCount:0})}catch(k){if(z===!1)throw k;let M=k;if(M.name==="InvalidInputRpcError"||M.name==="InvalidParamsRpcError"||M.name==="MethodNotFoundRpcError"||M.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[O]},{retryCount:0}).then($=>(ly.set(e.uid,!0),$)).catch($=>{let F=$;throw F.name==="MethodNotFoundRpcError"||F.name==="MethodNotSupportedRpcError"?(ly.set(e.uid,!1),M):F});throw M}})(),I=await oe(e,l5,"waitForTransactionReceipt")({checkReplacement:!1,hash:_,pollingInterval:y,timeout:v});if(b&&I.status==="reverted")throw new Ii({receipt:I});return I}if(E?.type==="local"){let U=(()=>{if(!E.nonceManager||typeof h<"u")return E.nonceManager;let _=E.nonceManager;return{consume(I){return B={address:I.address,chainId:I.chainId},_.consume(I)},get(I){return _.get(I)},increment(I){return _.increment(I)},reset(I){return _.reset(I)}}})(),R=await oe(e,zo,"prepareTransactionRequest")({account:E,accessList:i,authorizationList:s,blobs:a,chain:o,data:d?_r([c??"0x",d]):c,gas:f,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:p,maxPriorityFeePerGas:m,nonce:h,nonceManager:U,parameters:[...ad,"sidecars"],type:x,value:g,...w,to:N}),T=o?.serializers?.transaction,O=await E.signTransaction(R,{serializer:T}),z=(o??e.chain)?.serializers?.transactionEnvelope,P=z?await z({serializedTransaction:O,transaction:R}):O;return await oe(e,mp,"sendRawTransactionSync")({serializedTransaction:P,throwOnReceiptRevert:b,timeout:t.timeout})}throw E?.type==="smart"?new ar({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new ar({docsPath:"/docs/actions/wallet/sendTransactionSync",type:E?.type})}catch(N){throw N instanceof ar?N:(B&&!(N instanceof Ii)&&E?.nonceManager?.reset(B),No(N,{...t,account:E,chain:t.chain||void 0}))}}var ly,py=C(()=>{Ye();Mn();le();Lt();Du();Cl();or();ed();xa();Fi();vt();wi();Uo();Mo();p5();cd();uy();ly=new zt(128)});async function Pa(e,t){return Pr.internal(e,hp,"sendTransactionSync",t)}var yp=C(()=>{py();fd()});var W5=["invalid_arguments","invalid_config","invalid_record","config_conflict","agent_policy","human_only","confirmation_required","sale_not_approved","trust_required","signer_required","signer_init_only","credentials_required","backup_secret_required","work_dir_required","max_price_required","budget_required","budget_exceeded","base_rpc_required","transport_required","near_wallet_required","base_wallet_required","base_unavailable","route_unavailable","file_required","offer_required","purchase_required","origin_required","origin_asset_required","origin_not_allowed","resource_not_allowed","path_not_allowed","output_exists","unknown_file","already_registered","taken_down","sales_stopped","unknown_moderator","storage_required","funding_refused","file_storage_low","protocol_fee_above_max","price_mismatch","price_above_max","recipient_mismatch","file_mismatch","network_mismatch","token_mismatch","method_mismatch","untrusted_contract","file_invalid","bad_requirements","insufficient_balance","smart_wallet_unsupported","bad_signature","payment_rejected","purchase_open","payment_id_conflict","payment_expired","payment_not_found","payment_used","quote_refused","quote_expired","settlement_pending","transaction_uncertain","not_sponsored","not_buyer","bad_magic","unsupported_version","bad_chunk_size","header_too_large","bad_header","bad_stanza","file_id_mismatch","cipher_hash_mismatch","seller_signature_invalid","bad_body_length","chunk_hash_mismatch","no_usable_stanza","key_unwrap_failed","header_mac_invalid","chunk_invalid","meta_invalid","preview_invalid","ckd_failed","ckd_invalid","rejected","wrong_chain","wrong_identity","invalid_signature","missing_method","invalid_response","wallet_error","store_conflict","lease_busy","source_changed","sell_incomplete","recovery_not_final","transport","refused","bad_request","bad_deadline","limited","duplicate","in_flight","unavailable","disabled","rate_limited","budget","busy","not_found","internal","relayer_unavailable","relayer_rate_limited","base_rpc_rate_limited","near_rpc_rate_limited","host_payment_failed","facilitator_busy","bad_response","not_authorized","cancelled","too_large","download_limited","download_in_progress","file_expired","upload_expired","upload_conflict","upload_incomplete","host_capacity","operation_failed"],yd={route_unavailable:"This file does not support the selected payment route.",host_payment_failed:"Payment submission failed. Keep the saved purchase and check final status before retrying.",bad_request:"The request is invalid. Check its fields before retrying.",bad_deadline:"The authorization deadline is invalid or expired.",invalid_arguments:"Invalid arguments. Run annon --help.",invalid_record:"Invalid saved record. Export necessary test evidence and clear development state.",transport:"The service could not be reached. Keep saved state and retry later.",recovery_not_final:"The recovery grant is not final. Resume the saved recovery later.",invalid_signature:"The wallet did not authorize the exact requested message.",operation_failed:"Operation failed. Check configuration, funding and final purchase status before retrying. Saved encrypted records are retained.",transaction_uncertain:"Transaction submission is uncertain. Check the saved purchase and transaction hash before retrying.",quote_refused:"The 1Click quote was refused. Review the source asset and amount before retrying.",base_rpc_rate_limited:"The Base RPC is rate limiting requests. Configure a Base RPC endpoint with an API key (baseRpc).",near_rpc_rate_limited:"Configure a NEAR RPC endpoint with an API key (nearRpc).",budget_exceeded:"The persisted spending budget is exhausted.",download_limited:"Download limit reached. Wait before downloading again.",download_in_progress:"Another download is active. Wait before retrying.",rate_limited:"The host is busy. Wait before retrying.",unavailable:"The service is temporarily unavailable. Wait before retrying.",transport_required:"Configure a trusted relayer before a Base purchase.",relayer_unavailable:"Base sponsorship checks are unavailable. Retry before paying.",not_sponsored:"This listing does not qualify for Base sponsorship. Do not pay through this route.",wrong_identity:"The wallet does not control the required identity.",settlement_pending:"The purchase is still settling. Wait before retrying the saved purchase.",protocol_fee_above_max:"The advertised protocol fee exceeds maxProtocolFee. Review the fee in human configuration.",funding_refused:"File funding was refused. Correct the cause before retrying.",file_storage_low:"This file needs more purchase storage funding before a NEAR or 1Click payment.",source_changed:"The source changed between passes. Resume sell with the original plaintext and saved fileId.",quote_expired:"The 1Click quote expired. Run buy again.",storage_required:"Prepay storage with storageDeposit before register or reopen, then resume the saved operation.",unknown_file:"The configured contract has no such file. Check the file ID and deployment.",taken_down:"The moderator has taken down this file; key release is blocked.",sales_stopped:"The seller has stopped new sales. Use a saved purchase to open an earlier purchase.",unknown_moderator:"Review this file's moderator and explicitly accept it with the moderator option before buying.",price_above_max:"The registered price exceeds maxPrice. Review the current terms before buying.",untrusted_contract:"The offer names a different contract. Review that deployment and configure it explicitly.",network_mismatch:"The deployment network or USDC asset differs from the configured network. Check the configuration.",store_conflict:"Another process updated this purchase. Keep the encrypted state and check status before retrying.",file_invalid:"The file failed SDK verification. Obtain the registered file from its host.",file_mismatch:"The file or offer differs from its registered commitment. Obtain the correct file or offer.",bad_requirements:"The host offer failed SDK validation. Obtain an updated Annon offer.",not_authorized:"The host has not accepted this final grant. Check final purchase status and the resource URL."};function bd(e){return typeof e=="string"&&W5.includes(e)}function Na(e){let t=e&&typeof e=="object"&&"code"in e?e.code:void 0;return t==="transport"||t==="base_rpc_rate_limited"||t==="near_rpc_rate_limited"}var S=class extends Error{code;constructor(t,r=yd[t]??`${t.replaceAll("_"," ")}.`,n){super(r,n),this.code=t,this.name="AnnonError"}},Z5=new Set(["budget","settlement_pending","transaction_uncertain","transport","base_rpc_rate_limited","near_rpc_rate_limited","relayer_unavailable","relayer_rate_limited","download_limited","download_in_progress","rate_limited","unavailable","in_flight","busy","facilitator_busy","lease_busy","recovery_not_final","host_capacity","limited"]),Y5=new Set(["agent_policy","human_only","confirmation_required","sale_not_approved","trust_required"]),X5=new Set(["invalid_arguments","invalid_config","invalid_record","config_conflict","agent_policy","human_only","confirmation_required","sale_not_approved","trust_required","signer_required","signer_init_only","credentials_required","backup_secret_required","work_dir_required","max_price_required","budget_required","base_rpc_required","transport_required","near_wallet_required","base_wallet_required","base_unavailable","route_unavailable","file_required","offer_required","purchase_required","origin_required","origin_asset_required","origin_not_allowed","resource_not_allowed","path_not_allowed","output_exists","network_mismatch","bad_request","bad_deadline"]);function Ko(e){let t=e&&typeof e=="object"?e:{};if(!bd(t.code))return{code:"operation_failed",message:yd.operation_failed??"Operation failed.",exitCode:1};let r=t.code,n=e instanceof S&&e.name==="AdapterError"?e:void 0,o=a=>typeof a=="string"&&/^0x[0-9a-f]{64}$/.test(a),i=typeof t.retryAfterSeconds=="number"&&t.retryAfterSeconds>=0?Math.ceil(t.retryAfterSeconds):NaN,s=Number.isSafeInteger(i)?i:r==="settlement_pending"?30:void 0;return{code:r,message:(r==="route_unavailable"?yd.route_unavailable:n?.message)??(yd[r]??`${r.replaceAll("_"," ")}.`)+(e instanceof S&&e.name==="SellError"&&r!=="source_changed"?" Resume sell with the original plaintext and saved fileId.":""),exitCode:(r==="route_unavailable"?2:n?.exitCode)??(Z5.has(r)?4:Y5.has(r)?3:X5.has(r)?2:1),...o(t.fileId)?{fileId:t.fileId}:{},...o(t.purchaseId)?{purchaseId:t.purchaseId}:{},...typeof t.txHash=="string"?{txHash:t.txHash}:{},...typeof t.minimumAmountUsdc=="string"&&/^(0|[1-9][0-9]*)(\.[0-9]+)?$/.test(t.minimumAmountUsdc)?{minimumAmountUsdc:t.minimumAmountUsdc}:{},...s!==void 0?{retryAfterSeconds:s}:{}}}function X(e,t="invalid_record"){if(e==null)throw new S(t);return e}var gd=e=>Object.freeze(e());function J5(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Fa(e){if(!J5(e))throw new TypeError("Uint8Array expected")}function Ma(e,t){if(typeof t!="string")throw new TypeError(`${e}: string expected`);return!0}function Py(e,t="number"){if(typeof e!="number")throw new TypeError(`${t}: expected number, got ${typeof e}`);if(!Number.isSafeInteger(e))throw new RangeError(`${t}: expected safe integer, got ${e}`)}function Ry(...e){let t=i=>i,r=(i,s)=>a=>i(s(a)),n=e.map(i=>i.encode).reduceRight(r,t),o=e.map(i=>i.decode).reduce(r,t);return{encode:n,decode:o}}var Q5=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();var ky=(()=>{try{let e=new TextDecoder;return e.decode(Uint8Array.of(65,48,43,127))==="A0+\x7F"?e:void 0}catch{return}})(),kp=8192;function e8(e){let t=e.length;if(ky!==void 0&&t>=12)return ky.decode(e);if(t<=kp)return String.fromCharCode.apply(null,e);let r="";for(let n=0;n<t;n+=kp)r+=String.fromCharCode.apply(null,e.subarray(n,n+kp));return r}function Oy(e){if(Py(e),e<=0||e>8)throw new RangeError("radix2: bits should be in (0..8]");let t=Q5[e]-1;return{encode:r=>{Fa(r);let n=r.length,o=new Uint8Array(Math.ceil(n*8/e)),i=0,s=0,a=0;for(let c=0;c<n;)for(c+2<n?(i=i<<24|r[c]<<16|r[c+1]<<8|r[c+2],s+=24,c+=3):(i=(i<<8|r[c])&65535,s+=8,c++);s-=e,o[a++]=i>>s&t,!(s<e););return s>0&&(o[a]=i<<e-s&t),o},decode:r=>{let n=r.length,o=new Uint8Array(Math.floor(n*e/8)),i=0,s=0,a=0;for(let c=0;c<n;c++)for(i=(i<<e|r[c])&65535,s+=e;s>=8;s-=8)o[a++]=i>>s-8&255;if(i=i<<8-s&255,s>=e)throw new Error("Excess padding");if(i>0)throw new Error(`Non-zero padding: ${i}`);return o}}}function Bp(e,t){let r=e.length;if(r>128)throw new Error("alphabet: max 128 letters");let n=new Uint8Array(r),o=new Int8Array(128).fill(-1);for(let i=0;i<r;i++){let s=e.charCodeAt(i);if(e.codePointAt(i)!==s||s>127)throw new Error("alphabet: single-char ASCII letters only");n[i]=s,o[s]=i}if(t!==void 0)for(let i of Object.keys(t)){let s=i.charCodeAt(0),a=o[t[i].charCodeAt(0)];if(i.length!==1||s>127||a===void 0||a===-1)throw new Error(`alphabet: invalid alias ${i}`);o[s]=a}return{encode:i=>{let s=new Uint8Array(i.length);for(let a=0;a<i.length;a++){let c=i[a],d=n[c];if(d===void 0)throw new Error(`alphabet.encode: invalid digit ${c}`);s[a]=d}return e8(s)},decode:i=>{Ma("decode",i);let s=i.length,a=new Uint8Array(s);for(let c=0;c<s;c++){let d=i.charCodeAt(c),f=d<128?o[d]:-1;if(f===-1)throw new Error(`Unknown letter "${i[c]}". Allowed: ${e}`);a[c]=f}return a}}}function t8(e,t="="){return Py(e),Ma("padding",t),{encode(r){for(;r.length*e%8;)r+=t;return r},decode(r){Ma("decode",r);let n=r.length;if(n*e%8)throw new Error("padding: invalid length");for(;n>0&&r[n-1]===t;n--)if((n-1)*e%8===0)throw new Error("padding: excess padding");return r.slice(0,n)}}}var r8=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",n8=/[\t\n\f\r ]/,o8=(e,t)=>{Ma("base64",e);let r=t?"base64url":"base64";if(e.length>0&&n8.test(e))throw new Error("invalid base64");return Uint8Array.fromBase64(e,{alphabet:r,lastChunkHandling:"strict"})},i8=gd(()=>Ry(Oy(6),Bp("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),t8(6)));var wd=gd(()=>r8?{encode(e){return Fa(e),e.toBase64()},decode(e){return o8(e,!1)}}:i8);var Cy=gd(()=>Ry(Oy(6),Bp("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"))),s8=656356768;var By=65536,a8=2048,c8=4096,d8=(e,t)=>({encode:r=>{Fa(r);let n=r.length;if(n===0)return new Uint8Array(0);if(n>=By)throw new Error("invalid length");let o=0;for(;o<n-1&&r[o]===0;)o++;let i=Math.ceil(n/2),s=new Uint16Array(i),a=n&1;a&&(s[0]=r[0]);for(let m=a,h=a;m<n;m+=2,h++)s[h]=r[m]<<8|r[m+1];let c=[],d=0;for(;d<i;){let m=0;for(let h=d;h<i;h++){let y=m*65536+s[h],b=Math.floor(y/t);m=y-b*t,s[h]=b,b===0&&h===d&&d++}c.push(m)}let f=c.length-1,u=f*5;for(let m=c[f];u++,!(m<e);m=Math.floor(m/e));let l=new Uint8Array(o+u),p=l.length-1;for(let m=0;m<f;m++){let h=c[m];for(let y=0;y<5;y++)l[p--]=h%e,h=Math.floor(h/e)}for(let m=c[f];p>=o;m=Math.floor(m/e))l[p--]=m%e;return l},decode:r=>{Fa(r);let n=r.length;if(n===0)return new Uint8Array(0);if(n>=By)throw new Error("invalid length");let o=0;for(;o<n-1&&r[o]===0;)o++;let i=new Uint16Array(Math.ceil(n*6/16)+1),s=0,a=0,c=n%5||5;for(;a<n;){let l=0,p=1;for(let h=a+c;a<h;a++){let y=r[a];if(y>=e)throw new Error(`invalid integer: ${y}`);l=l*e+y,p*=e}c=5;let m=l;for(let h=0;h<s;h++){let y=i[h]*p+m;m=Math.floor(y/65536),i[h]=y-m*65536}for(;m>0;m=Math.floor(m/65536))i[s++]=m%65536}let d=s===0?1:s*2-(i[s-1]<256?1:0),f=new Uint8Array(o+d),u=f.length-1;for(let l=0;l<s;l++){let p=i[l];f[u--]=p&255,u>=o&&(f[u--]=p>>8)}return f}}),f8=(e,t)=>{let r=Bp(t);return{encode(n){if(Fa(n),n.length>a8)throw new Error("invalid length");return r.encode(e.encode(n))},decode(n){if(Ma("baseN.decode",n),n.length>c8)throw new Error("invalid length");return e.decode(r.decode(n))}}},u8=d8(58,s8);var l8=e=>f8(u8,e),Ut=gd(()=>l8("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"));function st(e){let t=new Uint8Array(e.reduce((n,o)=>n+o.length,0)),r=0;for(let n of e)t.set(n,r),r+=n.length;return t}function xd(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function vd(e){return`0x${xd(e)}`}var Sd=BigInt(4294967295),Uy=BigInt(32);function p8(e,t=!1){return t?{h:Number(e&Sd),l:Number(e>>Uy&Sd)}:{h:Number(e>>Uy&Sd)|0,l:Number(e&Sd)|0}}function Ed(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=p8(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var m8=e=>e/2**32|0,h8=e=>e>>>0;function Ny(e,t,r,n){let o=m8(r),i=h8(r);e.setUint32(t,n?i:o,n),e.setUint32(t+4,n?o:i,n)}var Pp=(e,t,r)=>e>>>r,Rp=(e,t,r)=>e<<32-r|t>>>r,Wo=(e,t,r)=>e>>>r|t<<32-r,Zo=(e,t,r)=>e<<32-r|t>>>r,za=(e,t,r)=>e<<64-r|t>>>r-32,Ha=(e,t,r)=>e>>>r-32|t<<64-r;function Or(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}var Fy=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),My=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,zy=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Hy=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,$y=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),Ly=(e,t,r,n,o,i)=>t+r+n+o+i+(e/2**32|0)|0;function _d(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Ad=e=>e?`"${e}" `:"";function ut(e,t=""){if(typeof e!="number")throw new TypeError(Ad(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Ad(t)+"expected integer >= 0, got "+e);return e}function jy(e,t=""){if(typeof e!="boolean")throw new TypeError(Ad(t)+"expected boolean, got type="+typeof e);return e}function St(e,t,r=""){if(_d(e)&&(t===void 0||e.length===t))return e;t!==void 0&&ut(t,"length");let n=_d(e),o=t!==void 0?` of length ${t}`:"",i=n?`length=${e.length}`:`type=${typeof e}`,s=Ad(r)+"expected Uint8Array"+o+", got "+i;throw n?new RangeError(s):new TypeError(s)}function Td(e){if(typeof e!="function"||typeof e.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(ut(e.outputLen),ut(e.blockLen),e.outputLen<1||e.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var b8=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},Dy=(e,t)=>{b8(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function un(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Di(e,t){St(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw new RangeError('"output" expected length >= '+r)}function Op(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Cr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Id(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function fr(e,t){return e<<32-t|e>>>t}var g8=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function w8(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function x8(e){for(let t=0;t<e.length;t++)e[t]=w8(e[t]);return e}var Cp=g8?e=>e:x8,Gy=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",v8=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function kd(e){if(St(e),Gy)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=v8[e[r]];return t}function qy(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Bd(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(Gy)try{return Uint8Array.fromHex(e)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let t=e.length,r=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,i=0;o<r;o++,i+=2){let s=qy(e.charCodeAt(i)),a=qy(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function Up(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];St(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let i=e[n];r.set(i,o),o+=i.length}return r}function Vy(e,t,r="opts"){return Dy(e,"defaults"),t!==void 0&&Dy(t,r),Object.assign(Object.create(null),e,t)}function $a(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=Vy({},t,"info");let r=(o,i)=>e(i).update(o).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>e(o),Object.assign(r,t),Object.freeze(r)}function Ky(e=32){ut(e,"bytesLength");let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(e>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var La=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Wy(e,t,r){return e&t^~e&r}function Zy(e,t,r){return e&t^e&r^t&r}var Da=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,r,n,o){this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Id(this.buffer)}update(t){un(this),St(t);let{view:r,buffer:n,blockLen:o}=this,i=t.length,s=!1;for(let a=0;a<i;){let c=Math.min(o-this.pos,i-a);if(c===o){let d=Id(t);for(;o<=i-a;a+=o)this.process(d,a);s=!0;continue}n.set(a===0&&c===i?t:t.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(r,0),this.pos=0,s=!0)}return this.length+=t.length,s&&this.roundClean(),this}digestInto(t){un(this),Di(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;r[s++]=128,r.fill(0,s),this.padOffset>o-s&&(this.process(n,0),r.fill(0)),Ny(n,o-8,this.length*8,i),this.process(n,0),this.roundClean();let a=t===r?n:Id(t),c=this.outputLen,d=c/4,f=this.get();if(c%4||d>f.length)throw new Error("invalid outputLen");for(let u=0;u<d;u++)a.setUint32(4*u,f[u],i)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneIntoMeta(t){let{buffer:r,length:n,finished:o,destroyed:i,pos:s}=this;return t.destroyed=i,t.finished=o,t.length=n,t.pos=s,s&&t.buffer.set(r),t}clone(){return this._cloneInto()}},Yy=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Xy=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var S8=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Dn=new Uint32Array(64),Np=class extends Da{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(t,r){super(64,t,8,!1),this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:t,B:r,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[t,r,n,o,i,s,a,c]}set(t,r,n,o,i,s,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,r){for(let u=0;u<16;u++,r+=4)Dn[u]=t.getUint32(r,!1);for(let u=16;u<64;u++){let l=Dn[u-15],p=Dn[u-2],m=fr(l,7)^fr(l,18)^l>>>3,h=fr(p,17)^fr(p,19)^p>>>10;Dn[u]=h+Dn[u-7]+m+Dn[u-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:d,H:f}=this;for(let u=0;u<64;u++){let l=fr(a,6)^fr(a,11)^fr(a,25),p=f+l+Wy(a,c,d)+S8[u]+Dn[u]|0,h=(fr(n,2)^fr(n,13)^fr(n,22))+Zy(n,o,i)|0;f=d,d=c,c=a,a=s+p|0,s=i,i=o,o=n,n=p+h|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,d=d+this.G|0,f=f+this.H|0,this.set(n,o,i,s,a,c,d,f)}roundClean(){Cr(Dn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Cr(this.buffer)}},Fp=class extends Np{constructor(){super(32,Yy)}};var Jy=Ed(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),E8=Jy[0],_8=Jy[1],qn=new Uint32Array(80),jn=new Uint32Array(80),Mp=class extends Da{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(t,r){super(128,t,16,!1),this.Ah=r[0]|0,this.Al=r[1]|0,this.Bh=r[2]|0,this.Bl=r[3]|0,this.Ch=r[4]|0,this.Cl=r[5]|0,this.Dh=r[6]|0,this.Dl=r[7]|0,this.Eh=r[8]|0,this.El=r[9]|0,this.Fh=r[10]|0,this.Fl=r[11]|0,this.Gh=r[12]|0,this.Gl=r[13]|0,this.Hh=r[14]|0,this.Hl=r[15]|0}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:d,El:f,Fh:u,Fl:l,Gh:p,Gl:m,Hh:h,Hl:y}=this;return[t,r,n,o,i,s,a,c,d,f,u,l,p,m,h,y]}set(t,r,n,o,i,s,a,c,d,f,u,l,p,m,h,y){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=d|0,this.El=f|0,this.Fh=u|0,this.Fl=l|0,this.Gh=p|0,this.Gl=m|0,this.Hh=h|0,this.Hl=y|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,r){for(let g=0;g<16;g++,r+=4)qn[g]=t.getUint32(r),jn[g]=t.getUint32(r+=4);for(let g=16;g<80;g++){let w=qn[g-15]|0,v=jn[g-15]|0,E=Wo(w,v,1)^Wo(w,v,8)^Pp(w,v,7),B=Zo(w,v,1)^Zo(w,v,8)^Rp(w,v,7),N=qn[g-2]|0,U=jn[g-2]|0,R=Wo(N,U,19)^za(N,U,61)^Pp(N,U,6),T=Zo(N,U,19)^Ha(N,U,61)^Rp(N,U,6),O=zy(B,T,jn[g-7],jn[g-16]),z=Hy(O,E,R,qn[g-7],qn[g-16]);qn[g]=z|0,jn[g]=O|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:d,Dl:f,Eh:u,El:l,Fh:p,Fl:m,Gh:h,Gl:y,Hh:b,Hl:x}=this;for(let g=0;g<80;g++){let w=Wo(u,l,14)^Wo(u,l,18)^za(u,l,41),v=Zo(u,l,14)^Zo(u,l,18)^Ha(u,l,41),E=u&p^~u&h,B=l&m^~l&y,N=$y(x,v,B,_8[g],jn[g]),U=Ly(N,b,w,E,E8[g],qn[g]),R=N|0,T=Wo(n,o,28)^za(n,o,34)^za(n,o,39),O=Zo(n,o,28)^Ha(n,o,34)^Ha(n,o,39),z=n&i^n&a^i&a,P=o&s^o&c^s&c;b=h|0,x=y|0,h=p|0,y=m|0,p=u|0,m=l|0,{h:u,l}=Or(d|0,f|0,U|0,R|0),d=a|0,f=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let _=Fy(R,O,P);n=My(_,U,T,z),o=_|0}({h:n,l:o}=Or(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=Or(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Or(this.Ch|0,this.Cl|0,a|0,c|0),{h:d,l:f}=Or(this.Dh|0,this.Dl|0,d|0,f|0),{h:u,l}=Or(this.Eh|0,this.El|0,u|0,l|0),{h:p,l:m}=Or(this.Fh|0,this.Fl|0,p|0,m|0),{h,l:y}=Or(this.Gh|0,this.Gl|0,h|0,y|0),{h:b,l:x}=Or(this.Hh|0,this.Hl|0,b|0,x|0),this.set(n,o,i,s,a,c,d,f,u,l,p,m,h,y,b,x)}roundClean(){Cr(qn,jn)}destroy(){this.destroyed=!0,Cr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},zp=class extends Mp{constructor(){super(64,Xy)}};var ur=$a(()=>new Fp,La(1));var Hp=$a(()=>new zp,La(3));var et=new TextEncoder,Et=(...e)=>st(e),Y=e=>vd(e);function G(e,t){if(typeof e!="string"||!new RegExp(`^0x[0-9a-f]{${t*2}}$`).test(e))throw new TypeError(`expected canonical ${t}-byte hex`);return Uint8Array.from(e.slice(2).match(/../g)??[],r=>Number.parseInt(r,16))}function _t(e,t){if(typeof e!="bigint"&&(typeof e!="string"||e.length>Math.ceil(t*Math.LOG10E*Math.LN2)||!/^(0|[1-9][0-9]*)$/.test(e)))throw new TypeError("expected canonical unsigned integer");let r=BigInt(e);if(r<0n||r>=1n<<BigInt(t))throw new RangeError(`expected u${t}`);return r}function je(e,t){if(typeof e=="number"&&!Number.isSafeInteger(e))throw new RangeError("expected integer");let r=_t(typeof e=="number"?BigInt(e):e,t*8);return Uint8Array.from({length:t},()=>{let n=Number(r&255n);return r>>=8n,n})}var At=e=>{let t=et.encode(e);return Et(je(t.length,4),t)},Pd=(e,t)=>Y(ur(Et(et.encode(e),new Uint8Array([0]),t)));function be(e){if(typeof e!="string"||!/^(?=.{2,64}$)[a-z0-9]+(?:[._-][a-z0-9]+)*$/.test(e))throw new TypeError("invalid NEAR account id");return e}function Gn(e){if(!["near:mainnet","near:testnet","near:sandbox"].includes(e))throw new TypeError("invalid NEAR network");return e}function ae(e,t){if(e===null||typeof e!="object"||Array.isArray(e)||Object.keys(e).length!==t.length||!t.every(r=>Object.hasOwn(e,r)))throw new TypeError("unexpected object fields")}var Ur=(e,t)=>{for(let r=0;r<Math.min(e.length,t.length);r++){let n=e[r]-t[r];if(n)return n}return e.length-t.length};function at(e){let t=_t(e,128),r=t%1000000n;return`${t/1000000n}${r?`.${r.toString().padStart(6,"0").replace(/0+$/,"")}`:""}`}function Vn(e){if(typeof e=="number"&&!Number.isSafeInteger(e))throw new RangeError("deadline out of range");let t=_t(BigInt(e),64),r=t/86400n+719468n,n=r/146097n,o=r%146097n,i=(o-o/1460n+o/36524n-o/146096n)/365n,s=o-(365n*i+i/4n-i/100n),a=(5n*s+2n)/153n,c=s-(153n*a+2n)/5n+1n,d=a<10n?a+3n:a-9n,f=n*400n+i+(d<=2n?1n:0n),u=l=>l.toString().padStart(2,"0");return`${f.toString().padStart(4,"0")}-${u(d)}-${u(c)} ${u(t%86400n/3600n)}:${u(t/60n%60n)}:${u(t%60n)} UTC`}function Jt(e,t,r=()=>{}){if(!Array.isArray(e))throw new TypeError(`"${t}" expected array, got type=${typeof e}`);for(let n=0;n<e.length;n++)r(e[n],`${t}[${n}]`);return e}var se=(e,t,r)=>St(e,t,r),Lp=ut;function Qy(e,t=""){if(typeof e!="string"){let r=t&&`"${t}" `;throw new TypeError(r+"expected string, got type="+typeof e)}return e}function Kn(e,t="object"){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(t==="object"?"expected valid options object":`"${t}" expected object, got type=${typeof e}`);return e}function Yo(e,t){if(typeof e!="function")throw new TypeError(`"${t}" is invalid: expected function, got ${typeof e}`);return e}var Zn=kd,ke=(...e)=>Up(...e),ln=e=>Bd(e),Qt=_d,lr=e=>Ky(e),Rd=BigInt(0),$p=BigInt(1),A8=e=>e?`"${e}" `:"";function Nt(e,t=""){if(typeof e!="boolean")throw new TypeError(A8(t)+"expected boolean, got type="+typeof e);return e}function Od(e){if(typeof e=="bigint"){if(!Wn(e))throw new RangeError("positive bigint expected, got "+e)}else Lp(e);return e}function _e(e,t=""){if(typeof e!="number"){let r=t&&`"${t}" `;throw new TypeError(r+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let r=t&&`"${t}" `;throw new RangeError(r+"expected safe integer, got "+e)}}function qa(e){let t=Od(e).toString(16);return t.length&1?"0"+t:t}function eb(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?Rd:BigInt("0x"+e)}function er(e){return eb(kd(e))}function Xo(e){return eb(kd(Nr(St(e)).reverse()))}function Yn(e,t){if(ut(t),t===0)throw new Error("zero output length is invalid");e=Od(e);let r=t*2,n=e.toString(16);if(n.length>r)throw new RangeError("number is too large");return Bd(n.padStart(r,"0"))}function Dp(e,t){return Yn(e,t).reverse()}function Nr(e){return Uint8Array.from(se(e))}function Cd(e){if(typeof e!="string")throw new TypeError("ascii string expected, got "+typeof e);return Uint8Array.from(e,(t,r)=>{let n=t.charCodeAt(0);if(t.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${e[r]}" with code ${n} at position ${r}`);return n})}function Wn(e){return typeof e=="bigint"&&Rd<=e}function qp(e,t,r){return Wn(e)&&Wn(t)&&Wn(r)&&t<=e&&e<r}function Xn(e,t,r,n){if(!qp(t,r,n))throw new RangeError("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function tr(e){if(e<Rd)throw new Error("expected non-negative bigint, got "+e);return e===Rd?0:e.toString(2).length}function tb(e,t){if(typeof e!="bigint")throw new TypeError('"n" expected bigint, got type='+typeof e);return _e(t,"pos"),e>>BigInt(t)&$p}var ja=e=>(_e(e,"n"),($p<<BigInt(e))-$p);function rb(e,t,r){if(ut(e,"hashLen"),ut(t,"qByteLen"),typeof r!="function")throw new TypeError("hmacFn must be a function");let n=y=>new Uint8Array(y),o=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1e3,c=n(e),d=n(e),f=0,u=()=>{c.fill(1),d.fill(0),f=0},l=(...y)=>r(d,ke(c,...y)),p=(y=o)=>{d=l(i,y),c=l(),y.length!==0&&(d=l(s,y),c=l())},m=()=>{if(f++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,b=[];for(;y<t;){c=l();let x=c.slice();b.push(x),y+=c.length}return ke(...b)};return(y,b)=>{u(),p(y);let x;for(;(x=b(m()))===void 0;)p();return u(),x}}function Be(e,t={},r={},n="object"){Kn(e,n),Kn(t,"fields"),Kn(r,"optFields");function o(s,a,c){let d=n==="object"?`param "${String(s)}"`:`"${n}.${String(s)}"`,f=e[s];if(!Object.hasOwn(e,s)&&(c?f!==void 0:a!=="function"))throw new TypeError(`${d} is invalid: expected own property`);if(c&&f===void 0)return;let u=typeof f;if(u!==a||f===null)throw new TypeError(`${d} is invalid: expected ${a}, got ${u}`)}let i=(s,a)=>Object.entries(s).forEach(([c,d])=>o(c,d,a));i(t,!1),i(r,!0)}var pr=()=>{throw new Error("not implemented")};var ze=BigInt(0),he=BigInt(1),Jn=BigInt(2),ib=BigInt(3),Nd=BigInt(4),sb=BigInt(5),T8=BigInt(7),ab=BigInt(8),I8=BigInt(9),cb=BigInt(15),db=BigInt(16),fb=BigInt("0x10000000000000000");function Ue(e,t){if(t<=ze)throw new Error("mod: expected positive modulus, got "+t);let r=e%t;return r>=ze?r:t+r}function ub(e,t,r){if(r<=he)throw new Error("pow: expected modulus > 1, got "+r);if(typeof t!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof t);if(t<ze)throw new Error("invalid exponent, negatives unsupported");if(t===ze)return he;if(t===he)return e;let n=e%r;if(n<ze&&(n+=r),t<fb){let a=he;for(;t>ze;)t&he&&(a=a*n%r),n=n*n%r,t>>=he;return a}let o=[];for(;t>ze;)o.push(Number(t&cb)),t>>=Nd;let i=new Array(16);i[0]=he,i[1]=n;for(let a=2;a<16;a++)i[a]=i[a-1]*n%r;let s=i[o[o.length-1]];for(let a=o.length-2;a>=0;a--){s=s*s%r,s=s*s%r,s=s*s%r,s=s*s%r;let c=o[a];c!==0&&(s=s*i[c]%r)}return s}function Fe(e,t,r){if(r<=he)throw new Error("pow2: expected modulus > 1, got "+r);if(t<ze)throw new Error("pow2: expected non-negative exponent, got "+t);let n=e;for(;t-- >ze;)n*=n,n%=r;return n}function nb(e,t){if(e===ze)throw new Error("invert: expected non-zero number");if(t<=he)throw new Error("invert: expected modulus > 1, got "+t);let r=Ue(e,t),n=t,o=ze,i=he;for(;r!==ze;){let a=n/r,c=n-r*a,d=o-i*a;n=r,r=c,o=i,i=d}if(n!==he)throw new Error("invert: does not exist");return Ue(o,t)}function lb(e,t){if(t<=he)throw new Error("invertCt: expected prime modulus > 1, got "+t);let r=Ue(e,t);if(r===ze)throw new Error("invertCt: expected non-zero number");let n=ub(r,t-Jn,t);if(Ue(r*n,t)!==he)throw new Error("invertCt: does not exist");return n}function jp(e,t,r){let n=e;if(!n.eql(n.sqr(t),r))throw new Error("Cannot find square root")}function Gp(e,t){if((e&he)===ze)throw new Error(t+": expected odd modulus, got "+e)}function pb(e,t){let r=e,n=(r.ORDER+he)/Nd,o=r.pow(t,n);return jp(r,o,t),o}function k8(e,t){let r=e,n=(r.ORDER-sb)/ab,o=r.mul(t,Jn),i=r.pow(o,n),s=r.mul(t,i),a=r.mul(r.mul(s,Jn),i),c=r.mul(s,r.sub(a,r.ONE));return jp(r,c,t),c}function B8(e){let t=Fr(e),r=mb(e),n=r(t,t.neg(t.ONE)),o=r(t,n),i=r(t,t.neg(n)),s=(e+T8)/db;return((a,c)=>{let d=a,f=d.pow(c,s),u=d.mul(f,n),l=d.mul(f,o),p=d.mul(f,i),m=d.eql(d.sqr(u),c),h=d.eql(d.sqr(l),c);f=d.cmov(f,u,m),u=d.cmov(p,l,h);let y=d.eql(d.sqr(u),c),b=d.cmov(f,u,y);return jp(d,b,c),b})}function mb(e){if(e<ib)throw new Error("sqrt is not defined for small field");Gp(e,"tonelliShanks");let t=e-he,r=0;for(;t%Jn===ze;)t/=Jn,r++;let n=Jn,o=Fr(e);for(;pn(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return pb;let i=o.pow(n,t),s=(t+he)/Jn;return function(c,d){let f=c;if(f.is0(d))return d;if(pn(f,d)!==1)throw new Error("Cannot find square root");let u=r,l=f.mul(f.ONE,i),p=f.pow(d,t),m=f.pow(d,s);for(;!f.eql(p,f.ONE);){if(f.is0(p))throw new Error("Cannot find square root: probably non-prime P");let h=1,y=f.sqr(p);for(;!f.eql(y,f.ONE);)if(h++,y=f.sqr(y),h===u)throw new Error("Cannot find square root");let b=he<<BigInt(u-h-1),x=f.pow(l,b);u=h,l=f.sqr(x),p=f.mul(p,l),m=f.mul(m,x)}return m}}function P8(e){return Gp(e,"Fp.sqrt"),e%Nd===ib?pb:e%ab===sb?k8:e%db===I8?B8(e):mb(e)}var hb=(e,t)=>(Ue(e,t)&he)===he,R8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ft(e){if(Kn(e,"field"),typeof e.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof e.ORDER);_e(e.BYTES,"BYTES"),_e(e.BITS,"BITS");for(let t of R8)Yo(e[t],"field."+t);if(e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=he)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function Fd(e,t,r){Ft(e);let n=e;if(typeof r!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof r);if(r<ze)throw new Error("invalid exponent, negatives unsupported");if(r===ze)return n.ONE;if(r===he)return t;if(r<fb){let a=n.ONE,c=t;for(;r>ze;)r&he&&(a=n.mul(a,c)),c=n.sqr(c),r>>=he;return a}let o=[];for(;r>ze;)o.push(Number(r&cb)),r>>=Nd;let i=new Array(16);i[0]=n.ONE,i[1]=t;for(let a=2;a<16;a++)i[a]=n.mul(i[a-1],t);let s=i[o[o.length-1]];for(let a=o.length-2;a>=0;a--){s=n.sqr(n.sqr(n.sqr(n.sqr(s))));let c=o[a];c!==0&&(s=n.mul(s,i[c]))}return s}function mr(e,t,r=!1){Ft(e),Jt(t,"nums"),Nt(r,"passZero");let n=e,o=new Array(t.length).fill(r?n.ZERO:void 0),i=t.reduce((a,c,d)=>n.is0(c)?a:(o[d]=a,n.mul(a,c)),n.ONE),s=n.inv(i);return t.reduceRight((a,c,d)=>n.is0(c)?a:(o[d]=n.mul(a,o[d]),n.mul(a,c)),s),o}function pn(e,t){Ft(e);let r=e;Gp(r.ORDER,"FpLegendre");let n=(r.ORDER-he)/Jn,o=r.pow(t,n),i=r.eql(o,r.ONE),s=r.eql(o,r.ZERO),a=r.eql(o,r.neg(r.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Vp(e,t){return pn(e,t)!==-1}function O8(e,t){if(t!==void 0&&Lp(t),e<=ze)throw new Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);let r=tr(e);if(t!==void 0&&t<r)throw new Error(`invalid n length: expected nBitLength (${t}) >= bitLen(n) (${r})`);let n=t!==void 0?t:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var ob=new WeakMap,Ud=class{ORDER;BITS;BYTES;isLE;ZERO=ze;ONE=he;_lengths;_mod;constructor(t,r={}){if(t<=he)throw new Error("invalid field: expected ORDER > 1, got "+t);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:o,nByteLength:i}=O8(t,n);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=i,Object.freeze(this)}create(t){return Ue(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return ze<=t&&t<this.ORDER}is0(t){return t===ze}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&he)===he}neg(t){return Ue(-t,this.ORDER)}eql(t,r){return t===r}sqr(t){return Ue(t*t,this.ORDER)}add(t,r){return Ue(t+r,this.ORDER)}sub(t,r){return Ue(t-r,this.ORDER)}mul(t,r){return Ue(t*r,this.ORDER)}pow(t,r){return ub(t,r,this.ORDER)}div(t,r){return Ue(t*nb(r,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,r){return t+r}subN(t,r){return t-r}mulN(t,r){return t*r}inv(t){return nb(t,this.ORDER)}sqrt(t){let r=ob.get(this);return r||ob.set(this,r=P8(this.ORDER)),r(this,t)}toBytes(t){return this.isLE?Dp(t,this.BYTES):Yn(t,this.BYTES)}fromBytes(t,r=!1){se(t);let{_lengths:n,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(n){if(t.length<1||!n.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let d=new Uint8Array(o);d.set(t,i?0:d.length-t.length),t=d}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=i?Xo(t):er(t);if(a&&(c=Ue(c,s)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return mr(this,t,!0)}cmov(t,r,n){return Nt(n,"condition"),n?r:t}};function Fr(e,t={}){return Object.freeze(Ud.prototype),new Ud(e,t)}function yb(e){if(typeof e!="bigint")throw new Error("field order must be bigint");if(e<=he)throw new Error("field order must be greater than 1");let t=tr(e-he);return Math.ceil(t/8)}function qi(e){let t=yb(e);return t+Math.ceil(t/2)}function ji(e,t,r=!1){se(e);let n=e.length,o=yb(t),i=Math.max(qi(t),16);if(n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=r?Xo(e):er(e),a=Ue(s,t-he)+he;return r?Dp(a,o):Yn(a,o)}var Zp=BigInt(0),Ga=BigInt(1),U8=BigInt(4),Kp=16,bb=128,N8=5,gb=2**31;function Mr(e){let t=e;if(typeof t!="function")throw new TypeError('"Point" expected constructor, got type='+typeof e);Yo(t.fromAffine,"Point.fromAffine"),Yo(t.fromBytes,"Point.fromBytes"),Yo(t.fromHex,"Point.fromHex"),Kn(t.BASE,"Point.BASE"),Kn(t.ZERO,"Point.ZERO"),Ft(t.Fp),Ft(t.Fn)}function Md(e,t){Mr(e),xb(t,e);let r=mr(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function F8(e,t,r=1){if(!Number.isSafeInteger(e)||e<r||e>t)throw new Error("invalid window size, expected ["+r+".."+t+"], got W="+e)}function M8(e,t){let r=e*(4*t+128);if(r>gb)throw new Error("invalid window size: table would need ~"+Math.ceil(r/2**20)+" MiB, max "+gb/2**20+" MiB")}function Yp(e,t){if(e!==void 0){Yo(e,"randomBytes");try{let r=e(t);if(!Qt(r)||r.length!==t)return}catch{return}return e}}function xb(e,t){Jt(e,"points"),e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function z8(e,t,r){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((n,o)=>{if(!(r===void 0?t.isValid(n):Wn(n)&&n<r))throw new Error("invalid scalar at index "+o)})}var vb=new WeakMap;function Wp(e){return vb.get(e)||1}function H8(e,t){let r=e.double(),n=[e];for(let o=1;o<t;o++)n.push(n[o-1].add(r));return n}function $8(e,t){let r=2**t,n=r/2,o=BigInt(r-1),i=[];for(;e>Zp;){let s=0;e&Ga&&(s=Number(e&o),s>=n&&(s-=r),e-=BigInt(s)),i.push(s),e>>=Ga}return i}function L8(e,t,r){let n=2**t,o=n/2,i=BigInt(n-1),s=BigInt(t),a=[];for(let c=0;c<r;c++){let d=Number(e&i);e>>=s,d>o&&(d-=n,e+=Ga),a.push(d)}if(e!==Zp)throw new Error("invalid wnaf");return a}function D8(e,t,r){let n=0;for(let i of r)n=Math.max(n,i.length);let o=e;for(let i=n-1;i>=0;i--){i!==n-1&&(o=o.double());for(let s=0;s<r.length;s++){let a=r[s][i];if(a){let c=t[s][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}var Gi=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(t,r){Mr(t),this.randomBytes=Yp(r,Kp),this.Point=t,this.BASE=t.BASE,this.ZERO=t.ZERO,this.bits=t.Fn.BITS}buildWnafTable(t,r,n){let o=Math.ceil(n/r)+1,i=2**(r-1),s=[],a=t;for(let c=0;c<o;c++){let d=a;for(let f=0;f<i;f++)s.push(d),d=d.add(a);a=s[s.length-1].double()}return{W:r,bits:n,windows:o,comp:s}}wnafCachedCT(t,r){let{W:n,windows:o,comp:i}=t,s=2**(n-1),a=L8(r,n,o),c=this.ZERO,d=this.BASE;for(let f=0;f<o;f++){let u=a[f],l=f*s,p=Math.abs(u)-1,m=i[l];for(let y=1;y<s;y++)m=y===p?i[l+y]:m;let h=m.negate();u===0?d=d.add(i[l]):c=c.add(u<0?h:m)}return{p:c,f:d}}getWnafPrecomputes(t,r,n,o){let i=this.wnafPrecomputes.get(r),s=i?.find(a=>a.W===t&&a.bits===n);return s||(s=this.buildWnafTable(r,t,n),typeof o=="function"&&(s={...s,comp:o(s.comp)}),i||(i=[],this.wnafPrecomputes.set(r,i)),i.push(s)),s}assertPoint(t){if(!(t instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof t)}validateMulInput(t,r){if(this.assertPoint(t),!qp(r,Ga,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(t,r,n,o){let i=Wp(t);return i===1?this.fixedWindowCT(t,r,n):this.wnafCachedCT(this.getWnafPrecomputes(i,t,n,o),r)}mulCT(t,r,n){return this.validateMulInput(t,r),this.runCT(t,r,this.bits,n)}mulCTBlinded(t,r,n){if(this.validateMulInput(t,r),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+bb,i=this.randomBytes(Kp);if(!Qt(i)||i.length!==Kp)throw new Error("randomBytes returned invalid byte array");i[0]=i[0]&63|128;let s=r+er(i)*this.Point.Fn.ORDER;return this.runCT(t,s,o,n)}fixedWindowCT(t,r,n){let o=N8,i=1<<o,s=ja(o),a=new Array(i);a[0]=this.ZERO;for(let f=1;f<i;f++)a[f]=a[f-1].add(t);let c=Math.ceil(n/o),d=this.ZERO;for(let f=c-1;f>=0;f--){if(f!==c-1)for(let p=0;p<o;p++)d=d.double();let u=Number(r>>BigInt(f*o)&s),l=a[0];for(let p=1;p<i;p++)l=p===u?a[p]:l;d=d.add(l)}return{p:d,f:d}}shouldBlind(t,r){return this.randomBytes===void 0?!1:r===Ga?!0:t!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(t,r,n,o){return this.shouldBlind(t,n)?this.mulCTBlinded(t,r,o):this.mulCT(t,r,o)}mulUnsafe(t,r,n){if(this.assertPoint(t),!Wn(r))throw new Error("invalid scalar");let o=Wp(t);if(o===1||r>=this.Point.Fn.ORDER)return zd(this.Point,[t],[r],!0);let i=this.getWnafPrecomputes(o,t,this.bits,n);return this.wnafCachedCT(i,r).p}setWindowSize(t,r){this.assertPoint(t),F8(r,this.bits);let n=Math.ceil((this.bits+bb)/r)+1;M8(n*2**(r-1),this.Point.Fp.BYTES),vb.set(t,r),this.wnafPrecomputes.delete(t)}hasWindowSize(t){return Wp(t)!==1}};function zd(e,t,r,n=!1){if(Mr(e),xb(t,e),Nt(n,"allowOversized"),z8(r,e.Fn,n?e.Fn.ORDER**U8:void 0),t.length!==r.length)throw new Error("arrays of points and scalars must have equal length");let o=t.map(s=>H8(s,4)),i=r.map(s=>$8(s,4));return D8(e.ZERO,o,i)}function wb(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ft(t),t}else return Fr(e,{isLE:r})}function Hd(e,t,r={},n){if(e!=="weierstrass"&&e!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);Be(r);for(let c of["p","n","h"]){let d=t[c];if(!(Wn(d)&&d!==Zp))throw new Error(`CURVE.${c} must be positive bigint`)}let o=wb(t.p,r.Fp,n),i=wb(t.n,r.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}function $d(e,t){return function(n){let o=e(n);return{secretKey:o,publicKey:t(o)}}}var Ld=BigInt(0),Dd=BigInt(1),qd=BigInt(2),q8=BigInt(4),Sb=BigInt(8);function j8(e,t,r,n){let o=e.sqr(r),i=e.sqr(n),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function Eb(e,t={}){Be(t,{},{},"extraOpts");let r=t,n=Hd("edwards",e,r,r.FpFnLE),{Fp:o,Fn:i}=n,s=n.CURVE,{h:a}=s;if(pn(o,s.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(pn(o,s.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Be(r,{},{uvRatio:"function",randomBytes:"function"});let c=r.randomBytes===void 0?lr:r.randomBytes,d=qd<<BigInt(o.BYTES*8)-Dd;function f(x){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(x)}let u=r.uvRatio===void 0?(x,g)=>{try{return{isValid:!0,value:o.sqrt(o.div(x,g))}}catch{return{isValid:!1,value:Ld}}}:r.uvRatio;if(!j8(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");let l=o.eql(s.a,o.neg(o.ONE))?x=>o.neg(x):o.eql(s.a,o.ONE)?x=>x:x=>o.mul(s.a,x);function p(x,g,w=!1){let v=w?Dd:Ld;return Xn("coordinate "+x,g,v,d),g}function m(x){if(!(x instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(s.Gx,s.Gy,o.ONE,o.mul(s.Gx,s.Gy));static ZERO=new h(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=i;X;Y;Z;T;constructor(g,w,v,E){this.X=p("x",g),this.Y=p("y",w),this.Z=p("z",v,!0),this.T=p("t",E),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){if(g instanceof h)throw new Error("extended point not allowed");let{x:w,y:v}=g||{};return p("x",w),p("y",v),new h(w,v,o.ONE,o.mul(w,v))}static fromBytes(g,w=!1){let v=o.BYTES,{a:E,d:B}=s;g=Nr(se(g,v,"point")),Nt(w,"zip215");let N=Nr(g),U=g[v-1];N[v-1]=U&-129;let R=Xo(N),T=w?d:o.ORDER;Xn("point.y",R,Ld,T);let O=o.sqr(R),z=o.sub(O,o.ONE),P=o.sub(o.mulN(B,O),E),{isValid:_,value:I}=u(z,P);if(!_)throw new Error("bad point: invalid y coordinate");let k=f(I),M=(U&128)!==0;if(!w&&o.is0(I)&&M)throw new Error("bad point: x=0 and x_0=1");return M!==k&&(I=o.neg(I)),h.fromAffine({x:I,y:R})}static fromHex(g,w=!1){return h.fromBytes(ln(g),w)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=6,w=!0){return b.setWindowSize(this,g),w||this.multiply(qd),this}assertValidity(){let g=this,{a:w,d:v}=s;if(g.is0())throw new Error("bad point: ZERO");let{X:E,Y:B,Z:N,T:U}=g,R=o.sqr(E),T=o.sqr(B),O=o.sqr(N),z=o.sqr(O),P=o.mul(R,w),_=o.mul(o.add(P,T),O),I=o.add(z,o.mul(v,o.mul(R,T)));if(!o.eql(_,I))throw new Error("bad point: equation left != right (1)");let k=o.mul(E,B),M=o.mul(N,U);if(!o.eql(k,M))throw new Error("bad point: equation left != right (2)")}equals(g){m(g);let{X:w,Y:v,Z:E}=this,{X:B,Y:N,Z:U}=g,R=o.mul(w,U),T=o.mul(B,E),O=o.mul(v,U),z=o.mul(N,E);return o.eql(R,T)&&o.eql(O,z)}is0(){return this.equals(h.ZERO)}negate(){return new h(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:g,Y:w,Z:v}=this,E=o.sqr(g),B=o.sqr(w),N=o.mul(o.sqr(v),qd),U=l(E),R=o.addN(g,w),T=o.sub(o.subN(o.sqr(R),E),B),O=o.addN(U,B),z=o.subN(O,N),P=o.subN(U,B),_=o.mul(T,z),I=o.mul(O,P),k=o.mul(T,P),M=o.mul(z,O);return new h(_,I,M,k)}add(g){m(g);let{d:w}=s,{X:v,Y:E,Z:B,T:N}=this,{X:U,Y:R,Z:T,T:O}=g,z=o.mul(v,U),P=o.mul(E,R),_=o.mul(o.mulN(N,w),O),I=o.mul(B,T),k=o.sub(o.subN(o.mulN(o.addN(v,E),o.addN(U,R)),z),P),M=o.subN(I,_),$=o.addN(I,_),F=o.sub(P,l(z)),A=o.mul(k,M),H=o.mul($,F),D=o.mul(k,F),q=o.mul(M,$);return new h(A,H,q,D)}subtract(g){return m(g),this.add(g.negate())}multiply(g){if(!i.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:w,f:v}=b.mulSecret(this,g,a,y);return y([w,v])[0]}multiplyUnsafe(g){if(!i.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===Ld?h.ZERO:this.is0()||g===Dd?this:b.mulUnsafe(this,g,y)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return b.mulUnsafe(this,s.n).is0()}toAffine(g){let w=this,v=g;if(v!=null&&typeof v!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof v);let{X:E,Y:B,Z:N}=w,U=w.is0();v==null&&(v=U?o.create(Sb):o.inv(N));let R=o.mul(E,v),T=o.mul(B,v),O=o.mul(N,v);if(U)return{x:o.ZERO,y:o.ONE};if(!o.eql(O,o.ONE))throw new Error("invZ was invalid");return{x:R,y:T}}clearCofactor(){return a===Dd?this:a===qd?this.double():a===q8?this.double().double():a===Sb?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:g,y:w}=this.toAffine(),v=o.toBytes(w);return v[v.length-1]|=f(g)?128:0,v}toHex(){return Zn(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let y=x=>Md(h,x),b=new Gi(h,c);return b.bits>=6&&h.BASE.precompute(6),Object.freeze(h.prototype),Object.freeze(h),h}function _b(e,t,r={}){if(Mr(e),typeof t!="function")throw new Error('"hash" function param is required');let n=t,o=r;Be(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=e,d=n.outputLen,f=2*a.BYTES;if(d!==void 0&&(_e(d,"hash.outputLen"),d!==f))throw new Error(`hash.outputLen must be ${f}, got ${d}`);let u=o.randomBytes===void 0?lr:o.randomBytes,l=o.toMontgomery,p=o.toMontgomerySecret,m=o.adjustScalarBytes===void 0?P=>P:o.adjustScalarBytes,h=o.domain===void 0?(P,_,I)=>{if(Nt(I,"phflag"),_.length||I)throw new Error("Contexts/pre-hash are not supported");return P}:o.domain;function y(P){return c.create(Xo(P))}function b(P){let _=U.secretKey;se(P,U.secretKey,"secretKey");let I=se(n(P),2*_,"hashedSecretKey"),k=m(I.slice(0,_)),M=I.slice(_,2*_),$=y(k);return{head:k,prefix:M,scalar:$}}function x(P){let{head:_,prefix:I,scalar:k}=b(P),M=s.multiply(k),$=M.toBytes();return{head:_,prefix:I,scalar:k,point:M,pointBytes:$}}function g(P){return x(P).pointBytes}function w(P=Uint8Array.of(),..._){let I=ke(..._);return y(n(h(I,se(P,void 0,"context"),!!i)))}function v(P,_,I={}){Be(I,{},{},"options"),P=Nr(se(P,void 0,"message")),i&&(P=i(P));let{prefix:k,scalar:M,pointBytes:$}=x(_),F=w(I.context,k,P),A=s.multiply(F).toBytes(),H=w(I.context,A,$,P),D=c.create(F+H*M);if(!c.isValid(D))throw new Error("sign failed: invalid s");let q=ke(A,c.toBytes(D));return se(q,U.signature,"result")}let E={zip215:o.zip215};function B(P,_,I,k=E){Be(k);let{context:M}=k,$=k.zip215===void 0?!!E.zip215:k.zip215,F=U.signature;P=se(P,F,"signature"),_=se(_,void 0,"message"),I=se(I,U.publicKey,"publicKey"),$!==void 0&&Nt($,"zip215"),i&&(_=i(_));let A=F/2,H=P.subarray(0,A),D=Xo(P.subarray(A,F)),q,j,K;try{q=e.fromBytes(I,$),j=e.fromBytes(H,$),K=s.multiplyUnsafe(D)}catch{return!1}if(!$&&q.isSmallOrder())return!1;let W=w(M,H,I,_);return j.add(q.multiplyUnsafe(W)).subtract(K).clearCofactor().is0()}let N=a.BYTES,U={secretKey:N,publicKey:N,signature:2*N,seed:N};function R(P){return P=P===void 0?u(U.seed):P,se(P,U.seed,"seed")}function T(P){return Qt(P)&&P.length===U.secretKey}function O(P,_){try{return!!e.fromBytes(P,_===void 0?E.zip215:_)}catch{return!1}}let z={getExtendedPublicKey:x,randomSecretKey:R,isValidSecretKey:T,isValidPublicKey:O,toMontgomery(P){if(l===void 0)throw new Error("Montgomery conversion is not supported for this curve");return l(e.fromBytes(P))},toMontgomerySecret(P){if(p===void 0)throw new Error("Montgomery conversion is not supported for this curve");return p(P)}};return Object.freeze(U),Object.freeze(z),Object.freeze({keygen:$d(R,g),getPublicKey:g,sign:v,verify:B,utils:z,Point:e,lengths:U})}var Ab=BigInt(0),zr=BigInt(1),Qn=BigInt(2),Tb=BigInt(3),Ib=BigInt(4),G8=er;function Jo(e,t){if(_e(e),_e(t),t<0||t>4)throw new Error("invalid I2OSP length: "+t);if(e<0||e>2**(8*t)-1)throw new Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let n=t-1;n>=0;n--)r[n]=e&255,e>>>=8;return new Uint8Array(r)}function V8(e,t){let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e[n]^t[n];return r}function kb(e){if(!Qt(e)&&typeof e!="string")throw new Error("DST must be Uint8Array or ascii string");let t=typeof e=="string"?Cd(e):e;if(t.length===0)throw new Error("DST must be non-empty");return t}function K8(e,t,r,n){if(se(e),_e(r),typeof n!="function")throw new Error("expand_message_xmd: expected hash function");_e(n.outputLen,"hash.outputLen"),_e(n.blockLen,"hash.blockLen"),t=kb(t),t.length>255&&(t=n(ke(Cd("H2C-OVERSIZE-DST-"),t)));let{outputLen:o,blockLen:i}=n,s=Math.ceil(r/o);if(r>65535||s>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=ke(t,Jo(t.length,1)),c=new Uint8Array(i),d=Jo(r,2),f=new Array(s),u=n(ke(c,e,d,Jo(0,1),a));f[0]=n(ke(u,Jo(1,1),a));for(let p=1;p<s;p++){let m=[V8(u,f[p-1]),Jo(p+1,1),a];f[p]=n(ke(...m))}return ke(...f).slice(0,r)}function W8(e,t,r,n,o){if(se(e),_e(r),_e(n,"k"),n<0)throw new Error("expand_message_xof: invalid k");if(typeof o!="function")throw new Error("expand_message_xof: expected XOF function");if(typeof o.create!="function")throw new Error("expand_message_xof: expected XOF create");if(t=kb(t),r<0||r>65535)throw new Error("expand_message_xof: invalid lenInBytes");if(t.length>255){let i=Math.ceil(2*n/8);t=o.create({dkLen:i}).update(Cd("H2C-OVERSIZE-DST-")).update(t).digest()}if(t.length>255)throw new Error("expand_message_xof: invalid DST");return o.create({dkLen:r}).update(e).update(Jo(r,2)).update(t).update(Jo(t.length,1)).digest()}function Xp(e,t,r){Be(r,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:n,k:o,m:i,hash:s,expand:a,DST:c}=r;if(_e(s.outputLen,"valid hash"),se(e),_e(t),_e(i,"m"),_e(o,"k"),n<=BigInt(1))throw new Error("hash_to_field: expected valid field characteristic");if(t<1)throw new Error("hash_to_field: expected count >= 1");if(i<1)throw new Error("hash_to_field: expected m >= 1");if(o<0)throw new Error("hash_to_field: invalid k");let d=n.toString(2).length,f=Math.ceil((d+o)/8),u=t*i*f,l;if(a==="xmd")l=K8(e,c,u,s);else if(a==="xof")l=W8(e,c,u,o,s);else if(a==="_internal_pass")l=e;else throw new Error('expand must be "xmd" or "xof"');let p=new Array(t);for(let m=0;m<t;m++){let h=new Array(i);for(let y=0;y<i;y++){let b=f*(y+m*i),x=l.subarray(b,b+f);h[y]=Ue(G8(x),n)}p[m]=h}return p}function Jp(e,t){Ft(e),Jt(t,"map");let r=t.map((n,o)=>{if(Jt(n,"map["+o+"]"),n.length<1)throw new Error("isogenyMap: expected non-empty coefficients");return Array.from(n).reverse()});return(n,o)=>{let[i,s,a,c]=r.map(l=>l.reduce((p,m)=>e.add(e.mul(p,n),m))),d=e.is0(s)||e.is0(c),[f,u]=mr(e,[s,c],!0);return n=e.mul(i,f),o=e.mul(o,e.mul(a,u)),d?{x:e.ZERO,y:e.ZERO}:{x:n,y:o}}}var Z8="HashToScalar-";function Qp(e,t,r){if(typeof t!="function")throw new Error("mapToCurve() must be defined");Be(r);let n=c=>Object.freeze({...c,DST:Qt(c.DST)?Nr(c.DST):c.DST,...c.encodeDST===void 0?{}:{encodeDST:Qt(c.encodeDST)?Nr(c.encodeDST):c.encodeDST}}),o=n(r),i=c=>c&&c.DST!==void 0?{DST:c.DST}:void 0;function s(c){return e.fromAffine(t(c))}function a(c){let d=c.clearCofactor();return d.equals(e.ZERO)?e.ZERO:(d.assertValidity(),d)}return Object.freeze({get defaults(){return n(o)},Point:e,hashToCurve(c,d){let f=Object.assign({},o,i(d)),u=Xp(c,2,f),l=s(u[0]),p=s(u[1]);return a(l.add(p))},encodeToCurve(c,d){let f=o.encodeDST===void 0?{}:{DST:o.encodeDST},u=Object.assign({},o,f,i(d)),l=Xp(c,1,u),p=s(l[0]);return a(p)},mapToCurve(c){if(o.m===1){if(typeof c!="bigint")throw new Error("expected bigint (m=1)");return a(s([c]))}if(!Array.isArray(c))throw new Error("expected array of bigints");if(c.length!==o.m)throw new Error(`expected array of ${o.m} bigints`);for(let d of c)if(typeof d!="bigint")throw new Error("expected array of bigints");return a(s(c))},hashToScalar(c,d){let f=e.Fn.ORDER,u=Object.assign({},o,{DST:Z8},i(d),{p:f,m:1});return Xp(c,1,u)[0][0]}})}function Y8(e,t){let r=Ft(e),n=r.ORDER,o=Ab;for(let h=n-zr;h%Qn===Ab;h/=Qn)o+=zr;let i=o,s=Qn<<i-zr-zr,a=s*Qn,c=(n-zr)/a,d=(c-zr)/Qn,f=a-zr,u=s,l=r.pow(t,c),p=r.pow(t,(c+zr)/Qn),m=(h,y)=>{let b=l,x=r.pow(y,f),g=r.sqr(x);g=r.mul(g,y);let w=r.mul(h,g);w=r.pow(w,d),w=r.mul(w,x),x=r.mul(w,y),g=r.mul(w,h);let v=r.mul(g,x);w=r.pow(v,u);let E=r.eql(w,r.ONE);x=r.mul(g,p),w=r.mul(v,b),g=r.cmov(x,g,E),v=r.cmov(w,v,E);for(let B=i;B>zr;B--){let N=B-Qn;N=Qn<<N-zr;let U=r.pow(v,N),R=r.eql(U,r.ONE);x=r.mul(g,b),b=r.mul(b,b),U=r.mul(v,b),g=r.cmov(x,g,R),v=r.cmov(U,v,R)}return{isValid:!r.is0(y)&&(E||r.is0(h)),value:g}};if(r.ORDER%Ib===Tb){let h=(r.ORDER-Tb)/Ib,y=r.sqrt(r.neg(t));m=(b,x)=>{let g=r.sqr(x),w=r.mul(b,x);g=r.mul(g,w);let v=r.pow(g,h);v=r.mul(v,w);let E=r.mul(v,y),B=r.mul(r.sqr(v),x),N=r.eql(B,b),U=r.cmov(E,v,N);return{isValid:!r.is0(x)&&N,value:U}}}return m}function e0(e,t){let r=Ft(e);Be(t,{},{},"opts");let{A:n,B:o,Z:i}=t;if(!r.isValidNot0(n)||!r.isValidNot0(o)||!r.isValid(i))throw new Error("mapToCurveSimpleSWU: invalid opts");if(r.eql(i,r.neg(r.ONE))||Vp(r,i))throw new Error("mapToCurveSimpleSWU: invalid opts");let s=r.mul(o,r.inv(r.mul(i,n))),a=r.add(r.add(r.mul(r.sqr(s),s),r.mul(n,s)),o);if(!Vp(r,a))throw new Error("mapToCurveSimpleSWU: invalid opts");let c=Y8(r,i);if(!r.isOdd)throw new Error("Field does not have .isOdd()");return d=>{let f,u,l,p,m,h,y,b;f=r.sqr(d),f=r.mul(f,i),u=r.sqr(f),u=r.add(u,f),l=r.add(u,r.ONE),l=r.mul(l,o),p=r.cmov(i,r.neg(u),!r.eql(u,r.ZERO)),p=r.mul(p,n),u=r.sqr(l),h=r.sqr(p),m=r.mul(h,n),u=r.add(u,m),u=r.mul(u,l),h=r.mul(h,p),m=r.mul(h,o),u=r.add(u,m),y=r.mul(f,l);let{isValid:x,value:g}=c(u,h);b=r.mul(f,d),b=r.mul(b,g),y=r.cmov(y,l,x),b=r.cmov(b,g,x);let w=r.isOdd(d)===r.isOdd(b);b=r.cmov(r.neg(b),b,w);let v=mr(r,[p],!0)[0];return y=r.mul(y,v),{x:y,y:b}}}var t0=BigInt(1),Bb=BigInt(2);var X8=BigInt(5),J8=BigInt(8),r0=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Q8={p:r0,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:J8,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ev(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=r0,a=e*e%i*e%i,c=Fe(a,Bb,i)*a%i,d=Fe(c,t0,i)*e%i,f=Fe(d,X8,i)*d%i,u=Fe(f,t,i)*f%i,l=Fe(u,r,i)*u%i,p=Fe(l,n,i)*l%i,m=Fe(p,o,i)*p%i,h=Fe(m,o,i)*p%i,y=Fe(h,t,i)*f%i;return{pow_p_5_8:Fe(y,Bb,i)*e%i,b2:a}}function Ob(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var Pb=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function tv(e,t){let r=r0,n=Ue(t*t*t,r),o=Ue(n*n*t,r),i=ev(e*o).pow_p_5_8,s=Ue(e*n*i,r),a=Ue(t*s*s,r),c=s,d=Ue(s*Pb,r),f=a===e,u=a===Ue(-e,r),l=a===Ue(-e*Pb,r);return f&&(s=c),(u||l)&&(s=d),hb(s,r)&&(s=Ue(-s,r)),{isValid:f||u,value:s}}var n0=Eb(Q8,{uvRatio:tv}),Rb=n0.Fp;function rv(e){let{y:t}=e;return Rb.toBytes(Rb.div(t0+t,t0-t))}function nv(e){let t=n0.Fp.BYTES;return St(e,t),Ob(Hp(e.subarray(0,t))).subarray(0,t)}function ov(e){return _b(n0,Hp,Object.assign({adjustScalarBytes:Ob,toMontgomery:rv,toMontgomerySecret:nv,zip215:!0},e))}var jd=ov({});var Gd=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(t,r){if(Td(t),St(r,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?t.create().update(r).digest():r);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=t.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Cr(o)}update(t){return un(this),this.iHash.update(t),this}digestInto(t){un(this),Di(t,this),this.finished=!0;let r=t.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a,canXOF:c}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.canXOF=c,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Cb=(()=>{let e=((t,r,n)=>new Gd(t,r).update(n).digest());return e.create=(t,r)=>new Gd(t,r),e})();var iv=BigInt(0),o0=class extends Error{constructor(t=""){super(t)}},mn={Err:o0,_tlv:{encode:(e,t)=>{let{Err:r}=mn;if(_e(e,"tag"),e<0||e>255)throw new r("tlv.encode: wrong tag");if(Qy(t,"data"),t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=qa(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let i=n>127?qa(o.length/2|128):"";return qa(e)+i+o+t},decode(e,t){let{Err:r}=mn;t=se(t,void 0,"DER data");let n=0;if(e<0||e>255)throw new r("tlv.decode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let d=t.subarray(n,n+c);if(d.length!==c)throw new r("tlv.decode: length bytes not complete");if(d[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let f of d)s=s<<8|f;if(n+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(e){let{Err:t}=mn;if(Od(e),e<iv)throw new t("integer: negative integers are not allowed");let r=qa(e);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=mn;if(e.length<1)throw new t("invalid signature integer: empty");if(e[0]&128)throw new t("invalid signature integer: negative");if(e.length>1&&e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return er(e)}},toSig(e,t){let{Err:r,_int:n,_tlv:o}=mn;if(t!==void 0&&(_e(t,"maxScalarBytes"),t<1))throw new r("invalid signature: maxScalarBytes must be positive");let i=se(e,void 0,"signature"),{v:s,l:a}=o.decode(48,i);if(a.length)throw new r("invalid signature: left bytes after parsing");let{v:c,l:d}=o.decode(2,s),{v:f,l:u}=o.decode(2,d);if(u.length)throw new r("invalid signature: left bytes after parsing");if(t!==void 0&&(c.length>t||f.length>t))throw new r("invalid signature: integer too large");return{r:n.decode(c),s:n.decode(f)}},hexFromSig(e){let{_tlv:t,_int:r}=mn;Be(e,{r:"bigint",s:"bigint"},{},"sig");let n=t.encode(2,r.encode(e.r)),o=t.encode(2,r.encode(e.s)),i=n+o;return t.encode(48,i)}},Vd=(Object.freeze(mn._tlv),Object.freeze(mn._int),Object.freeze(mn));var Ub=(e,t)=>(e+(e>=0?t:-t)/Nb)/t;function sv(e,t,r){Xn("scalar",e,hn,r);let[[n,o],[i,s]]=t,a=Ub(s*e,r),c=Ub(-o*e,r),d=e-a*n-c*i,f=-a*o-c*s,u=d<hn,l=f<hn;u&&(d=-d),l&&(f=-f);let p=ja(Math.ceil(tr(r)/2))+Qo;if(d<hn||d>=p||f<hn||f>=p)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:u,k1:d,k2neg:l,k2:f}}function a0(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function i0(e,t){Be(e);let r={};for(let n of Object.keys(t))r[n]=e[n]===void 0?t[n]:e[n];return Nt(r.lowS,"lowS"),Nt(r.prehash,"prehash"),r.format!==void 0&&a0(r.format),r}var hn=BigInt(0),Qo=BigInt(1),Nb=BigInt(2),s0=BigInt(3),av=BigInt(4);function Va(e,t={}){let r=Hd("weierstrass",e,t),n=r.Fp,o=r.Fn,i=r.CURVE,{h:s,n:a}=i;Be(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:d,clearCofactor:f,isTorsionFree:u,fromBytes:l,toBytes:p}=t,m=t.randomBytes===void 0?lr:t.randomBytes;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let h=c?{beta:c.beta,basises:c.basises.map(F=>[...F])}:void 0,y=Mb(n,o);function b(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function x(F,A,H){if(A.is0()){if(!d)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:D,y:q}=A.toAffine(),j=n.toBytes(D);if(Nt(H,"isCompressed"),H){b();let K=!n.isOdd(q);return ke(Fb(K),j)}else return ke(Uint8Array.of(4),j,n.toBytes(q))}function g(F){se(F,void 0,"Point");let{publicKey:A,publicKeyUncompressed:H}=y,D=F.length,q=F[0],j=F.subarray(1);if(d&&D===1&&q===0)return{x:n.ZERO,y:n.ZERO};if(D===A&&(q===2||q===3)){let K=n.fromBytes(j);if(!n.isValid(K))throw new Error("bad point: is not on curve, wrong x");let W=N(K),Z;try{Z=n.sqrt(W)}catch(de){let ue=de instanceof Error?": "+de.message:"";throw new Error("bad point: is not on curve, sqrt error"+ue)}b();let te=n.isOdd(Z);return(q&1)===1!==te&&(Z=n.neg(Z)),{x:K,y:Z}}else if(D===H&&q===4){let K=n.BYTES,W=n.fromBytes(j.subarray(0,K)),Z=n.fromBytes(j.subarray(K,K*2));if(!U(W,Z))throw new Error("bad point: is not on curve");return{x:W,y:Z}}else throw new Error(`bad point: got length ${D}, expected compressed=${A} or uncompressed=${H}`)}let w=p===void 0?x:p,v=l===void 0?g:l,E=n.mul(i.b,s0),B=n.is0(i.a)?F=>n.ZERO:F=>n.mul(i.a,F);function N(F){let A=n.sqr(F),H=n.mul(A,F);return n.add(n.add(H,n.mul(F,i.a)),i.b)}function U(F,A){let H=n.sqr(A),D=N(F);return n.eql(H,D)}if(!U(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let R=n.mul(n.pow(i.a,s0),av),T=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(R,T)))throw new Error("bad curve params: a or b");function O(F,A,H=!1){if(!n.isValid(A)||H&&n.is0(A))throw new Error(`bad point coordinate ${F}`);return typeof A=="object"&&A!==null?n.create(A):A}function z(F){if(!(F instanceof k))throw new Error("Weierstrass Point expected")}function P(F){if(!h||!h.basises)throw new Error("no endo");return sv(F,h.basises,o.ORDER)}function _(F,A,H,D){if(!o.isValid(D))throw new RangeError("invalid scalar: out of range");if(h){let{k1neg:q,k1:j,k2neg:K,k2:W}=P(D),Z=new k(n.mul(H.X,h.beta),H.Y,H.Z);F.push(q?H.negate():H,K?Z.negate():Z),A.push(j,W)}else F.push(H),A.push(D)}let I=new WeakSet;class k{static BASE=new k(i.Gx,i.Gy,n.ONE);static ZERO=new k(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(A,H,D){this.X=O("x",A),this.Y=O("y",H,!0),this.Z=O("z",D),Object.freeze(this)}static CURVE(){return i}static fromAffine(A){let{x:H,y:D}=A||{};if(!A||!n.isValid(H)||!n.isValid(D))throw new Error("invalid affine point");if(A instanceof k)throw new Error("projective point not allowed");return n.is0(H)&&n.is0(D)?k.ZERO:new k(H,D,n.ONE)}static fromBytes(A){let H=k.fromAffine(v(se(A,void 0,"point")));return H.assertValidity(),H}static fromHex(A){return k.fromBytes(ln(A))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(A=6,H=!0){return $.setWindowSize(this,A),H||this.multiply(s0),this}assertValidity(){let A=this;if(A.is0()){if(d&&n.is0(A.X)&&n.eql(A.Y,n.ONE)&&n.is0(A.Z))return;throw new Error("bad point: ZERO")}if(I.has(A))return;let{x:H,y:D}=A.toAffine();if(!n.isValid(H)||!n.isValid(D))throw new Error("bad point: x or y not field elements");if(!U(H,D))throw new Error("bad point: equation left != right");if(!A.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");I.add(A)}hasEvenY(){let{y:A}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(A)}equals(A){z(A);let{X:H,Y:D,Z:q}=this,{X:j,Y:K,Z:W}=A,Z=n.eql(n.mul(H,W),n.mul(j,q)),te=n.eql(n.mul(D,W),n.mul(K,q));return Z&&te}negate(){return new k(this.X,n.neg(this.Y),this.Z)}double(){let{X:A,Y:H,Z:D}=this,q=n.ZERO,j=n.ZERO,K=n.ZERO,W=n.mul(A,A),Z=n.mul(H,H),te=n.mul(D,D),J=n.mul(A,H);return J=n.add(J,J),K=n.mul(A,D),K=n.add(K,K),q=B(K),j=n.mul(E,te),j=n.add(q,j),q=n.sub(Z,j),j=n.add(Z,j),j=n.mul(q,j),q=n.mul(J,q),K=n.mul(E,K),te=B(te),J=n.sub(W,te),J=B(J),J=n.add(J,K),K=n.add(W,W),W=n.add(K,W),W=n.add(W,te),W=n.mul(W,J),j=n.add(j,W),te=n.mul(H,D),te=n.add(te,te),W=n.mul(te,J),q=n.sub(q,W),K=n.mul(te,Z),K=n.add(K,K),K=n.add(K,K),new k(q,j,K)}add(A){z(A);let{X:H,Y:D,Z:q}=this,{X:j,Y:K,Z:W}=A,Z=n.ZERO,te=n.ZERO,J=n.ZERO,de=n.mul(H,j),ue=n.mul(D,K),me=n.mul(q,W),Ne=n.add(H,D),fe=n.add(j,K);Ne=n.mul(Ne,fe),fe=n.add(de,ue),Ne=n.sub(Ne,fe),fe=n.add(H,q);let we=n.add(j,W);return fe=n.mul(fe,we),we=n.add(de,me),fe=n.sub(fe,we),we=n.add(D,q),Z=n.add(K,W),we=n.mul(we,Z),Z=n.add(ue,me),we=n.sub(we,Z),J=B(fe),Z=n.mul(E,me),J=n.add(Z,J),Z=n.sub(ue,J),J=n.add(ue,J),te=n.mul(Z,J),ue=n.add(de,de),ue=n.add(ue,de),me=B(me),fe=n.mul(E,fe),ue=n.add(ue,me),me=n.sub(de,me),me=B(me),fe=n.add(fe,me),de=n.mul(ue,fe),te=n.add(te,de),de=n.mul(we,fe),Z=n.mul(Ne,Z),Z=n.sub(Z,de),de=n.mul(Ne,ue),J=n.mul(we,J),J=n.add(J,de),new k(Z,te,J)}subtract(A){return z(A),this.add(A.negate())}is0(){return this.equals(k.ZERO)}multiply(A){if(!o.isValidNot0(A))throw new RangeError("invalid scalar: out of range");let{p:H,f:D}=$.mulSecret(this,A,s,M);return M([H,D])[0]}multiplyUnsafe(A){let H=this,D=A;if(!o.isValid(D))throw new RangeError("invalid scalar: out of range");if(D===hn||H.is0())return k.ZERO;if(D===Qo)return H;if($.hasWindowSize(this))return $.mulUnsafe(H,D,M);let q=[],j=[];return _(q,j,H,D),zd(k,q,j)}mulAddUnsafe(A,H,D){z(H);let q=[],j=[];return _(q,j,this,A),_(q,j,H,D),zd(k,q,j)}toAffine(A){let H=this,D=A;if(D!=null&&!n.isValid(D))throw new RangeError('"invertedZ" expected valid field element');let{X:q,Y:j,Z:K}=H;if(n.eql(K,n.ONE))return{x:q,y:j};let W=H.is0();D==null&&(D=W?n.ONE:n.inv(K));let Z=n.mul(q,D),te=n.mul(j,D),J=n.mul(K,D);if(W)return{x:n.ZERO,y:n.ZERO};if(!n.eql(J,n.ONE))throw new Error("invZ was invalid");return{x:Z,y:te}}isTorsionFree(){return s===Qo?!0:u?u(k,this):$.mulUnsafe(this,a).is0()}clearCofactor(){return s===Qo?this:f?f(k,this):this.multiplyUnsafe(s)}isSmallOrder(){return s===Qo?this.is0():this.clearCofactor().is0()}toBytes(A=!0){return Nt(A,"isCompressed"),this.assertValidity(),w(k,this,A)}toHex(A=!0){return Zn(this.toBytes(A))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let M=F=>Md(k,F),$=new Gi(k,m);return $.bits>=6&&k.BASE.precompute(6),Object.freeze(k.prototype),Object.freeze(k),k}function Fb(e){return Uint8Array.of(e?2:3)}function Mb(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function cv(e,t={}){Mr(e);let{Fn:r}=e,n=t.randomBytes===void 0?lr:t.randomBytes,o=Object.assign(Mb(e.Fp,r),{seed:Math.max(qi(r.ORDER),16)});function i(p){try{let m=r.fromBytes(p);return r.isValidNot0(m)}catch{return!1}}function s(p,m){let{publicKey:h,publicKeyUncompressed:y}=o;try{let b=p.length;return m===!0&&b!==h||m===!1&&b!==y?!1:!e.fromBytes(p).is0()}catch{return!1}}function a(p){return p=p===void 0?n(o.seed):p,ji(se(p,o.seed,"seed"),r.ORDER)}function c(p,m=!0){return e.BASE.multiply(r.fromBytes(p)).toBytes(m)}function d(p){let{secretKey:m,publicKey:h,publicKeyUncompressed:y}=o,b=r._lengths;if(!Qt(p))return;let x=se(p,void 0,"key").length,g=x===h||x===y,w=x===m||!!b?.includes(x);if(!(g&&w))return g}function f(p,m,h=!0){if(d(p)===!0)throw new Error("first arg must be private key");if(d(m)===!1)throw new Error("second arg must be public key");let y=r.fromBytes(p),b=e.fromBytes(m);if(b.is0())throw new Error("invalid public key: point at infinity");return b.multiply(y).toBytes(h)}let u={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},l=$d(a,c);return Object.freeze(u),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:l,Point:e,utils:u,lengths:o})}function zb(e,t,r={}){Mr(e);let n=t;Td(n),Be(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},r),i=o.randomBytes===void 0?lr:o.randomBytes,s=o.hmac===void 0?(F,A)=>Cb(n,F,A):o.hmac,{Fp:a,Fn:c}=e,{ORDER:d,BITS:f}=c,u=qi(d),l=Yp(i,u),{keygen:p,getPublicKey:m,getSharedSecret:h,utils:y,lengths:b}=cv(e,o),x={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},g=d*Nb+Qo<a.ORDER;function w(F){let A=d>>Qo;return F>A}function v(F,A){if(!c.isValidNot0(A))throw new Error(`invalid signature ${F}: out of range 1..Point.Fn.ORDER`);return A}function E(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function B(F,A,H){return E(),(F===H?0:2)|Number(a.isOdd(A))}function N(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function U(F,A){a0(A);let H=b.signature,D=A==="compact"?H:A==="recovered"?H+1:void 0;return se(F,D)}class R{r;s;recovery;constructor(A,H,D){if(this.r=v("r",A),this.s=v("s",H),D!=null){if(N(),![0,1,2,3].includes(D))throw new Error("invalid recovery id");this.recovery=D}Object.freeze(this)}static fromBytes(A,H=x.format){U(A,H);let D;if(H==="der"){if(A.length>2*c.BYTES+16)throw new Vd.Err("invalid signature: DER signature too long");let{r:W,s:Z}=Vd.toSig(se(A),c.BYTES+1);return new R(W,Z)}H==="recovered"&&(D=A[0],H="compact",A=A.subarray(1));let q=b.signature/2,j=A.subarray(0,q),K=A.subarray(q,q*2);return new R(c.fromBytes(j),c.fromBytes(K),D)}static fromHex(A,H){return this.fromBytes(ln(A),H)}assertRecovery(){let{recovery:A}=this;if(A==null)throw new Error("invalid recovery id: must be present");return A}addRecoveryBit(A){return new R(this.r,this.s,A)}recoverPublicKey(A){let{r:H,s:D}=this,q=this.assertRecovery(),j=q===2||q===3?H+d:H;if(!a.isValid(j))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let K=a.toBytes(j),W=e.fromBytes(ke(Fb((q&1)===0),K)),Z=c.inv(j),te=O(se(A,void 0,"msgHash")),J=c.create(-te*Z),de=c.create(D*Z),ue=e.BASE.mulAddUnsafe(J,W,de);if(ue.is0())throw new Error("invalid recovery: point at infinify");return ue.assertValidity(),ue}hasHighS(){return w(this.s)}toBytes(A=x.format){if(a0(A),A==="der")return ln(Vd.hexFromSig(this));let{r:H,s:D}=this,q=c.toBytes(H),j=c.toBytes(D);return A==="recovered"?(N(),ke(Uint8Array.of(this.assertRecovery()),q,j)):ke(q,j)}toHex(A){return Zn(this.toBytes(A))}}Object.freeze(R.prototype),Object.freeze(R);let T=o.bits2int===void 0?function(A){if(A.length>8192)throw new Error("input is too large");let H=er(A),D=A.length*8-f;return D>0?H>>BigInt(D):H}:o.bits2int,O=o.bits2int_modN===void 0?function(A){return c.create(T(A))}:o.bits2int_modN,z=ja(f);function P(F){return Xn("num < 2^"+f,F,hn,z),c.toBytes(F)}function _(F,A){return se(F,void 0,"message"),A?se(n(F),void 0,"prehashed message"):F}function I(F,A,H){let{lowS:D,prehash:q,extraEntropy:j}=i0(H,x);F=_(F,q);let K=O(F),W=c.fromBytes(A);if(!c.isValidNot0(W))throw new Error("invalid private key");let Z=[P(W),P(K)];if(j!=null&&j!==!1){let ue=j===!0?i(b.secretKey):j;Z.push(se(ue,void 0,"extraEntropy"))}let te=ke(...Z),J=K;function de(ue){let me=T(ue);if(!c.isValidNot0(me))return;let Ne=e.BASE.multiply(me).toAffine(),fe=c.create(Ne.x);if(fe===hn)return;let we;if(l!==void 0){let dr=er(ji(l(u),d)),dn=c.inv(c.mul(dr,me)),fn=c.mul(dr,J),qo=c.mul(dr,W);we=c.create(dn*c.create(fn+qo*fe))}else{let dr=lb(me,d);we=c.create(dr*c.create(J+fe*W))}if(we===hn)return;let cn=B(Ne.x,Ne.y,fe),Ln=we;return D&&w(we)&&(Ln=c.neg(we),cn^=1),new R(fe,Ln,g?void 0:cn)}return{seed:te,k2sig:de}}function k(F,A,H={}){let{seed:D,k2sig:q}=I(F,A,H);return rb(n.outputLen,c.BYTES,s)(D,q).toBytes(H.format)}function M(F,A,H,D={}){let{lowS:q,prehash:j,format:K}=i0(D,x);if(H=se(H,void 0,"publicKey"),A=_(A,j),!Qt(F)){let W=F instanceof R?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+W)}U(F,K);try{let W=R.fromBytes(F,K),Z=e.fromBytes(H);if(Z.is0()||q&&W.hasHighS())return!1;let{r:te,s:J}=W,de=O(A),ue=c.inv(J),me=c.create(de*ue),Ne=c.create(te*ue),fe=e.BASE.mulAddUnsafe(me,Z,Ne);if(fe.is0())return!1;let we=fe.toAffine();return!(c.create(we.x)!==te||K==="recovered"&&W.recovery!==B(we.x,we.y,te))}catch{return!1}}function $(F,A,H={}){let{prehash:D}=i0(H,x);return A=_(A,D),R.fromBytes(F,"recovered").recoverPublicKey(A).toBytes()}return Object.freeze({keygen:p,getPublicKey:m,getSharedSecret:h,utils:y,lengths:b,Point:e,sign:k,verify:M,recoverPublicKey:$,Signature:R,hash:n})}var d0={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},dv={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Hb=BigInt(2);function fv(e){let t=d0.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),d=e*e*e%t,f=d*d*e%t,u=Fe(f,r,t)*f%t,l=Fe(u,r,t)*f%t,p=Fe(l,Hb,t)*d%t,m=Fe(p,o,t)*p%t,h=Fe(m,i,t)*m%t,y=Fe(h,a,t)*h%t,b=Fe(y,c,t)*y%t,x=Fe(b,a,t)*h%t,g=Fe(x,r,t)*f%t,w=Fe(g,s,t)*m%t,v=Fe(w,n,t)*d%t,E=Fe(v,Hb,t);if(!c0.eql(c0.sqr(E),e))throw new Error("Cannot find square root");return E}var c0=Fr(d0.p,{sqrt:fv}),uv=Va(d0,{Fp:c0,endo:dv}),eo=zb(uv,ur);var lv=BigInt(0),Ka=BigInt(1),pv=BigInt(2),mv=BigInt(7),hv=BigInt(256),yv=BigInt(113),Db=[],qb=[],jb=[];for(let e=0,t=Ka,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],Db.push(2*(5*n+r)),qb.push((e+1)*(e+2)/2%64);let o=lv;for(let i=0;i<7;i++)t=(t<<Ka^(t>>mv)*yv)%hv,t&pv&&(o^=Ka<<(Ka<<BigInt(i))-Ka);jb.push(o)}var Gb=Ed(jb,!0),bv=Gb[0],gv=Gb[1],wv=(e,t,r)=>e<<r|t>>>32-r,xv=(e,t,r)=>t<<r|e>>>32-r,vv=(e,t,r)=>t<<r-32|e>>>64-r,Sv=(e,t,r)=>e<<r-32|t>>>64-r,$b=(e,t,r)=>r>32?vv(e,t,r):wv(e,t,r),Lb=(e,t,r)=>r>32?Sv(e,t,r):xv(e,t,r),Vi=new Uint32Array(10);function Ev(e,t=24){if(!(e instanceof Uint32Array))throw new TypeError('"s" expected Uint32Array(50), got type='+typeof e);if(e.length!==50)throw new RangeError('"s" expected Uint32Array(50), got length='+e.length);if(ut(t,"rounds"),t<1||t>24)throw new Error('"rounds" expected integer 1..24');for(let r=24-t;r<24;r++){for(let i=0;i<10;i++)Vi[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let s=(i+8)%10,a=(i+2)%10,c=Vi[a],d=Vi[a+1],f=$b(c,d,1)^Vi[s],u=Lb(c,d,1)^Vi[s+1];for(let l=0;l<50;l+=10)e[i+l]^=f,e[i+l+1]^=u}let n=e[2],o=e[3];for(let i=0;i<24;i++){let s=qb[i],a=$b(n,o,s),c=Lb(n,o,s),d=Db[i];n=e[d],o=e[d+1],e[d]=a,e[d+1]=c}for(let i=0;i<50;i+=10){let s=e[i],a=e[i+1],c=e[i+2],d=e[i+3];e[i]^=~e[i+2]&e[i+4],e[i+1]^=~e[i+3]&e[i+5],e[i+2]^=~e[i+4]&e[i+6],e[i+3]^=~e[i+5]&e[i+7],e[i+4]^=~e[i+6]&e[i+8],e[i+5]^=~e[i+7]&e[i+9],e[i+6]^=~e[i+8]&s,e[i+7]^=~e[i+9]&a,e[i+8]^=~s&c,e[i+9]^=~a&d}e[0]^=bv[r],e[1]^=gv[r]}Cr(Vi)}var f0=class e{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;canXOF;enableXOF=!1;rounds;constructor(t,r,n,o=!1,i=24){if(ut(t,"blockLen"),ut(r,"suffix"),ut(i,"rounds"),jy(o,"enableXOF"),this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.canXOF=o,this.rounds=i,ut(n,"outputLen"),!(0<t&&t<200))throw new Error('"blockLen" must be 1..199');this.state=new Uint8Array(200),this.state32=Op(this.state)}clone(){return this._cloneInto()}keccak(){Cp(this.state32),Ev(this.state32,this.rounds),Cp(this.state32),this.posOut=0,this.pos=0}update(t){un(this),St(t);let{blockLen:r,state:n,state32:o}=this,i=t.length,s=r%4===0&&t.byteOffset%4===0,a=r/4,c=s&&i>=r?Op(t):void 0;for(let d=0;d<i;){if(c!==void 0&&this.pos===0&&d%4===0&&i-d>=r){for(let u=0,l=d/4;u<a;u++)o[u]^=c[l+u];d+=r,this.pos=r,this.keccak();continue}let f=Math.min(r-this.pos,i-d);for(let u=0;u<f;u++)n[this.pos++]^=t[d++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:t,suffix:r,pos:n,blockLen:o}=this;t[n]^=r,(r&128)!==0&&n===o-1&&this.keccak(),t[o-1]^=128,this.keccak()}writeInto(t){un(this,!1),St(t),this.finish();let r=this.state,{blockLen:n}=this;for(let o=0,i=t.length;o<i;){this.posOut>=n&&this.keccak();let s=Math.min(n-this.posOut,i-o);t.set(r.subarray(this.posOut,this.posOut+s),o),this.posOut+=s,o+=s}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not enabled");return this.writeInto(t)}xof(t){return ut(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(Di(t,this),this.finished)throw new Error("digest() was already called");this.writeInto(t.length===this.outputLen?t:t.subarray(0,this.outputLen)),this.destroy()}digest(){let t=new Uint8Array(this.outputLen);return this.digestInto(t),t}destroy(){this.destroyed=!0,Cr(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:o,rounds:i,enableXOF:s}=this;return t||=new e(r,n,o,s,i),t.blockLen=r,t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=i,t.suffix=n,t.outputLen=o,t.enableXOF=s,t.canXOF=this.canXOF,t.destroyed=this.destroyed,t}},Vb=(e,t,r,n={})=>$a(()=>new f0(t,e,r),n);var Kb=Vb(6,136,32,La(8));var Pe=Vb(1,136,32);var Wb=new TextEncoder,Zb=(...e)=>Uint8Array.from(e.flatMap(t=>Array.from(t)));function Wa(e,t,r){return _v(e,t)===r.toLowerCase()}function _v(e,t){if(t.length!==65||t[64]!==27&&t[64]!==28||BigInt(`0x${xd(t.subarray(32,64))}`)>eo.Point.Fn.ORDER/2n)return null;let n=Wb.encode(e),o=Pe(Zb(Wb.encode(`Ethereum Signed Message:
41
- ${n.length}`),n));try{let i=Zb(new Uint8Array([(t[64]??27)-27]),t.subarray(0,64)),s=eo.Point.fromBytes(eo.recoverPublicKey(i,o,{prehash:!1}));return`0x${xd(Pe(s.toBytes(!1).subarray(1)).subarray(12))}`}catch{return null}}var hr=e=>({evm:0,solana:1,near:2})[e.kind];function ne(e){ae(e,["kind","id"]);let{kind:t,id:r}=e;if(typeof r!="string")throw new TypeError("invalid identity id");if(t==="near")return{kind:t,id:be(r)};if(t==="evm"){let n=r.toLowerCase();return G(n,20),{kind:t,id:n}}if(t==="solana"){let n;if(/^[a-fA-F0-9]{64}$/.test(r))n=G(`0x${r.toLowerCase()}`,32);else{if(r.length<32||r.length>44)throw new TypeError("invalid Solana key");if(n=Ut.decode(r),n.length!==32||Ut.encode(n)!==r)throw new TypeError("invalid Solana key")}return{kind:t,id:Y(n).slice(2)}}throw new TypeError("unknown identity kind")}function Tt(e){let t=ne(e);return Et(new Uint8Array([hr(t)]),t.kind==="near"?At(t.id):G(t.kind==="evm"?t.id:`0x${t.id}`,t.kind==="evm"?20:32))}var Q=e=>JSON.stringify(ne(e));function Ke(e){let t=ne(e);return t.kind==="near"?`NEAR ${t.id}`:t.kind==="evm"?`EVM ${t.id}`:`Solana ${Ut.encode(G(`0x${t.id}`,32))}`}function lt(e,t,r,n){try{let o=ne(e);if(typeof t!="string"||t.includes("\r")||t.endsWith(`
42
- `))return!1;if(o.kind==="near")return r===void 0&&n===o.id;if(ae(r,["kind","sig"]),r.kind!==o.kind)return!1;let i=G(r.sig,o.kind==="evm"?65:64);return o.kind==="evm"?Wa(t,i,o.id):jd.verify(i,et.encode(t),G(`0x${o.id}`,32),{zip215:!1})}catch{return!1}}function u0(e,t,r){if(!(r.signedMessage instanceof Uint8Array)||Ur(r.signedMessage,et.encode(t))!==0)throw new S("invalid_signature","wallet returned different signed bytes");let n={kind:"solana",sig:Y(r.signature)};if(e.kind!=="solana"||!lt(e,t,n))throw new S("invalid_signature","the signature is not from the seller");return n}var l0="0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",Ki="17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1",Yb=e=>{let t=_t(e,128);if(t===0n)throw new RangeError("price must be positive");return je(t,16)};function Av(e,t={}){if(ae(e,["network","contract","file_id","seller","pay2_version","cipher_hash","moderator","near","base"]),ae(e.near,["token","price","recipients","remainder"]),e.base!==null&&(ae(e.base,["usdc","price","pay_to"]),e.base.usdc!==(t.baseUsdc??l0)))throw new TypeError("invalid Base USDC");if(Gn(e.network),be(e.contract),e.pay2_version!==2)throw new TypeError("unsupported PAY2 version");let r=e.near;if(be(r.token),(t.nearUsdc!==void 0||e.network==="near:mainnet")&&r.token!==(t.nearUsdc??Ki)||r.recipients.length<1||r.recipients.length>8||!Number.isInteger(r.remainder)||r.remainder<0||r.remainder>=r.recipients.length)throw new TypeError("invalid NEAR terms");let n,o=0,i=r.recipients.map(s=>{ae(s,["identity","bps"]);let a=Tt(s.identity);if(n&&Ur(n,a)>=0)throw new TypeError("recipients must be distinct and Borsh sorted");if(n=a,!Number.isInteger(s.bps)||s.bps<=0||s.bps>1e4)throw new TypeError("invalid bps");return o+=s.bps,Et(a,je(s.bps,2))});if(o!==1e4)throw new TypeError("bps must sum to 10000");return Et(At(e.network),At(e.contract),G(e.file_id,32),Tt(e.seller),je(e.pay2_version,1),G(e.cipher_hash,32),e.moderator===null?je(0,1):Et(je(1,1),At(be(e.moderator))),At(r.token),Yb(r.price),je(i.length,4),...i,je(r.remainder,1),e.base===null?je(0,1):Et(je(1,1),G(e.base.usdc,20),Yb(e.base.price),G(e.base.pay_to,20)))}var tt=(e,t)=>Pd("annon/terms/v2",Av(e,t));function Za(e,t,r,n){let o=tt(e,n);return G(t,48),["Annon: list a file for sale","Signing this lets whoever holds the seller key below open the file.",`contract: ${e.contract}`,`file: ${e.file_id}`,`seller: ${Ke(e.seller)}`,`price: ${at(e.near.price)} USDC on NEAR`,...e.near.recipients.map(i=>`split: ${Ke(i.identity)} ${(i.bps/100).toFixed(2)}%`),`remainder: ${Ke(e.near.recipients[e.near.remainder].identity)}`,e.base?`base: ${at(e.base.price)} USDC on Base to ${e.base.pay_to}`:"base: none",`cipher: ${e.cipher_hash}`,`moderator: ${e.moderator??"(none)"}`,`terms: ${o}`,`seller key: ${t}`,`valid until: ${Vn(r)}`].join(`
43
- `)}function p0(e,t,r){return be(e),G(t,32),G(r,32),`Annon: publish a file
35
+ `,o+=n6(n.state)),n.stateDiff&&(o+=` stateDiff:
36
+ `,o+=n6(n.stateDiff)),o},` State Override:
37
+ `).slice(0,-1)}var yl,bl,kh=C(()=>{le();yl=class extends L{constructor({address:t}){super(`State for account "${t}" is set multiple times.`,{name:"AccountStateConflictError"})}},bl=class extends L{constructor(){super("state and stateDiff are set on the same account.",{name:"StateAssignmentConflictError"})}}});var gl,wl,xl,vl,Sl,ba,El=C(()=>{Ye();_u();Pm();vo();yx();_s();Vu();Cs();yt();le();kh();$t();Cn();gl=class extends L{constructor(t,{account:r,docsPath:n,chain:o,data:i,gas:s,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:d,nonce:f,to:u,value:l,stateOverride:p}){let m=r?ce(r):void 0,h=Bi({from:m?.address,to:u,value:typeof l<"u"&&`${Os(l)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:i,gas:s,gasPrice:typeof a<"u"&&`${ot(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${ot(c)} gwei`,maxPriorityFeePerGas:typeof d<"u"&&`${ot(d)} gwei`,nonce:f});p&&(h+=`
38
+ ${o6(p)}`),super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Raw Call Arguments:",h].filter(Boolean),name:"CallExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}},wl=class extends L{constructor(t,{abi:r,args:n,contractAddress:o,docsPath:i,functionName:s,sender:a}){let c=Jr({abi:r,args:n,name:s}),d=c?$m({abiItem:c,args:n,includeFunctionName:!1,includeName:!1}):void 0,f=c?ft(c,{includeName:!0}):void 0,u=Bi({address:o&&C2(o),function:f,args:d&&d!=="()"&&`${[...Array(s?.length??0).keys()].map(()=>" ").join("")}${d}`,sender:a});super(t.shortMessage||`An unknown error occurred while executing the contract function "${s}".`,{cause:t,docsPath:i,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],u&&"Contract Call:",u].filter(Boolean),name:"ContractFunctionExecutionError"}),Object.defineProperty(this,"abi",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"args",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"contractAddress",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"formattedArgs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"functionName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sender",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.abi=r,this.args=n,this.cause=t,this.contractAddress=o,this.functionName=s,this.sender=a}},xl=class extends L{constructor({abi:t,data:r,functionName:n,message:o,cause:i}){let s,a,c,d;if(r&&r!=="0x")try{a=Tu({abi:t,data:r,cause:i});let{abiItem:u,errorName:l,args:p}=a;if(l==="Error")d=p[0];else if(l==="Panic"){let[m]=p;d=X1[m]}else{let m=u?ft(u,{includeName:!0}):void 0,h=u&&p?$m({abiItem:u,args:p,includeFunctionName:!1,includeName:!1}):void 0;c=[m?`Error: ${m}`:"",h&&h!=="()"?` ${[...Array(l?.length??0).keys()].map(()=>" ").join("")}${h}`:""]}}catch(u){s=u}else o&&(d=o);let f;s instanceof ys&&(f=s.signature,c=[`Unable to decode signature "${f}" as it was not found on the provided ABI.`,"Make sure you are using the correct ABI and that the error exists on it.",`You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${f}.`]),super(d&&d!=="execution reverted"||f?[`The contract function "${n}" reverted with the following ${f?"signature":"reason"}:`,d||f].join(`
39
+ `):`The contract function "${n}" reverted.`,{cause:s??i,metaMessages:c,name:"ContractFunctionRevertedError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=a,this.raw=r,this.reason=d,this.signature=f}},vl=class extends L{constructor({functionName:t,cause:r}){super(`The contract function "${t}" returned no data ("0x").`,{metaMessages:["This could be due to any of the following:",` - The contract does not have the function "${t}",`," - The parameters passed to the contract function may be invalid, or"," - The address is not a contract."],name:"ContractFunctionZeroDataError",cause:r})}},Sl=class extends L{constructor({factory:t}){super(`Deployment for counterfactual contract call failed${t?` for factory "${t}".`:""}`,{metaMessages:["Please ensure:","- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).","- The `factoryData` is a valid encoded function call for contract deployment function on the factory."],name:"CounterfactualDeploymentFailedError"})}},ba=class extends L{constructor({data:t,message:r}){super(r||"",{name:"RawContractError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t}}});function Qc(e){let{blockHash:t,blockNumber:r,blockTag:n,requireCanonical:o}=e;if(o!==void 0&&!t)throw new L("`requireCanonical` can only be provided when `blockHash` is set.");return t?o?{blockHash:t,requireCanonical:o}:{blockHash:t}:typeof r=="bigint"?V(r):n??"latest"}var Bh=C(()=>{le();xe()});function i6({blockNumber:e,chain:t,contract:r}){let n=t?.contracts?.[r];if(!n)throw new Pi({chain:t,contract:{name:r}});if(e&&n.blockCreated&&n.blockCreated>e)throw new Pi({blockNumber:e,chain:t,contract:{name:r,blockCreated:n.blockCreated}});return n.address}var s6=C(()=>{Wc()});function ga(e,t){let r=(e.details||"").toLowerCase(),n=e instanceof L?e.walk(o=>o?.code===On.code):e;return n instanceof L?new On({cause:e,message:n.details}):On.nodeMessage.test(r)?new On({cause:e,message:e.details}):ir.nodeMessage.test(r)?new ir({cause:e,maxFeePerGas:t?.maxFeePerGas}):Ls.nodeMessage.test(r)?new Ls({cause:e,maxFeePerGas:t?.maxFeePerGas}):Ds.nodeMessage.test(r)?new Ds({cause:e,nonce:t?.nonce}):qs.nodeMessage.test(r)?new qs({cause:e,nonce:t?.nonce}):js.nodeMessage.test(r)?new js({cause:e,nonce:t?.nonce}):Gs.nodeMessage.test(r)?new Gs({cause:e}):Vs.nodeMessage.test(r)?new Vs({cause:e,gas:t?.gas}):Ks.nodeMessage.test(r)?new Ks({cause:e,gas:t?.gas}):Ws.nodeMessage.test(r)?new Ws({cause:e}):en.nodeMessage.test(r)?new en({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas}):new tn({cause:e})}var _l=C(()=>{le();Oi()});function a6(e,{docsPath:t,...r}){let n=(()=>{let o=ga(e,r);return o instanceof tn?e:o})();return new gl(n,{docsPath:t,...r})}var c6=C(()=>{El();Oi();_l()});function nn(e,{format:t}){if(!t)return{};let r={};function n(i){let s=Object.keys(i);for(let a of s)a in e&&(r[a]=e[a]),i[a]&&typeof i[a]=="object"&&!Array.isArray(i[a])&&n(i[a])}let o=t(e||{});return n(o),r}var wa=C(()=>{});function xa(e,t){return({exclude:r,format:n})=>({exclude:r,format:(o,i)=>{let s=t(o,i);if(r)for(let a of r)delete s[a];return{...s,...n(o,i)}},type:e})}var Al=C(()=>{});function sr(e,t){let r={};return typeof e.authorizationList<"u"&&(r.authorizationList=X3(e.authorizationList)),typeof e.accessList<"u"&&(r.accessList=e.accessList),typeof e.blobVersionedHashes<"u"&&(r.blobVersionedHashes=e.blobVersionedHashes),typeof e.blobs<"u"&&(typeof e.blobs[0]!="string"?r.blobs=e.blobs.map(n=>Me(n)):r.blobs=e.blobs),typeof e.data<"u"&&(r.data=e.data),e.account&&(r.from=e.account.address),typeof e.from<"u"&&(r.from=e.from),typeof e.gas<"u"&&(r.gas=V(e.gas)),typeof e.gasPrice<"u"&&(r.gasPrice=V(e.gasPrice)),typeof e.maxFeePerBlobGas<"u"&&(r.maxFeePerBlobGas=V(e.maxFeePerBlobGas)),typeof e.maxFeePerGas<"u"&&(r.maxFeePerGas=V(e.maxFeePerGas)),typeof e.maxPriorityFeePerGas<"u"&&(r.maxPriorityFeePerGas=V(e.maxPriorityFeePerGas)),typeof e.nonce<"u"&&(r.nonce=V(e.nonce)),typeof e.to<"u"&&(r.to=e.to),typeof e.type<"u"&&(r.type=Y3[e.type]),typeof e.value<"u"&&(r.value=V(e.value)),r}function X3(e){return e.map(t=>({address:t.address,r:t.r?V(BigInt(t.r)):t.r,s:t.s?V(BigInt(t.s)):t.s,chainId:V(t.chainId),nonce:V(t.nonce),...typeof t.yParity<"u"?{yParity:V(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:V(t.v)}:{}}))}var Y3,Mi=C(()=>{xe();Y3={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"}});function va(){let e=()=>{},t=()=>{};return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}var Tl=C(()=>{});function d6({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:o}){let i=async()=>{let f=c();s();let u=f.map(({args:l})=>l);u.length!==0&&e(u).then(l=>{o&&Array.isArray(l)&&l.sort(o);for(let p=0;p<f.length;p++){let{resolve:m}=f[p];m?.([l[p],l])}}).catch(l=>{for(let p=0;p<f.length;p++){let{reject:m}=f[p];m?.(l)}})},s=()=>Ph.delete(t),a=()=>c().map(({args:f})=>f),c=()=>Ph.get(t)||[],d=f=>Ph.set(t,[...c(),f]);return{flush:s,async schedule(f){let{promise:u,resolve:l,reject:p}=va();return r?.([...a(),f])&&i(),c().length>0?(d({args:f,resolve:l,reject:p}),u):(d({args:f,resolve:l,reject:p}),setTimeout(i,n),u)}}}var Ph,f6=C(()=>{Tl();Ph=new Map});function u6(e){if(!(!e||e.length===0))return e.reduce((t,{slot:r,value:n})=>{if(r.length!==66)throw new Sc({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new Sc({size:n.length,targetSize:66,type:"hex"});return t[r]=n,t},{})}function J3(e){let{balance:t,nonce:r,state:n,stateDiff:o,code:i}=e,s={};if(i!==void 0&&(s.code=i),t!==void 0&&(s.balance=V(t)),r!==void 0&&(s.nonce=V(r)),n!==void 0&&(s.state=u6(n)),o!==void 0){if(s.state)throw new bl;s.stateDiff=u6(o)}return s}function Il(e){if(!e)return;let t={};for(let{address:r,...n}of e){if(!pe(r,{strict:!1}))throw new Ce({address:r});if(t[r])throw new yl({address:r});t[r]=J3(n)}return t}var Rh=C(()=>{Gr();Zf();kh();Zt();xe()});function Lt(e){let{account:t,maxFeePerGas:r,maxPriorityFeePerGas:n,to:o}=e,i=t?ce(t):void 0;if(i&&!pe(i.address))throw new Ce({address:i.address});if(o&&!pe(o))throw new Ce({address:o});if(r&&r>$s)throw new ir({maxFeePerGas:r});if(n&&r&&n>r)throw new en({maxFeePerGas:r,maxPriorityFeePerGas:n})}var Uo=C(()=>{Ye();vh();Gr();Oi();Zt()});async function kl(e,t){let{account:r=e.account,authorizationList:n,batch:o=!!e.batch?.multicall,blockHash:i,blockNumber:s,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,accessList:d,blobs:f,blockOverrides:u,code:l,data:p,factory:m,factoryData:h,gas:y,gasPrice:b,maxFeePerBlobGas:x,maxFeePerGas:g,maxPriorityFeePerGas:w,nonce:v,requestOptions:E,to:B,value:N,stateOverride:U,...R}=t,T=r?ce(r):void 0;if(l&&(m||h))throw new L("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(l&&B)throw new L("Cannot provide both `code` & `to` as parameters.");let O=l&&p,H=m&&h&&B&&p,P=O||H,_=O?m6({code:l,data:p}):H?o4({data:p,factory:m,factoryData:h,to:B}):p;try{Lt(t);let I=Qc({blockHash:i,blockNumber:s,blockTag:a,requireCanonical:c}),k=u?W2(u):void 0,M=Il(U),$=e.chain?.formatters?.transactionRequest?.format,A=($||sr)({...nn(R,{format:$}),accessList:d,account:T,authorizationList:n,blobs:f,data:_,gas:y,gasPrice:b,maxFeePerBlobGas:x,maxFeePerGas:g,maxPriorityFeePerGas:w,nonce:v,to:P?void 0:B,value:N},"call");if(o&&Q3({request:A})&&!k&&i===void 0)try{let{deployless:q=!1}=typeof e.batch?.multicall=="object"?e.batch.multicall:{},j=p6(e,{blockNumber:s,deployless:q});if(!j||!n4(M,j))return await r4(e,{...A,blockHash:i,blockNumber:s,blockTag:a,multicallAddress:j,requestOptions:E,requireCanonical:c,rpcStateOverride:M})}catch(q){if(!(q instanceof Kc)&&!(q instanceof Pi))throw q}let z=(()=>{let q=[A,I];return M&&k?[...q,M,k]:M?[...q,M]:k?[...q,{},k]:q})(),D=await e.request({method:"eth_call",params:z},E);return D==="0x"?{data:void 0}:{data:D}}catch(I){if(E?.signal?.aborted)throw gt(E.signal);if(rn(I))throw I;let k=i4(I),{offchainLookup:M,offchainLookupSignature:$}=await Promise.resolve().then(()=>(y6(),h6));if(e.ccipRead!==!1&&k?.slice(0,10)===$&&B)return{data:await M(e,{data:k,requestOptions:E,to:B})};throw P&&k?.slice(0,10)==="0x101bb98d"?new Sl({factory:m}):a6(I,{...t,account:T,chain:e.chain})}}function Q3({request:e}){let{data:t,to:r,...n}=e;return!(!t||t.startsWith(X2)||!r||Object.values(n).filter(o=>typeof o<"u").length>0)}function t4(e){if(!e)return"default";let t=l6.get(e);if(t!==void 0)return t;let r=e4++;return l6.set(e,r),r}async function r4(e,t){let{batchSize:r=1024,deployless:n=!1,wait:o=0}=typeof e.batch?.multicall=="object"?e.batch.multicall:{},{blockHash:i,blockNumber:s,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,data:d,multicallAddress:f,requestOptions:u,rpcStateOverride:l,to:p}=t,m=f!==void 0?f:p6(e,{blockNumber:s,deployless:n}),h=Qc({blockHash:i,blockNumber:s,blockTag:a,requireCanonical:c}),y=typeof h=="string"?h:JSON.stringify(h),b=l?`.${JSON.stringify(l)}`:"",{schedule:x}=d6({id:`${e.uid}.${y}.${t4(u)}${b}`,wait:o,shouldSplitBatch(v){return v.reduce((B,{data:N})=>B+(N.length-2),0)>r*2},fn:async v=>{let E=v.map(R=>({allowFailure:!0,callData:R.data,target:R.to})),B=Yt({abi:Ih,args:[E],functionName:"aggregate3"}),N={...m===null?{data:m6({code:t6,data:B})}:{to:m,data:B}},U=await e.request({method:"eth_call",params:l?[N,h,l]:[N,h]},u);return ku({abi:Ih,args:[E],functionName:"aggregate3",data:U||"0x"})}}),[{returnData:g,success:w}]=await x({data:d,to:p});if(!w)throw new ba({data:g});return g==="0x"?{data:void 0}:{data:g}}function p6(e,t){let{blockNumber:r,deployless:n}=t;if(n)return null;if(e.chain)return i6({blockNumber:r,chain:e.chain,contract:"multicall3"});throw new Kc}function n4(e,t){return e?Object.keys(e).some(r=>Ht(r,t)):!1}function m6(e){let{code:t,data:r}=e;return Nc({abi:Wf(["constructor(bytes, bytes)"]),bytecode:Q2,args:[t,r]})}function o4(e){let{data:t,factory:r,factoryData:n,to:o}=e;return Nc({abi:Wf(["constructor(address, bytes, address, bytes)"]),bytecode:e6,args:[o,t,r,n]})}function i4(e){if(!(e instanceof L))return;let t=e.walk();return typeof t?.data=="object"?t.data?.data:t.data}var e4,l6,Oh=C(()=>{mm();Z2();Ye();Jc();J2();r6();le();Wc();El();Cn();Um();Fm();Si();Ei();Bh();s6();c6();wa();Mi();f6();Rh();Uo();e4=0,l6=new WeakMap});var Bl,Pl,Rl,b6=C(()=>{_r();le();Cn();Bl=class extends L{constructor({callbackSelector:t,cause:r,data:n,extraData:o,sender:i,urls:s}){super(r.shortMessage||"An error occurred while fetching for an offchain result.",{cause:r,metaMessages:[...r.metaMessages||[],r.metaMessages?.length?"":[],"Offchain Gateway Call:",s&&[" Gateway URL(s):",...s.map(a=>` ${Ys(a)}`)],` Sender: ${i}`,` Data: ${n}`,` Callback selector: ${t}`,` Extra data: ${o}`].flat(),name:"OffchainLookupError"})}},Pl=class extends L{constructor({result:t,url:r}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${Ys(r)}`,`Response: ${qe(t)}`],name:"OffchainLookupResponseMalformedError"})}},Rl=class extends L{constructor({sender:t,to:r}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${r}`,`OffchainLookup sender address: ${t}`],name:"OffchainLookupSenderMismatchError"})}}});async function Uh(e){let{data:t,ccipRequest:r}=e,{args:[n]}=ax({abi:hl,data:t}),o=[],i=[];return await Promise.all(n.map(async(s,a)=>{try{i[a]=s.urls.includes(Ch)?await Uh({data:s.data,ccipRequest:r}):await r(s),o[a]=!1}catch(c){o[a]=!0,i[a]=s4(c)}})),mx({abi:hl,functionName:"query",result:[o,i]})}function s4(e){return e.name==="HttpRequestError"&&e.status?Hm({abi:hl,errorName:"HttpError",args:[e.status,e.shortMessage]}):Hm({abi:[Eu],errorName:"Error",args:["shortMessage"in e?e.shortMessage:e.message]})}var Ch,g6=C(()=>{Jc();_u();cx();fx();hx();Ch="x-batch-gateway:true"});var h6={};By(h6,{ccipRequest:()=>x6,offchainLookup:()=>c4,offchainLookupAbiItem:()=>w6,offchainLookupSignature:()=>a4});async function c4(e,{blockNumber:t,blockTag:r,data:n,requestOptions:o,to:i}){let{args:s}=Tu({data:n,abi:[w6]}),[a,c,d,f,u]=s,{ccipRead:l}=e,p=l&&typeof l?.request=="function"?l.request:x6;try{if(!Ht(i,a))throw new Rl({sender:a,to:i});let m=c.includes(Ch)?await Uh({data:d,ccipRequest:y=>p({...y,requestOptions:o})}):await p({data:d,requestOptions:o,sender:a,urls:c}),{data:h}=await kl(e,{blockNumber:t,blockTag:r,data:Er([f,Yr([{type:"bytes"},{type:"bytes"}],[m,u])]),requestOptions:o,to:i});return h}catch(m){throw o?.signal?.aborted?gt(o.signal):rn(m)?m:new Bl({callbackSelector:f,cause:m,data:n,extraData:u,sender:a,urls:c})}}async function x6({data:e,requestOptions:t,sender:r,urls:n}){let o=new Error("An unknown error occurred.");for(let i=0;i<n.length;i++){if(t?.signal?.aborted)throw gt(t.signal);let s=n[i],a=s.includes("{data}")?"GET":"POST",c=a==="POST"?{data:e,sender:r}:void 0,d=a==="POST"?{"Content-Type":"application/json"}:{};try{let f=await fetch(s.replace("{sender}",r.toLowerCase()).replace("{data}",e),{body:JSON.stringify(c),headers:d,method:a,...t?.signal?{signal:t.signal}:{}}),u;if(f.headers.get("Content-Type")?.startsWith("application/json")?u=(await f.json()).data:u=await f.text(),!f.ok){o=new ko({body:c,details:u?.error?qe(u.error):f.statusText,headers:f.headers,status:f.status,url:s});continue}if(!dt(u)){o=new Pl({result:u,url:s});continue}return u}catch(f){if(t?.signal?.aborted)throw gt(t.signal);if(rn(f))throw f;o=new ko({body:c,details:f.message,url:s})}}throw o}var a4,w6,y6=C(()=>{Oh();b6();Yc();Cn();Pm();vi();Ei();or();xn();g6();_r();a4="0x556f1830",w6={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]}});function Sa({chain:e,currentChainId:t}){if(!e)throw new sl;if(t!==e.id)throw new il({chain:e,currentChainId:t})}var Ol=C(()=>{Wc()});function Nh(e){let t={formatters:void 0,fees:void 0,serializers:void 0,...e};function r(n){return o=>{let i=typeof o=="function"?o(n):o,s={...n,...i};return Object.assign(s,{extend:r(s)})}}return Object.assign(t,{extend:r(t)})}var v6=C(()=>{});function Ea(e,{abi:t,address:r,args:n,docsPath:o,functionName:i,sender:s}){let a=e instanceof ba?e:e instanceof L?e.walk(m=>typeof m=="object"&&m!==null&&"data"in m)||e.walk():{},{code:c,data:d,details:f,message:u,shortMessage:l}=a,p=e instanceof So?new vl({functionName:i,cause:e}):[d4,Un.code].includes(c)&&(d||f||u||l)||c===Bo.code&&f==="execution reverted"&&d?new xl({abi:t,data:typeof d=="object"?d.data:d,functionName:i,message:a instanceof Xs?f:l??u,cause:e}):e;return new wl(p,{abi:t,args:n,contractAddress:r,docsPath:o,functionName:i,sender:s})}var d4,Cl=C(()=>{yt();le();El();Yc();fl();d4=3});var Ul,S6=C(()=>{Vu();Cs();le();$t();Ul=class extends L{constructor(t,{account:r,docsPath:n,chain:o,data:i,gas:s,gasPrice:a,maxFeePerGas:c,maxPriorityFeePerGas:d,nonce:f,to:u,value:l}){let p=Bi({from:r?.address,to:u,value:typeof l<"u"&&`${Os(l)} ${o?.nativeCurrency?.symbol||"ETH"}`,data:i,gas:s,gasPrice:typeof a<"u"&&`${ot(a)} gwei`,maxFeePerGas:typeof c<"u"&&`${ot(c)} gwei`,maxPriorityFeePerGas:typeof d<"u"&&`${ot(d)} gwei`,nonce:f});super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessages?[...t.metaMessages," "]:[],"Estimate Gas Arguments:",p].filter(Boolean),name:"EstimateGasExecutionError"}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t}}});function E6(e,{docsPath:t,...r}){let n=(()=>{let o=ga(e,r);return o instanceof tn?e:o})();return new Ul(n,{docsPath:t,...r})}var _6=C(()=>{S6();Oi();_l()});function No(e,{docsPath:t,...r}){let n=(()=>{let o=ga(e,r);return o instanceof tn?e:o})();return new Yu(n,{docsPath:t,...r})}var ed=C(()=>{Oi();$t();_l()});function Nn(e,t){let r={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,...e.blockTimestamp!=null&&{blockTimestamp:BigInt(e.blockTimestamp)},chainId:e.chainId?Xe(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?Xe(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?Fh[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};return e.authorizationList&&(r.authorizationList=f4(e.authorizationList)),r.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof r.v=="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}})(),r.type==="legacy"&&(delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity),r.type==="eip2930"&&(delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas),r.type==="eip1559"&&delete r.maxFeePerBlobGas,r}function f4(e){return e.map(t=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}var Fh,A6,_a=C(()=>{Bt();Al();Fh={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};A6=xa("transaction",Nn)});function Mh(e,t){let r=(e.transactions??[]).map(n=>typeof n=="string"?n:Nn(n));return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:r,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}var T6,Hh=C(()=>{Al();_a();T6=xa("block",Mh)});function td(e,t){let r={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map(n=>Bu(n)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Xe(e.transactionIndex):null,status:e.status?zh[e.status]:null,type:e.type?Fh[e.type]||e.type:null};return e.blobGasPrice&&(r.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(r.blobGasUsed=BigInt(e.blobGasUsed)),r}var zh,I6,rd=C(()=>{Bt();Al();Lm();_a();zh={"0x0":"reverted","0x1":"success"};I6=xa("transactionReceipt",td)});function oe(e,t,r){let n=e[t.name];if(typeof n=="function")return n;let o=e[r];return typeof o=="function"?o:i=>t(e,i)}var vt=C(()=>{});async function Nl(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:i}){let s=Qc({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i}),a=await e.request({method:"eth_getTransactionCount",params:[t,s]},{dedupe:typeof n=="bigint"||r!==void 0});return Xe(a)}var $h=C(()=>{Bh();Bt()});var Fl,Ml,Hl,zl,k6=C(()=>{_r();le();Fl=class extends L{constructor({domain:t}){super(`Invalid domain "${qe(t)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}},Ml=class extends L{constructor({primaryType:t,types:r}){super(`Invalid primary type \`${t}\` must be one of \`${JSON.stringify(Object.keys(r))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}},Hl=class extends L{constructor({type:t}){super(`Struct type "${t}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}},zl=class extends L{constructor({type:t}){let r=t.replace(/^(u?int)/,"$&256");super(`Type "${t}" is not a valid EIP-712 type.`,{metaMessages:[`Use "${r}" instead.`],name:"InvalidTypedDataTypeError"})}}});function B6(e){let{domain:t,message:r,primaryType:n,types:o}=e,i=(c,d)=>{let f={...d};for(let u of c){let{name:l,type:p}=u;p==="address"&&(f[l]=f[l].toLowerCase())}return f},s=o.EIP712Domain?t?i(o.EIP712Domain,t):{}:{},a=(()=>{if(n!=="EIP712Domain")return i(o[n],r)})();return qe({domain:s,message:a,primaryType:n,types:o})}function P6(e){let{domain:t,message:r,primaryType:n,types:o}=e,i=(s,a)=>{for(let c of s){let{name:d,type:f}=c,u=a[d],l=f.replace(/(\[[0-9]*\])+$/,"");if(l==="int"||l==="uint")throw new zl({type:f});let p=f.match(Su);if(p&&(typeof u=="number"||typeof u=="bigint")){let[y,b,x]=p;V(u,{signed:b==="int",size:Number.parseInt(x,10)/8})}if(f==="address"&&typeof u=="string"&&!pe(u))throw new Ce({address:u});let m=f.match(Z1);if(m){let[y,b]=m;if(b&&ge(u)!==Number.parseInt(b,10))throw new hu({expectedSize:Number.parseInt(b,10),givenSize:ge(u)})}let h=o[f];h&&(u4(f),i(h,u))}};if(o.EIP712Domain&&t){if(typeof t!="object")throw new Fl({domain:t});i(o.EIP712Domain,t)}if(n!=="EIP712Domain")if(o[n])i(o[n],r);else throw new Ml({primaryType:n,types:o})}function R6({domain:e}){return[typeof e?.name=="string"&&{name:"name",type:"string"},typeof e?.version=="string"&&{name:"version",type:"string"},(typeof e?.chainId=="number"||typeof e?.chainId=="bigint")&&{name:"chainId",type:"uint256"},e?.verifyingContract&&{name:"verifyingContract",type:"address"},e?.salt&&{name:"salt",type:"bytes32"}].filter(Boolean)}function u4(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new Hl({type:e})}var O6=C(()=>{yt();Gr();k6();Zt();wr();xe();_m();_r()});function $l(e,t){return ju(e,t)}var Lh=C(()=>{Vc()});function C6(e,t){return h2(e,t)}var U6=C(()=>{Vc()});var Dh=C(()=>{Si();Zt()});var Aa,Fo,Vl,sd=C(()=>{Cs();le();Aa=class extends L{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}},Fo=class extends L{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}},Vl=class extends L{constructor({maxPriorityFeePerGas:t}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${ot(t)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}});var Ta,Wh=C(()=>{le();Ta=class extends L{constructor({blockHash:t,blockNumber:r}){let n="Block";t&&(n=`Block at hash "${t}"`),r&&(n=`Block at number "${r}"`),super(`${n} could not be found.`,{name:"BlockNotFoundError"})}}});async function kr(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",includeTransactions:o}={}){let i=o??!1,s=r!==void 0?V(r):void 0,a=null;if(t?a=await e.request({method:"eth_getBlockByHash",params:[t,i]},{dedupe:!0}):a=await e.request({method:"eth_getBlockByNumber",params:[s||n,i]},{dedupe:!!s}),!a)throw new Ta({blockHash:t,blockNumber:r});return(e.chain?.formatters?.block?.format||Mh)(a,"getBlock")}var Ia=C(()=>{Wh();xe();Hh()});async function Kl(e){let t=await e.request({method:"eth_gasPrice"});return BigInt(t)}var Zh=C(()=>{});async function X6(e,t){let{block:r,chain:n=e.chain,request:o}=t||{};try{let i=n?.fees?.maxPriorityFeePerGas??n?.fees?.defaultPriorityFee;if(typeof i=="function"){let a=r||await oe(e,kr,"getBlock")({}),c=await i({block:a,client:e,request:o});if(c===null)throw new Error;return c}if(typeof i<"u")return i;let s=await e.request({method:"eth_maxPriorityFeePerGas"});return De(s)}catch{let[i,s]=await Promise.all([r?Promise.resolve(r):oe(e,kr,"getBlock")({}),oe(e,Kl,"getGasPrice")({})]);if(typeof i.baseFeePerGas!="bigint")throw new Fo;let a=s-i.baseFeePerGas;return a<0n?0n:a}}var J6=C(()=>{sd();Bt();vt();Ia();Zh()});async function Yh(e,t){let{block:r,chain:n=e.chain,request:o,type:i="eip1559"}=t||{},s=await(async()=>typeof n?.fees?.baseFeeMultiplier=="function"?n.fees.baseFeeMultiplier({block:r,client:e,request:o}):n?.fees?.baseFeeMultiplier??1.2)();if(s<1)throw new Aa;let c=10**(s.toString().split(".")[1]?.length??0),d=l=>l*BigInt(Math.round(s*c))/BigInt(c),f=r||await oe(e,kr,"getBlock")({});if(typeof n?.fees?.estimateFeesPerGas=="function"){let l=await n.fees.estimateFeesPerGas({block:r,client:e,multiply:d,request:o,type:i});if(l!==null)return l}if(i==="eip1559"){if(typeof f.baseFeePerGas!="bigint")throw new Fo;let l=typeof o?.maxPriorityFeePerGas=="bigint"?o.maxPriorityFeePerGas:await X6(e,{block:f,chain:n,request:o}),p=d(f.baseFeePerGas);return{maxFeePerGas:o?.maxFeePerGas??p+l,maxPriorityFeePerGas:l}}return{gasPrice:o?.gasPrice??d(await oe(e,Kl,"getGasPrice")({}))}}var Q6=C(()=>{sd();vt();J6();Ia();Zh()});async function Dt(e){let t=await e.request({method:"eth_chainId"},{dedupe:!0});return Xe(t)}var Mo=C(()=>{Bt()});async function Wl(e,t){let{account:r=e.account,accessList:n,authorizationList:o,chain:i=e.chain,blobVersionedHashes:s,blobs:a,data:c,gas:d,gasPrice:f,maxFeePerBlobGas:u,maxFeePerGas:l,maxPriorityFeePerGas:p,nonce:m,nonceManager:h,to:y,type:b,value:x,...g}=t,w=await(async()=>{if(!r||!h||typeof m<"u")return m;let N=ce(r),U=i?i.id:await oe(e,Dt,"getChainId")({});return await h.consume({address:N.address,chainId:U,client:e})})();Lt(t);let v=i?.formatters?.transactionRequest?.format,B=(v||sr)({...nn(g,{format:v}),account:r?ce(r):void 0,accessList:n,authorizationList:o,blobs:a,blobVersionedHashes:s,data:c,gas:d,gasPrice:f,maxFeePerBlobGas:u,maxFeePerGas:l,maxPriorityFeePerGas:p,nonce:w,to:y,type:b,value:x},"fillTransaction");try{let N=await e.request({method:"eth_fillTransaction",params:[B]}),R=(i?.formatters?.transaction?.format||Nn)(N.tx);delete R.blockHash,delete R.blockNumber,delete R.r,delete R.s,delete R.transactionIndex,delete R.v,delete R.yParity,R.data=R.input;let T=typeof R.feePayerSignature<"u"&&R.feePayerSignature!==null;if(T&&typeof w<"u"&&R.nonce!==w)throw new Us({filledNonce:R.nonce,requestedNonce:w});if(!T){R.gas&&(R.gas=t.gas??R.gas),R.gasPrice&&(R.gasPrice=t.gasPrice??R.gasPrice),R.maxFeePerBlobGas&&(R.maxFeePerBlobGas=t.maxFeePerBlobGas??R.maxFeePerBlobGas),R.maxFeePerGas&&(R.maxFeePerGas=t.maxFeePerGas??R.maxFeePerGas),R.maxPriorityFeePerGas&&(R.maxPriorityFeePerGas=t.maxPriorityFeePerGas??R.maxPriorityFeePerGas),typeof R.nonce<"u"&&(R.nonce=t.nonce??R.nonce);let O=await(async()=>{if(typeof i?.fees?.baseFeeMultiplier=="function"){let I=await oe(e,kr,"getBlock")({});return i.fees.baseFeeMultiplier({block:I,client:e,request:t})}return i?.fees?.baseFeeMultiplier??1.2})();if(O<1)throw new Aa;let P=10**(O.toString().split(".")[1]?.length??0),_=I=>I*BigInt(Math.round(O*P))/BigInt(P);R.maxFeePerGas&&!t.maxFeePerGas&&(R.maxFeePerGas=_(R.maxFeePerGas)),R.gasPrice&&!t.gasPrice&&(R.gasPrice=_(R.gasPrice))}return{raw:N.raw,transaction:{from:B.from,...R},...N.capabilities?{capabilities:N.capabilities}:{}}}catch(N){throw No(N,{...t,chain:e.chain})}}var Xh=C(()=>{Ye();sd();$t();ed();wa();_a();Mi();vt();Uo();Ia();Mo()});async function Ho(e,t){let r=t;r.account??=e.account,r.parameters??=ad;let{account:n,chain:o=e.chain,nonceManager:i,parameters:s}=r,a=(()=>{if(typeof o?.prepareTransactionRequest=="function")return{fn:o.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(o?.prepareTransactionRequest))return{fn:o.prepareTransactionRequest[0],runAt:o.prepareTransactionRequest[1].runAt}})(),c;async function d(){return c||(typeof r.chainId<"u"?r.chainId:o?o.id:(c=await oe(e,Dt,"getChainId")({}),c))}let f=n&&ce(n),u=r.nonce;if(a?.fn&&a.runAt?.includes("beforeFillTransaction")){r=await a.fn({...r,chain:o},{client:e,phase:"beforeFillTransaction"}),u??=r.nonce;let w=r.account??r.from;f=w?ce(w):void 0}if(s.includes("nonce")&&typeof u>"u"&&f&&i){let w=await d();u=await i.consume({address:f.address,chainId:w,client:e})}let p=((s.includes("blobVersionedHashes")||s.includes("sidecars"))&&r.kzg&&r.blobs?!1:s.length>0&&"feePayer"in r&&r.feePayer&&!("feePayerSignature"in r&&r.feePayerSignature)?!0:Jh.get(e.uid)===!1||!["fees","gas"].some(v=>s.includes(v))?!1:!!(s.includes("chainId")&&typeof r.chainId!="number"||s.includes("nonce")&&typeof u!="number"||s.includes("fees")&&typeof r.gasPrice!="bigint"&&(typeof r.maxFeePerGas!="bigint"||typeof r.maxPriorityFeePerGas!="bigint")||s.includes("gas")&&typeof r.gas!="bigint"))?await oe(e,Wl,"fillTransaction")({...r,nonce:u}).then(w=>{let{chainId:v,from:E,gas:B,gasPrice:N,nonce:U,maxFeePerBlobGas:R,maxFeePerGas:T,maxPriorityFeePerGas:O,type:H,...P}=w.transaction,_="feeToken"in P?P.feeToken:void 0,I="feePayerSignature"in P&&P.feePayerSignature!==null&&typeof P.feePayerSignature<"u",k=typeof _<"u"&&_!==null&&(!("feeToken"in r)||I);return Jh.set(e.uid,!0),{...r,...E?{from:E}:{},...H&&!r.type?{type:H}:{},...typeof v<"u"?{chainId:v}:{},...typeof B<"u"?{gas:B}:{},...typeof N<"u"?{gasPrice:N}:{},...typeof U<"u"?{nonce:U}:{},...typeof R<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerBlobGas:R}:{},...typeof T<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerGas:T}:{},...typeof O<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxPriorityFeePerGas:O}:{},..."nonceKey"in P&&typeof P.nonceKey<"u"?{nonceKey:P.nonceKey}:{},..."validBefore"in P&&P.validBefore!==null&&typeof P.validBefore<"u"?{validBefore:P.validBefore}:{},..."validAfter"in P&&P.validAfter!==null&&typeof P.validAfter<"u"?{validAfter:P.validAfter}:{},..."keyAuthorization"in P&&typeof P.keyAuthorization<"u"&&P.keyAuthorization!==null&&!("keyAuthorization"in r)?{keyAuthorization:P.keyAuthorization}:{},..."feePayerSignature"in P&&typeof P.feePayerSignature<"u"&&P.feePayerSignature!==null?{feePayerSignature:P.feePayerSignature}:{},...k?{feeToken:_}:{},...w.capabilities?{_capabilities:w.capabilities}:{}}}).catch(w=>{let v=w;if(v.name!=="TransactionExecutionError")return r;if(v.walk?.(U=>U instanceof Us)||v.walk?.(U=>U.name==="ExecutionRevertedError"))throw w;return v.walk?.(U=>{let R=U;return R.name==="MethodNotFoundRpcError"||R.name==="MethodNotSupportedRpcError"||R.message?.includes("eth_fillTransaction is not available")})&&Jh.set(e.uid,!1),r}):r;u??=p.nonce,r={...p,...f?{from:f?.address}:{},...typeof u<"u"?{nonce:u}:{}};let{blobs:m,gas:h,kzg:y,type:b}=r;a?.fn&&a.runAt?.includes("beforeFillParameters")&&(r=await a.fn({...r,chain:o},{client:e,phase:"beforeFillParameters"}));let x;async function g(){return x||(x=await oe(e,kr,"getBlock")({blockTag:"latest"}),x)}if(s.includes("nonce")&&typeof u>"u"&&f&&!i&&(r.nonce=await oe(e,Nl,"getTransactionCount")({address:f.address,blockTag:"pending"})),(s.includes("blobVersionedHashes")||s.includes("sidecars"))&&m&&y){let w=Ms({blobs:m,kzg:y});if(s.includes("blobVersionedHashes")){let v=el({commitments:w,to:"hex"});r.blobVersionedHashes=v}if(s.includes("sidecars")){let v=Hs({blobs:m,commitments:w,kzg:y}),E=ol({blobs:m,commitments:w,proofs:v,to:"hex"});r.sidecars=E}}if(s.includes("chainId")&&(r.chainId=await d()),(s.includes("fees")||s.includes("type"))&&typeof b>"u")try{r.type=cl(r)}catch{let w=e5.get(e.uid);typeof w>"u"&&(w=typeof(await g())?.baseFeePerGas=="bigint",e5.set(e.uid,w)),r.type=w?"eip1559":"legacy"}if(s.includes("fees"))if(r.type!=="legacy"&&r.type!=="eip2930"){if(typeof r.maxFeePerGas>"u"||typeof r.maxPriorityFeePerGas>"u"){let w=await g(),{maxFeePerGas:v,maxPriorityFeePerGas:E}=await Yh(e,{block:w,chain:o,request:r});if(typeof r.maxPriorityFeePerGas>"u"&&r.maxFeePerGas&&r.maxFeePerGas<E)throw new Vl({maxPriorityFeePerGas:E});r.maxPriorityFeePerGas=E,r.maxFeePerGas=v}}else{if(typeof r.maxFeePerGas<"u"||typeof r.maxPriorityFeePerGas<"u")throw new Fo;if(typeof r.gasPrice>"u"){let w=await g(),{gasPrice:v}=await Yh(e,{block:w,chain:o,request:r,type:"legacy"});r.gasPrice=v}}return s.includes("gas")&&typeof h>"u"&&(r.gas=await oe(e,Zl,"estimateGas")({...r,account:f,prepare:f?.type==="local"?[]:["blobVersionedHashes"]})),a?.fn&&a.runAt?.includes("afterFillParameters")&&(r=await a.fn({...r,chain:o},{client:e,phase:"afterFillParameters"})),Lt(r),delete r.parameters,r}var ad,e5,Jh,cd=C(()=>{Ye();Q6();Qh();Ia();$h();sd();$t();Ju();Qu();gh();xh();vt();xi();Uo();Sh();Xh();Mo();ad=["blobVersionedHashes","chainId","fees","gas","nonce","type"],e5=new Map,Jh=new Mt(128)});async function Zl(e,t){let{account:r=e.account,prepare:n=!0}=t,o=r?ce(r):void 0,i=(()=>{if(Array.isArray(n))return n;if(o?.type!=="local")return["blobVersionedHashes"]})();try{let s=await(async()=>{if(t.to)return t.to;if(t.authorizationList&&t.authorizationList.length>0)return await Rs({authorization:t.authorizationList[0]}).catch(()=>{throw new L("`to` is required. Could not infer from `authorizationList`")})})(),{accessList:a,authorizationList:c,blobs:d,blobVersionedHashes:f,blockNumber:u,blockTag:l,data:p,gas:m,gasPrice:h,maxFeePerBlobGas:y,maxFeePerGas:b,maxPriorityFeePerGas:x,nonce:g,value:w,stateOverride:v,...E}=n?await Ho(e,{...t,parameters:i,to:s}):t;if(m&&t.gas!==m)return m;let N=(typeof u=="bigint"?V(u):void 0)||l,U=Il(v);Lt(t);let R=e.chain?.formatters?.transactionRequest?.format,O=(R||sr)({...nn(E,{format:R}),account:o,accessList:a,authorizationList:c,blobs:d,blobVersionedHashes:f,data:p,gasPrice:h,maxFeePerBlobGas:y,maxFeePerGas:b,maxPriorityFeePerGas:x,nonce:g,to:s,value:w},"estimateGas");return BigInt(await e.request({method:"eth_estimateGas",params:U?[O,N??e.experimental_blockTag??"latest",U]:N?[O,N]:[O]}))}catch(s){throw E6(s,{...t,account:o,chain:e.chain})}}var Qh=C(()=>{Ye();le();Lu();xe();_6();wa();Mi();Rh();Uo();cd()});async function Yl(e,t){let{abi:r,address:n,args:o,functionName:i,dataSuffix:s=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=Yt({abi:r,args:o,functionName:i});try{return await oe(e,Zl,"estimateGas")({data:`${c}${s?s.replace("0x",""):""}`,to:n,...a})}catch(d){let f=a.account?ce(a.account):void 0;throw Ea(d,{abi:r,address:n,args:o,docsPath:"/docs/contract/estimateContractGas",functionName:i,sender:f?.address})}}var ey=C(()=>{Ye();Si();Cl();vt();Qh()});async function Xl(e,t){let{abi:r,address:n,args:o,functionName:i,dataSuffix:s=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=a.account?ce(a.account):e.account,d=Yt({abi:r,args:o,functionName:i});try{let{data:f}=await oe(e,kl,"call")({batch:!1,data:`${d}${s?s.replace("0x",""):""}`,to:n,...a,account:c}),u=ku({abi:r,args:o,functionName:i,data:f||"0x"}),l=r.filter(p=>"name"in p&&p.name===t.functionName);return{result:u,request:{abi:l,address:n,args:o,dataSuffix:s,functionName:i,...a,account:c}}}catch(f){throw Ea(f,{abi:r,address:n,args:o,docsPath:"/docs/contract/simulateContract",functionName:i,sender:c?.address})}}var ty=C(()=>{Ye();Um();Si();Cl();vt();Oh()});function Hi(e,t,r){let n=++B4,o=()=>Jl.get(e)||[],i=()=>{let u=o().filter(l=>l.id!==n);if(u.length===0){Jl.delete(e),ry.delete(e);return}Jl.set(e,u)},s=()=>{let f=o();if(!f.some(l=>l.id===n))return;let u=ry.get(e);if(f.length===1&&u){let l=u();l instanceof Promise&&l.catch(()=>{})}i()},a=o();if(Jl.set(e,[...a,{id:n,fns:t}]),a&&a.length>0)return s;let c={};for(let f in t)c[f]=((...u)=>{let l=o();if(l.length!==0)for(let p of l)p.fns[f]?.(...u)});let d=r(c);return typeof d=="function"&&ry.set(e,d),s}var Jl,ry,B4,Ql=C(()=>{Jl=new Map,ry=new Map,B4=0});function ep(e,{emitOnBegin:t,initialWaitTime:r,interval:n}){let o=!0,i=()=>o=!1;return(async()=>{let a;t&&(a=await e({unpoll:i}));let c=await r?.(a)??n;await Xc(c);let d=async()=>{o&&(await e({unpoll:i}),await Xc(n),d())};d()})(),i}var ny=C(()=>{_h()});function t5(e){let t=(o,i)=>({clear:()=>i.delete(o),get:()=>i.get(o),set:s=>i.set(o,s)}),r=t(e,P4),n=t(e,R4);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function r5(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){let n=t5(t),o=n.response.get();if(o&&r>0&&Date.now()-o.created.getTime()<r)return o.data;let i=n.promise.get();i||(i=e(),n.promise.set(i));try{let s=await i;return n.response.set({created:new Date,data:s}),s}finally{n.promise.clear()}}var P4,R4,n5=C(()=>{P4=new Map,R4=new Map});async function o5(e,{cacheTime:t=e.cacheTime}={}){let r=await r5(()=>e.request({method:"eth_blockNumber"}),{cacheKey:O4(e.uid),cacheTime:t});return BigInt(r)}var O4,i5=C(()=>{n5();O4=e=>`blockNumber.${e}`});var st,ar,Mn=C(()=>{le();st=class extends L{constructor({docsPath:t}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(`
40
+ `),{docsPath:t,docsSlug:"account",name:"AccountNotFoundError"})}},ar=class extends L{constructor({docsPath:t,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:t,metaMessages:r,name:"AccountTypeNotSupportedError"})}}});async function tp(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}var oy=C(()=>{});async function zo(e,t){let{account:r=e.account,assertChainId:n=!0,chain:o=e.chain,accessList:i,authorizationList:s,blobs:a,data:c,dataSuffix:d=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,gas:f,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:p,maxPriorityFeePerGas:m,nonce:h,type:y,value:b,...x}=t;if(typeof r>"u")throw new st({docsPath:"/docs/actions/wallet/sendTransaction"});let g=r?ce(r):null,w;try{Lt(t);let v=await(async()=>{if(t.to)return t.to;if(t.to!==null&&s&&s.length>0)return await Rs({authorization:s[0]}).catch(()=>{throw new L("`to` is required. Could not infer from `authorizationList`.")})})();if(g?.type==="json-rpc"||g===null){let E;o!==null&&(E=await oe(e,Dt,"getChainId")({}),n&&Sa({currentChainId:E,chain:o}));let B=e.chain?.formatters?.transactionRequest?.format,U=(B||sr)({...nn(x,{format:B}),accessList:i,account:g,authorizationList:s,blobs:a,chainId:E,data:d?Er([c??"0x",d]):c,gas:f,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:p,maxPriorityFeePerGas:m,nonce:h,to:v,type:y,value:b},"sendTransaction"),R=iy.get(e.uid),T=R?"wallet_sendTransaction":"eth_sendTransaction";try{return await e.request({method:T,params:[U]},{retryCount:0})}catch(O){if(R===!1)throw O;let H=O;if(H.name==="InvalidInputRpcError"||H.name==="InvalidParamsRpcError"||H.name==="MethodNotFoundRpcError"||H.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[U]},{retryCount:0}).then(P=>(iy.set(e.uid,!0),P)).catch(P=>{let _=P;throw _.name==="MethodNotFoundRpcError"||_.name==="MethodNotSupportedRpcError"?(iy.set(e.uid,!1),H):_});throw H}}if(g?.type==="local"){let E=(()=>{if(!g.nonceManager||typeof h<"u")return g.nonceManager;let O=g.nonceManager;return{consume(H){return w={address:H.address,chainId:H.chainId},O.consume(H)},get(H){return O.get(H)},increment(H){return O.increment(H)},reset(H){return O.reset(H)}}})(),B=await oe(e,Ho,"prepareTransactionRequest")({account:g,accessList:i,authorizationList:s,blobs:a,chain:o,data:d?Er([c??"0x",d]):c,gas:f,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:p,maxPriorityFeePerGas:m,nonce:h,nonceManager:E,parameters:[...ad,"sidecars"],type:y,value:b,...x,to:v}),N=o?.serializers?.transaction,U=await g.signTransaction(B,{serializer:N}),R=(o??e.chain)?.serializers?.transactionEnvelope,T=R?await R({serializedTransaction:U,transaction:B}):U;return await oe(e,tp,"sendRawTransaction")({serializedTransaction:T})}throw g?.type==="smart"?new ar({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new ar({docsPath:"/docs/actions/wallet/sendTransaction",type:g?.type})}catch(v){throw v instanceof ar?v:(w&&g?.nonceManager?.reset(w),No(v,{...t,account:g,chain:t.chain||void 0}))}}var iy,dd=C(()=>{Ye();Mn();le();Lu();Ol();or();ed();wa();Mi();vt();xi();Uo();Mo();cd();oy();iy=new Mt(128)});async function Br(e,t){return Br.internal(e,zo,"sendTransaction",t)}var fd=C(()=>{Ye();Mn();Si();Cl();vt();dd();(function(e){async function t(r,n,o,i){let{abi:s,account:a=r.account,address:c,args:d,functionName:f,...u}=i;if(typeof a>"u")throw new st({docsPath:"/docs/contract/writeContract"});let l=a?ce(a):null,p=Yt({abi:s,args:d,functionName:f});try{return await oe(r,n,o)({data:p,to:c,account:l,...u})}catch(m){throw Ea(m,{abi:s,address:c,args:d,docsPath:"/docs/contract/writeContract",functionName:f,sender:l?.address})}}e.internal=t})(Br||(Br={}))});async function l5(e,{blockHash:t,blockNumber:r,blockTag:n,hash:o,index:i,sender:s,nonce:a}){let c=n||"latest",d=r!==void 0?V(r):void 0,f=null;if(o?f=await e.request({method:"eth_getTransactionByHash",params:[o]},{dedupe:!0}):t?f=await e.request({method:"eth_getTransactionByBlockHashAndIndex",params:[t,V(i)]},{dedupe:!0}):(d||c)&&typeof i=="number"?f=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[d||c,V(i)]},{dedupe:!!d}):s&&typeof a=="number"&&(f=await e.request({method:"eth_getTransactionBySenderAndNonce",params:[s,V(a)]},{dedupe:!0})),!f)throw new Ns({blockHash:t,blockNumber:r,blockTag:c,hash:o,index:i});return(e.chain?.formatters?.transaction?.format||Nn)(f,"getTransaction")}var p5=C(()=>{$t();xe();_a()});async function dp(e,{hash:t}){let r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new Fs({hash:t});return(e.chain?.formatters?.transactionReceipt?.format||td)(r,"getTransactionReceipt")}var m5=C(()=>{$t();rd()});function h5(e,{emitOnBegin:t=!1,emitMissed:r=!1,onBlockNumber:n,onError:o,poll:i,pollingInterval:s=e.pollingInterval}){let a=typeof i<"u"?i:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")),c;return a?(()=>{let u=qe(["watchBlockNumber",e.uid,t,r,s]);return Hi(u,{onBlockNumber:n,onError:o},l=>ep(async()=>{try{let p=await oe(e,o5,"getBlockNumber")({cacheTime:0});if(c!==void 0){if(p===c)return;if(p-c>1&&r)for(let m=c+1n;m<p;m++)l.onBlockNumber(m,c),c=m}(c===void 0||p>c)&&(l.onBlockNumber(p,c),c=p)}catch(p){l.onError?.(p)}},{emitOnBegin:t,interval:s}))})():(()=>{let u=qe(["watchBlockNumber",e.uid,t,r]);return Hi(u,{onBlockNumber:n,onError:o},l=>{let p=!0,m=()=>p=!1;return(async()=>{try{let h=(()=>{if(e.transport.type==="fallback"){let b=e.transport.transports.find(x=>x.config.type==="webSocket"||x.config.type==="ipc");return b?b.value:e.transport}return e.transport})(),{unsubscribe:y}=await h.subscribe({params:["newHeads"],onData(b){if(!p)return;let x=De(b.result?.number);l.onBlockNumber(x,c),c=x},onError(b){l.onError?.(b)}});m=y,p||m()}catch(h){o?.(h)}})(),()=>m()})})()}var y5=C(()=>{Bt();vt();Ql();ny();_r();i5()});async function b5(e,t){let{checkReplacement:r=e.chain?.supportsTransactionReplacementDetection??!0,confirmations:n=1,hash:o,onReplaced:i,retryCount:s=6,retryDelay:a=({count:E})=>~~(1<<E)*200,timeout:c=18e4}=t,d=E=>e.chain?.transactionReplacement?.getKey?.(E)??String(E.nonce),f=t.pollingInterval?t.pollingInterval:e.chain?.experimental_preconfirmationTime?e.chain.experimental_preconfirmationTime:e.pollingInterval,u=qe(["waitForTransactionReceipt",e.uid,o,{checkReplacement:r,confirmations:n,pollingInterval:f,retryCount:s,timeout:c}]),l,p,m,h=!1,y,b,{promise:x,resolve:g,reject:w}=va(),v=c?setTimeout(()=>{b?.(),y?.(),w(new Xu({hash:o}))},c):void 0;return y=Hi(u,{onReplaced:i,resolve:g,reject:w},async E=>{if(m=await oe(e,dp,"getTransactionReceipt")({hash:o}).catch(()=>{}),m&&n<=1){clearTimeout(v),E.resolve(m),y?.();return}b=oe(e,h5,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:f,async onBlockNumber(B){let N=R=>{clearTimeout(v),b?.(),R(),y?.()},U=B;if(!h)try{if(m){if(n>1&&(!m.blockNumber||U-m.blockNumber+1n<n))return;N(()=>E.resolve(m));return}if(r&&!l&&(h=!0,await Ni(async()=>{l=await oe(e,l5,"getTransaction")({hash:o}),l.blockNumber&&(U=l.blockNumber)},{delay:a,retryCount:s}),h=!1),m=await oe(e,dp,"getTransactionReceipt")({hash:o}),n>1&&(!m.blockNumber||U-m.blockNumber+1n<n))return;N(()=>E.resolve(m))}catch(R){if(R instanceof Ns||R instanceof Fs){if(!l){h=!1;return}if(l.blockNumber){h=!1;return}try{p=l,h=!0;let T=await Ni(()=>oe(e,kr,"getBlock")({blockNumber:U,includeTransactions:!0}),{delay:a,retryCount:s,shouldRetry:({error:_})=>_ instanceof Ta});h=!1;let O=d(p),H=T.transactions.find(_=>Ht(_.from,p.from)&&_.hash!==p.hash&&d(_)===O);if(!H||(m=await oe(e,dp,"getTransactionReceipt")({hash:H.hash}),n>1&&(!m.blockNumber||U-m.blockNumber+1n<n)))return;let P=e.chain?.transactionReplacement?.getReason?.({replaced:p,replacement:H})??N4(p,H);N(()=>{E.onReplaced?.({reason:P,replacedTransaction:p,transaction:H,transactionReceipt:m}),E.resolve(m)})}catch(T){N(()=>E.reject(T))}}else N(()=>E.reject(R))}}})}),x}function N4(e,t){return(t.to&&e.to?Ht(t.to,e.to):t.to===e.to)&&t.value===e.value&&t.input===e.input?"repriced":t.from===t.to&&t.value===0n?"cancelled":"replaced"}var g5=C(()=>{Wh();$t();Ei();vt();Ql();Tl();ll();_r();Ia();p5();m5();y5()});function fp(e,t){if(typeof e=="bigint")return e;let r=e.decimals??t;return C6(e.formatted,F4(r))}function F4(e){if(e===void 0)throw new Error("Token decimals are required. Pass `amount.decimals` or select a declared token.");return e}function up(e,t){return typeof e=="bigint"?t:e.decimals??t}function $o(e,t){let{decimals:r,token:n}=t,o=M4(e,n);if(o)return{address:o.address,decimals:r??o.decimals};if(pe(n,{strict:!1}))return{address:n,decimals:r??z4(e,n)};throw new Error(`Token "${n}" is not a declared ERC-20 token on the client's \`tokens\` array (with an address for the client's chain), and is not a valid address.`)}function M4(e,t){let r=e.tokens,n=e.chain?.id;if(!r||n===void 0)return;let o=H4(r,t);if(o)return dy(o,n);if(pe(t,{strict:!1}))for(let i of r){let s=dy(i,n);if(s&&Ht(s.address,t))return s}}function dy(e,t){let r=e.addresses[t];if(r)return{address:r,currency:e.currency,decimals:e.decimals,name:e.name,popular:e.popular,symbol:e.symbol}}function H4(e,t){let r=t.toLowerCase();for(let n of e)if(n.symbol?.toLowerCase()===r)return n}function z4(e,t){let r=e.tokens,n=e.chain?.id;if(r&&n!==void 0)for(let o of r){let i=dy(o,n);if(i&&Ht(i.address,t))return i.decimals}}function ka(e){let{account:t,chain:r,gas:n,maxFeePerGas:o,maxPriorityFeePerGas:i,nonce:s}=e;return{account:t,chain:r,gas:n,maxFeePerGas:o,maxPriorityFeePerGas:i,nonce:s}}function lp(e){return{...e,data:Yt(e),to:e.address}}var ld=C(()=>{Zt();Ei();Dh();U6()});async function pp(e,{serializedTransaction:t,throwOnReceiptRevert:r,timeout:n}){let o=await e.request({method:"eth_sendRawTransactionSync",params:n?[t,n]:[t]},{retryCount:0}),s=(e.chain?.formatters?.transactionReceipt?.format||td)(o);if(s.status==="reverted"&&r)throw new ki({receipt:s});return s}var fy=C(()=>{$t();rd()});async function mp(e,t){let{account:r=e.account,assertChainId:n=!0,chain:o=e.chain,accessList:i,authorizationList:s,blobs:a,data:c,dataSuffix:d=typeof e.dataSuffix=="string"?e.dataSuffix:e.dataSuffix?.value,gas:f,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:p,maxPriorityFeePerGas:m,nonce:h,pollingInterval:y,throwOnReceiptRevert:b,type:x,value:g,...w}=t,v=t.timeout??Math.max((o?.blockTime??0)*3,5e3);if(typeof r>"u")throw new st({docsPath:"/docs/actions/wallet/sendTransactionSync"});let E=r?ce(r):null,B;try{Lt(t);let N=await(async()=>{if(t.to)return t.to;if(t.to!==null&&s&&s.length>0)return await Rs({authorization:s[0]}).catch(()=>{throw new L("`to` is required. Could not infer from `authorizationList`.")})})();if(E?.type==="json-rpc"||E===null){let U;o!==null&&(U=await oe(e,Dt,"getChainId")({}),n&&Sa({currentChainId:U,chain:o}));let R=e.chain?.formatters?.transactionRequest?.format,O=(R||sr)({...nn(w,{format:R}),accessList:i,account:E,authorizationList:s,blobs:a,chainId:U,data:d?Er([c??"0x",d]):c,gas:f,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:p,maxPriorityFeePerGas:m,nonce:h,to:N,type:x,value:g},"sendTransaction"),H=uy.get(e.uid),P=H?"wallet_sendTransaction":"eth_sendTransaction",_=await(async()=>{try{return await e.request({method:P,params:[O]},{retryCount:0})}catch(k){if(H===!1)throw k;let M=k;if(M.name==="InvalidInputRpcError"||M.name==="InvalidParamsRpcError"||M.name==="MethodNotFoundRpcError"||M.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[O]},{retryCount:0}).then($=>(uy.set(e.uid,!0),$)).catch($=>{let F=$;throw F.name==="MethodNotFoundRpcError"||F.name==="MethodNotSupportedRpcError"?(uy.set(e.uid,!1),M):F});throw M}})(),I=await oe(e,b5,"waitForTransactionReceipt")({checkReplacement:!1,hash:_,pollingInterval:y,timeout:v});if(b&&I.status==="reverted")throw new ki({receipt:I});return I}if(E?.type==="local"){let U=(()=>{if(!E.nonceManager||typeof h<"u")return E.nonceManager;let _=E.nonceManager;return{consume(I){return B={address:I.address,chainId:I.chainId},_.consume(I)},get(I){return _.get(I)},increment(I){return _.increment(I)},reset(I){return _.reset(I)}}})(),R=await oe(e,Ho,"prepareTransactionRequest")({account:E,accessList:i,authorizationList:s,blobs:a,chain:o,data:d?Er([c??"0x",d]):c,gas:f,gasPrice:u,maxFeePerBlobGas:l,maxFeePerGas:p,maxPriorityFeePerGas:m,nonce:h,nonceManager:U,parameters:[...ad,"sidecars"],type:x,value:g,...w,to:N}),T=o?.serializers?.transaction,O=await E.signTransaction(R,{serializer:T}),H=(o??e.chain)?.serializers?.transactionEnvelope,P=H?await H({serializedTransaction:O,transaction:R}):O;return await oe(e,pp,"sendRawTransactionSync")({serializedTransaction:P,throwOnReceiptRevert:b,timeout:t.timeout})}throw E?.type==="smart"?new ar({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new ar({docsPath:"/docs/actions/wallet/sendTransactionSync",type:E?.type})}catch(N){throw N instanceof ar?N:(B&&!(N instanceof ki)&&E?.nonceManager?.reset(B),No(N,{...t,account:E,chain:t.chain||void 0}))}}var uy,ly=C(()=>{Ye();Mn();le();$t();Lu();Ol();or();ed();wa();Mi();vt();xi();Uo();Mo();g5();cd();fy();uy=new Mt(128)});async function Ba(e,t){return Br.internal(e,mp,"sendTransactionSync",t)}var hp=C(()=>{ly();fd()});var e8=["invalid_arguments","invalid_config","invalid_record","config_conflict","agent_policy","human_only","confirmation_required","sale_not_approved","trust_required","signer_required","signer_init_only","credentials_required","backup_secret_required","work_dir_required","max_price_required","budget_required","budget_exceeded","base_rpc_required","transport_required","near_wallet_required","base_wallet_required","base_unavailable","route_unavailable","file_required","offer_required","purchase_required","origin_required","origin_asset_required","origin_not_allowed","resource_not_allowed","path_not_allowed","output_exists","unknown_file","already_registered","taken_down","sales_stopped","unknown_moderator","storage_required","funding_refused","file_storage_low","protocol_fee_above_max","price_mismatch","price_above_max","recipient_mismatch","file_mismatch","network_mismatch","token_mismatch","method_mismatch","untrusted_contract","file_invalid","bad_requirements","insufficient_balance","smart_wallet_unsupported","bad_signature","payment_rejected","purchase_open","payment_id_conflict","payment_expired","payment_not_found","payment_used","quote_refused","quote_expired","settlement_pending","transaction_uncertain","not_sponsored","not_buyer","bad_magic","unsupported_version","bad_chunk_size","header_too_large","bad_header","bad_stanza","file_id_mismatch","cipher_hash_mismatch","seller_signature_invalid","bad_body_length","chunk_hash_mismatch","no_usable_stanza","key_unwrap_failed","header_mac_invalid","chunk_invalid","meta_invalid","preview_invalid","ckd_failed","ckd_invalid","rejected","wrong_chain","wrong_identity","invalid_signature","missing_method","invalid_response","wallet_error","store_conflict","lease_busy","source_changed","sell_incomplete","recovery_not_final","transport","refused","bad_request","bad_deadline","limited","duplicate","in_flight","unavailable","disabled","rate_limited","budget","busy","not_found","internal","relayer_unavailable","relayer_rate_limited","base_rpc_rate_limited","near_rpc_rate_limited","host_payment_failed","facilitator_busy","bad_response","not_authorized","cancelled","too_large","download_limited","download_in_progress","file_expired","upload_expired","upload_conflict","upload_incomplete","host_capacity","operation_failed"],yd={route_unavailable:"This file does not support the selected payment route.",host_payment_failed:"Payment submission failed. Keep the saved purchase and check final status before retrying.",bad_request:"The request is invalid. Check its fields before retrying.",bad_deadline:"The authorization deadline is invalid or expired.",invalid_arguments:"Invalid arguments. Run annon --help.",invalid_record:"Invalid saved record. Export necessary test evidence and clear development state.",transport:"The service could not be reached. Keep saved state and retry later.",recovery_not_final:"The recovery grant is not final. Resume the saved recovery later.",invalid_signature:"The wallet did not authorize the exact requested message.",operation_failed:"Operation failed. Check configuration, funding and final purchase status before retrying. Saved encrypted records are retained.",transaction_uncertain:"Transaction submission is uncertain. Check the saved purchase and transaction hash before retrying.",quote_refused:"The 1Click quote was refused. Review the source asset and amount before retrying.",base_rpc_rate_limited:"The Base RPC is rate limiting requests. Configure a Base RPC endpoint with an API key (baseRpc).",near_rpc_rate_limited:"Configure a NEAR RPC endpoint with an API key (nearRpc).",budget_exceeded:"The persisted spending budget is exhausted.",download_limited:"Download limit reached. Wait before downloading again.",download_in_progress:"Another download is active. Wait before retrying.",rate_limited:"The host is busy. Wait before retrying.",unavailable:"The service is temporarily unavailable. Wait before retrying.",transport_required:"Configure a trusted relayer before a Base purchase.",relayer_unavailable:"Base sponsorship checks are unavailable. Retry before paying.",not_sponsored:"This listing does not qualify for Base sponsorship. Do not pay through this route.",wrong_identity:"The wallet does not control the required identity.",settlement_pending:"The purchase is still settling. Wait before retrying the saved purchase.",protocol_fee_above_max:"The advertised protocol fee exceeds maxProtocolFee. Review the fee in human configuration.",funding_refused:"File funding was refused. Correct the cause before retrying.",file_storage_low:"This file needs more purchase storage funding before a NEAR or 1Click payment.",source_changed:"The source changed between passes. Resume sell with the original plaintext and saved fileId.",quote_expired:"The 1Click quote expired. Run buy again.",storage_required:"Prepay storage with storageDeposit before register or reopen, then resume the saved operation.",unknown_file:"The configured contract has no such file. Check the file ID and deployment.",taken_down:"The moderator has taken down this file; key release is blocked.",sales_stopped:"The seller has stopped new sales. Use a saved purchase to open an earlier purchase.",unknown_moderator:"Review this file's moderator and explicitly accept it with the moderator option before buying.",price_above_max:"The registered price exceeds maxPrice. Review the current terms before buying.",untrusted_contract:"The offer names a different contract. Review that deployment and configure it explicitly.",network_mismatch:"The deployment network or USDC asset differs from the configured network. Check the configuration.",store_conflict:"Another process updated this purchase. Keep the encrypted state and check status before retrying.",file_invalid:"The file failed SDK verification. Obtain the registered file from its host.",file_mismatch:"The file or offer differs from its registered commitment. Obtain the correct file or offer.",bad_requirements:"The host offer failed SDK validation. Obtain an updated Annon offer.",not_authorized:"The host has not accepted this final grant. Check final purchase status and the resource URL."};function bd(e){return typeof e=="string"&&e8.includes(e)}function Ua(e){let t=e&&typeof e=="object"&&"code"in e?e.code:void 0;return t==="transport"||t==="base_rpc_rate_limited"||t==="near_rpc_rate_limited"}var S=class extends Error{code;constructor(t,r=yd[t]??`${t.replaceAll("_"," ")}.`,n){super(r,n),this.code=t,this.name="AnnonError"}},t8=new Set(["budget","settlement_pending","transaction_uncertain","transport","base_rpc_rate_limited","near_rpc_rate_limited","relayer_unavailable","relayer_rate_limited","download_limited","download_in_progress","rate_limited","unavailable","in_flight","busy","facilitator_busy","lease_busy","recovery_not_final","host_capacity","limited"]),r8=new Set(["agent_policy","human_only","confirmation_required","sale_not_approved","trust_required"]),n8=new Set(["invalid_arguments","invalid_config","invalid_record","config_conflict","agent_policy","human_only","confirmation_required","sale_not_approved","trust_required","signer_required","signer_init_only","credentials_required","backup_secret_required","work_dir_required","max_price_required","budget_required","base_rpc_required","transport_required","near_wallet_required","base_wallet_required","base_unavailable","route_unavailable","file_required","offer_required","purchase_required","origin_required","origin_asset_required","origin_not_allowed","resource_not_allowed","path_not_allowed","output_exists","network_mismatch","bad_request","bad_deadline"]);function Ko(e){let t=e&&typeof e=="object"?e:{};if(!bd(t.code))return{code:"operation_failed",message:yd.operation_failed??"Operation failed.",exitCode:1};let r=t.code,n=e instanceof S&&e.name==="AdapterError"?e:void 0,o=a=>typeof a=="string"&&/^0x[0-9a-f]{64}$/.test(a),i=typeof t.retryAfterSeconds=="number"&&t.retryAfterSeconds>=0?Math.ceil(t.retryAfterSeconds):NaN,s=Number.isSafeInteger(i)?i:r==="settlement_pending"?30:void 0;return{code:r,message:(r==="route_unavailable"?yd.route_unavailable:n?.message)??(yd[r]??`${r.replaceAll("_"," ")}.`)+(e instanceof S&&e.name==="SellError"&&r!=="source_changed"?" Resume sell with the original plaintext and saved fileId.":""),exitCode:(r==="route_unavailable"?2:n?.exitCode)??(t8.has(r)?4:r8.has(r)?3:n8.has(r)?2:1),...o(t.fileId)?{fileId:t.fileId}:{},...o(t.purchaseId)?{purchaseId:t.purchaseId}:{},...typeof t.txHash=="string"?{txHash:t.txHash}:{},...typeof t.minimumAmountUsdc=="string"&&/^(0|[1-9][0-9]*)(\.[0-9]+)?$/.test(t.minimumAmountUsdc)?{minimumAmountUsdc:t.minimumAmountUsdc}:{},...s!==void 0?{retryAfterSeconds:s}:{}}}function X(e,t="invalid_record"){if(e==null)throw new S(t);return e}var gd=e=>Object.freeze(e());function o8(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Na(e){if(!o8(e))throw new TypeError("Uint8Array expected")}function Fa(e,t){if(typeof t!="string")throw new TypeError(`${e}: string expected`);return!0}function Oy(e,t="number"){if(typeof e!="number")throw new TypeError(`${t}: expected number, got ${typeof e}`);if(!Number.isSafeInteger(e))throw new RangeError(`${t}: expected safe integer, got ${e}`)}function Cy(...e){let t=i=>i,r=(i,s)=>a=>i(s(a)),n=e.map(i=>i.encode).reduceRight(r,t),o=e.map(i=>i.decode).reduce(r,t);return{encode:n,decode:o}}var i8=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();var Py=(()=>{try{let e=new TextDecoder;return e.decode(Uint8Array.of(65,48,43,127))==="A0+\x7F"?e:void 0}catch{return}})(),Ip=8192;function s8(e){let t=e.length;if(Py!==void 0&&t>=12)return Py.decode(e);if(t<=Ip)return String.fromCharCode.apply(null,e);let r="";for(let n=0;n<t;n+=Ip)r+=String.fromCharCode.apply(null,e.subarray(n,n+Ip));return r}function Uy(e){if(Oy(e),e<=0||e>8)throw new RangeError("radix2: bits should be in (0..8]");let t=i8[e]-1;return{encode:r=>{Na(r);let n=r.length,o=new Uint8Array(Math.ceil(n*8/e)),i=0,s=0,a=0;for(let c=0;c<n;)for(c+2<n?(i=i<<24|r[c]<<16|r[c+1]<<8|r[c+2],s+=24,c+=3):(i=(i<<8|r[c])&65535,s+=8,c++);s-=e,o[a++]=i>>s&t,!(s<e););return s>0&&(o[a]=i<<e-s&t),o},decode:r=>{let n=r.length,o=new Uint8Array(Math.floor(n*e/8)),i=0,s=0,a=0;for(let c=0;c<n;c++)for(i=(i<<e|r[c])&65535,s+=e;s>=8;s-=8)o[a++]=i>>s-8&255;if(i=i<<8-s&255,s>=e)throw new Error("Excess padding");if(i>0)throw new Error(`Non-zero padding: ${i}`);return o}}}function kp(e,t){let r=e.length;if(r>128)throw new Error("alphabet: max 128 letters");let n=new Uint8Array(r),o=new Int8Array(128).fill(-1);for(let i=0;i<r;i++){let s=e.charCodeAt(i);if(e.codePointAt(i)!==s||s>127)throw new Error("alphabet: single-char ASCII letters only");n[i]=s,o[s]=i}if(t!==void 0)for(let i of Object.keys(t)){let s=i.charCodeAt(0),a=o[t[i].charCodeAt(0)];if(i.length!==1||s>127||a===void 0||a===-1)throw new Error(`alphabet: invalid alias ${i}`);o[s]=a}return{encode:i=>{let s=new Uint8Array(i.length);for(let a=0;a<i.length;a++){let c=i[a],d=n[c];if(d===void 0)throw new Error(`alphabet.encode: invalid digit ${c}`);s[a]=d}return s8(s)},decode:i=>{Fa("decode",i);let s=i.length,a=new Uint8Array(s);for(let c=0;c<s;c++){let d=i.charCodeAt(c),f=d<128?o[d]:-1;if(f===-1)throw new Error(`Unknown letter "${i[c]}". Allowed: ${e}`);a[c]=f}return a}}}function a8(e,t="="){return Oy(e),Fa("padding",t),{encode(r){for(;r.length*e%8;)r+=t;return r},decode(r){Fa("decode",r);let n=r.length;if(n*e%8)throw new Error("padding: invalid length");for(;n>0&&r[n-1]===t;n--)if((n-1)*e%8===0)throw new Error("padding: excess padding");return r.slice(0,n)}}}var c8=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",d8=/[\t\n\f\r ]/,f8=(e,t)=>{Fa("base64",e);let r=t?"base64url":"base64";if(e.length>0&&d8.test(e))throw new Error("invalid base64");return Uint8Array.fromBase64(e,{alphabet:r,lastChunkHandling:"strict"})},u8=gd(()=>Cy(Uy(6),kp("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),a8(6)));var wd=gd(()=>c8?{encode(e){return Na(e),e.toBase64()},decode(e){return f8(e,!1)}}:u8);var Ny=gd(()=>Cy(Uy(6),kp("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"))),l8=656356768;var Ry=65536,p8=2048,m8=4096,h8=(e,t)=>({encode:r=>{Na(r);let n=r.length;if(n===0)return new Uint8Array(0);if(n>=Ry)throw new Error("invalid length");let o=0;for(;o<n-1&&r[o]===0;)o++;let i=Math.ceil(n/2),s=new Uint16Array(i),a=n&1;a&&(s[0]=r[0]);for(let m=a,h=a;m<n;m+=2,h++)s[h]=r[m]<<8|r[m+1];let c=[],d=0;for(;d<i;){let m=0;for(let h=d;h<i;h++){let y=m*65536+s[h],b=Math.floor(y/t);m=y-b*t,s[h]=b,b===0&&h===d&&d++}c.push(m)}let f=c.length-1,u=f*5;for(let m=c[f];u++,!(m<e);m=Math.floor(m/e));let l=new Uint8Array(o+u),p=l.length-1;for(let m=0;m<f;m++){let h=c[m];for(let y=0;y<5;y++)l[p--]=h%e,h=Math.floor(h/e)}for(let m=c[f];p>=o;m=Math.floor(m/e))l[p--]=m%e;return l},decode:r=>{Na(r);let n=r.length;if(n===0)return new Uint8Array(0);if(n>=Ry)throw new Error("invalid length");let o=0;for(;o<n-1&&r[o]===0;)o++;let i=new Uint16Array(Math.ceil(n*6/16)+1),s=0,a=0,c=n%5||5;for(;a<n;){let l=0,p=1;for(let h=a+c;a<h;a++){let y=r[a];if(y>=e)throw new Error(`invalid integer: ${y}`);l=l*e+y,p*=e}c=5;let m=l;for(let h=0;h<s;h++){let y=i[h]*p+m;m=Math.floor(y/65536),i[h]=y-m*65536}for(;m>0;m=Math.floor(m/65536))i[s++]=m%65536}let d=s===0?1:s*2-(i[s-1]<256?1:0),f=new Uint8Array(o+d),u=f.length-1;for(let l=0;l<s;l++){let p=i[l];f[u--]=p&255,u>=o&&(f[u--]=p>>8)}return f}}),y8=(e,t)=>{let r=kp(t);return{encode(n){if(Na(n),n.length>p8)throw new Error("invalid length");return r.encode(e.encode(n))},decode(n){if(Fa("baseN.decode",n),n.length>m8)throw new Error("invalid length");return e.decode(r.decode(n))}}},b8=h8(58,l8);var g8=e=>y8(b8,e),Ct=gd(()=>g8("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"));function at(e){let t=new Uint8Array(e.reduce((n,o)=>n+o.length,0)),r=0;for(let n of e)t.set(n,r),r+=n.length;return t}function xd(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function vd(e){return`0x${xd(e)}`}var Sd=BigInt(4294967295),Fy=BigInt(32);function w8(e,t=!1){return t?{h:Number(e&Sd),l:Number(e>>Fy&Sd)}:{h:Number(e>>Fy&Sd)|0,l:Number(e&Sd)|0}}function Ed(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=w8(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var x8=e=>e/2**32|0,v8=e=>e>>>0;function My(e,t,r,n){let o=x8(r),i=v8(r);e.setUint32(t,n?i:o,n),e.setUint32(t+4,n?o:i,n)}var Bp=(e,t,r)=>e>>>r,Pp=(e,t,r)=>e<<32-r|t>>>r,Wo=(e,t,r)=>e>>>r|t<<32-r,Zo=(e,t,r)=>e<<32-r|t>>>r,Ma=(e,t,r)=>e<<64-r|t>>>r-32,Ha=(e,t,r)=>e>>>r-32|t<<64-r;function Rr(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}var Hy=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),zy=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,$y=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Ly=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,Dy=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),qy=(e,t,r,n,o,i)=>t+r+n+o+i+(e/2**32|0)|0;function _d(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Ad=e=>e?`"${e}" `:"";function ut(e,t=""){if(typeof e!="number")throw new TypeError(Ad(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Ad(t)+"expected integer >= 0, got "+e);return e}function Vy(e,t=""){if(typeof e!="boolean")throw new TypeError(Ad(t)+"expected boolean, got type="+typeof e);return e}function St(e,t,r=""){if(_d(e)&&(t===void 0||e.length===t))return e;t!==void 0&&ut(t,"length");let n=_d(e),o=t!==void 0?` of length ${t}`:"",i=n?`length=${e.length}`:`type=${typeof e}`,s=Ad(r)+"expected Uint8Array"+o+", got "+i;throw n?new RangeError(s):new TypeError(s)}function Td(e){if(typeof e!="function"||typeof e.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(ut(e.outputLen),ut(e.blockLen),e.outputLen<1||e.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var E8=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},jy=(e,t)=>{E8(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function fn(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Di(e,t){St(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw new RangeError('"output" expected length >= '+r)}function Rp(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Or(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Id(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function fr(e,t){return e<<32-t|e>>>t}var _8=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function A8(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function T8(e){for(let t=0;t<e.length;t++)e[t]=A8(e[t]);return e}var Op=_8?e=>e:T8,Ky=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",I8=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function kd(e){if(St(e),Ky)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=I8[e[r]];return t}function Gy(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Bd(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(Ky)try{return Uint8Array.fromHex(e)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let t=e.length,r=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,i=0;o<r;o++,i+=2){let s=Gy(e.charCodeAt(i)),a=Gy(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function Cp(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];St(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let i=e[n];r.set(i,o),o+=i.length}return r}function Wy(e,t,r="opts"){return jy(e,"defaults"),t!==void 0&&jy(t,r),Object.assign(Object.create(null),e,t)}function za(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=Wy({},t,"info");let r=(o,i)=>e(i).update(o).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>e(o),Object.assign(r,t),Object.freeze(r)}function Zy(e=32){ut(e,"bytesLength");let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(e>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var $a=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Yy(e,t,r){return e&t^~e&r}function Xy(e,t,r){return e&t^e&r^t&r}var La=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,r,n,o){this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Id(this.buffer)}update(t){fn(this),St(t);let{view:r,buffer:n,blockLen:o}=this,i=t.length,s=!1;for(let a=0;a<i;){let c=Math.min(o-this.pos,i-a);if(c===o){let d=Id(t);for(;o<=i-a;a+=o)this.process(d,a);s=!0;continue}n.set(a===0&&c===i?t:t.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(r,0),this.pos=0,s=!0)}return this.length+=t.length,s&&this.roundClean(),this}digestInto(t){fn(this),Di(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;r[s++]=128,r.fill(0,s),this.padOffset>o-s&&(this.process(n,0),r.fill(0)),My(n,o-8,this.length*8,i),this.process(n,0),this.roundClean();let a=t===r?n:Id(t),c=this.outputLen,d=c/4,f=this.get();if(c%4||d>f.length)throw new Error("invalid outputLen");for(let u=0;u<d;u++)a.setUint32(4*u,f[u],i)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneIntoMeta(t){let{buffer:r,length:n,finished:o,destroyed:i,pos:s}=this;return t.destroyed=i,t.finished=o,t.length=n,t.pos=s,s&&t.buffer.set(r),t}clone(){return this._cloneInto()}},Jy=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Qy=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var k8=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Dn=new Uint32Array(64),Up=class extends La{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(t,r){super(64,t,8,!1),this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:t,B:r,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[t,r,n,o,i,s,a,c]}set(t,r,n,o,i,s,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,r){for(let u=0;u<16;u++,r+=4)Dn[u]=t.getUint32(r,!1);for(let u=16;u<64;u++){let l=Dn[u-15],p=Dn[u-2],m=fr(l,7)^fr(l,18)^l>>>3,h=fr(p,17)^fr(p,19)^p>>>10;Dn[u]=h+Dn[u-7]+m+Dn[u-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:d,H:f}=this;for(let u=0;u<64;u++){let l=fr(a,6)^fr(a,11)^fr(a,25),p=f+l+Yy(a,c,d)+k8[u]+Dn[u]|0,h=(fr(n,2)^fr(n,13)^fr(n,22))+Xy(n,o,i)|0;f=d,d=c,c=a,a=s+p|0,s=i,i=o,o=n,n=p+h|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,d=d+this.G|0,f=f+this.H|0,this.set(n,o,i,s,a,c,d,f)}roundClean(){Or(Dn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Or(this.buffer)}},Np=class extends Up{constructor(){super(32,Jy)}};var eb=Ed(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),B8=eb[0],P8=eb[1],qn=new Uint32Array(80),jn=new Uint32Array(80),Fp=class extends La{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(t,r){super(128,t,16,!1),this.Ah=r[0]|0,this.Al=r[1]|0,this.Bh=r[2]|0,this.Bl=r[3]|0,this.Ch=r[4]|0,this.Cl=r[5]|0,this.Dh=r[6]|0,this.Dl=r[7]|0,this.Eh=r[8]|0,this.El=r[9]|0,this.Fh=r[10]|0,this.Fl=r[11]|0,this.Gh=r[12]|0,this.Gl=r[13]|0,this.Hh=r[14]|0,this.Hl=r[15]|0}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:d,El:f,Fh:u,Fl:l,Gh:p,Gl:m,Hh:h,Hl:y}=this;return[t,r,n,o,i,s,a,c,d,f,u,l,p,m,h,y]}set(t,r,n,o,i,s,a,c,d,f,u,l,p,m,h,y){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=d|0,this.El=f|0,this.Fh=u|0,this.Fl=l|0,this.Gh=p|0,this.Gl=m|0,this.Hh=h|0,this.Hl=y|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,r){for(let g=0;g<16;g++,r+=4)qn[g]=t.getUint32(r),jn[g]=t.getUint32(r+=4);for(let g=16;g<80;g++){let w=qn[g-15]|0,v=jn[g-15]|0,E=Wo(w,v,1)^Wo(w,v,8)^Bp(w,v,7),B=Zo(w,v,1)^Zo(w,v,8)^Pp(w,v,7),N=qn[g-2]|0,U=jn[g-2]|0,R=Wo(N,U,19)^Ma(N,U,61)^Bp(N,U,6),T=Zo(N,U,19)^Ha(N,U,61)^Pp(N,U,6),O=$y(B,T,jn[g-7],jn[g-16]),H=Ly(O,E,R,qn[g-7],qn[g-16]);qn[g]=H|0,jn[g]=O|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:d,Dl:f,Eh:u,El:l,Fh:p,Fl:m,Gh:h,Gl:y,Hh:b,Hl:x}=this;for(let g=0;g<80;g++){let w=Wo(u,l,14)^Wo(u,l,18)^Ma(u,l,41),v=Zo(u,l,14)^Zo(u,l,18)^Ha(u,l,41),E=u&p^~u&h,B=l&m^~l&y,N=Dy(x,v,B,P8[g],jn[g]),U=qy(N,b,w,E,B8[g],qn[g]),R=N|0,T=Wo(n,o,28)^Ma(n,o,34)^Ma(n,o,39),O=Zo(n,o,28)^Ha(n,o,34)^Ha(n,o,39),H=n&i^n&a^i&a,P=o&s^o&c^s&c;b=h|0,x=y|0,h=p|0,y=m|0,p=u|0,m=l|0,{h:u,l}=Rr(d|0,f|0,U|0,R|0),d=a|0,f=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let _=Hy(R,O,P);n=zy(_,U,T,H),o=_|0}({h:n,l:o}=Rr(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=Rr(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Rr(this.Ch|0,this.Cl|0,a|0,c|0),{h:d,l:f}=Rr(this.Dh|0,this.Dl|0,d|0,f|0),{h:u,l}=Rr(this.Eh|0,this.El|0,u|0,l|0),{h:p,l:m}=Rr(this.Fh|0,this.Fl|0,p|0,m|0),{h,l:y}=Rr(this.Gh|0,this.Gl|0,h|0,y|0),{h:b,l:x}=Rr(this.Hh|0,this.Hl|0,b|0,x|0),this.set(n,o,i,s,a,c,d,f,u,l,p,m,h,y,b,x)}roundClean(){Or(qn,jn)}destroy(){this.destroyed=!0,Or(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Mp=class extends Fp{constructor(){super(64,Qy)}};var ur=za(()=>new Np,$a(1));var Hp=za(()=>new Mp,$a(3));var et=new TextEncoder,Et=(...e)=>at(e),Y=e=>vd(e);function G(e,t){if(typeof e!="string"||!new RegExp(`^0x[0-9a-f]{${t*2}}$`).test(e))throw new TypeError(`expected canonical ${t}-byte hex`);return Uint8Array.from(e.slice(2).match(/../g)??[],r=>Number.parseInt(r,16))}function _t(e,t){if(typeof e!="bigint"&&(typeof e!="string"||e.length>Math.ceil(t*Math.LOG10E*Math.LN2)||!/^(0|[1-9][0-9]*)$/.test(e)))throw new TypeError("expected canonical unsigned integer");let r=BigInt(e);if(r<0n||r>=1n<<BigInt(t))throw new RangeError(`expected u${t}`);return r}function je(e,t){if(typeof e=="number"&&!Number.isSafeInteger(e))throw new RangeError("expected integer");let r=_t(typeof e=="number"?BigInt(e):e,t*8);return Uint8Array.from({length:t},()=>{let n=Number(r&255n);return r>>=8n,n})}var At=e=>{let t=et.encode(e);return Et(je(t.length,4),t)},Pd=(e,t)=>Y(ur(Et(et.encode(e),new Uint8Array([0]),t)));function be(e){if(typeof e!="string"||!/^(?=.{2,64}$)[a-z0-9]+(?:[._-][a-z0-9]+)*$/.test(e))throw new TypeError("invalid NEAR account id");return e}function Gn(e){if(!["near:mainnet","near:testnet","near:sandbox"].includes(e))throw new TypeError("invalid NEAR network");return e}function ae(e,t){if(e===null||typeof e!="object"||Array.isArray(e)||Object.keys(e).length!==t.length||!t.every(r=>Object.hasOwn(e,r)))throw new TypeError("unexpected object fields")}var Cr=(e,t)=>{for(let r=0;r<Math.min(e.length,t.length);r++){let n=e[r]-t[r];if(n)return n}return e.length-t.length};function ct(e){let t=_t(e,128),r=t%1000000n;return`${t/1000000n}${r?`.${r.toString().padStart(6,"0").replace(/0+$/,"")}`:""}`}function Vn(e){if(typeof e=="number"&&!Number.isSafeInteger(e))throw new RangeError("deadline out of range");let t=_t(BigInt(e),64),r=t/86400n+719468n,n=r/146097n,o=r%146097n,i=(o-o/1460n+o/36524n-o/146096n)/365n,s=o-(365n*i+i/4n-i/100n),a=(5n*s+2n)/153n,c=s-(153n*a+2n)/5n+1n,d=a<10n?a+3n:a-9n,f=n*400n+i+(d<=2n?1n:0n),u=l=>l.toString().padStart(2,"0");return`${f.toString().padStart(4,"0")}-${u(d)}-${u(c)} ${u(t%86400n/3600n)}:${u(t/60n%60n)}:${u(t%60n)} UTC`}function Jt(e,t,r=()=>{}){if(!Array.isArray(e))throw new TypeError(`"${t}" expected array, got type=${typeof e}`);for(let n=0;n<e.length;n++)r(e[n],`${t}[${n}]`);return e}var se=(e,t,r)=>St(e,t,r),$p=ut;function tb(e,t=""){if(typeof e!="string"){let r=t&&`"${t}" `;throw new TypeError(r+"expected string, got type="+typeof e)}return e}function Kn(e,t="object"){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(t==="object"?"expected valid options object":`"${t}" expected object, got type=${typeof e}`);return e}function Yo(e,t){if(typeof e!="function")throw new TypeError(`"${t}" is invalid: expected function, got ${typeof e}`);return e}var Zn=kd,ke=(...e)=>Cp(...e),un=e=>Bd(e),Qt=_d,lr=e=>Zy(e),Rd=BigInt(0),zp=BigInt(1),R8=e=>e?`"${e}" `:"";function Ut(e,t=""){if(typeof e!="boolean")throw new TypeError(R8(t)+"expected boolean, got type="+typeof e);return e}function Od(e){if(typeof e=="bigint"){if(!Wn(e))throw new RangeError("positive bigint expected, got "+e)}else $p(e);return e}function _e(e,t=""){if(typeof e!="number"){let r=t&&`"${t}" `;throw new TypeError(r+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let r=t&&`"${t}" `;throw new RangeError(r+"expected safe integer, got "+e)}}function Da(e){let t=Od(e).toString(16);return t.length&1?"0"+t:t}function rb(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?Rd:BigInt("0x"+e)}function er(e){return rb(kd(e))}function Xo(e){return rb(kd(Ur(St(e)).reverse()))}function Yn(e,t){if(ut(t),t===0)throw new Error("zero output length is invalid");e=Od(e);let r=t*2,n=e.toString(16);if(n.length>r)throw new RangeError("number is too large");return Bd(n.padStart(r,"0"))}function Lp(e,t){return Yn(e,t).reverse()}function Ur(e){return Uint8Array.from(se(e))}function Cd(e){if(typeof e!="string")throw new TypeError("ascii string expected, got "+typeof e);return Uint8Array.from(e,(t,r)=>{let n=t.charCodeAt(0);if(t.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${e[r]}" with code ${n} at position ${r}`);return n})}function Wn(e){return typeof e=="bigint"&&Rd<=e}function Dp(e,t,r){return Wn(e)&&Wn(t)&&Wn(r)&&t<=e&&e<r}function Xn(e,t,r,n){if(!Dp(t,r,n))throw new RangeError("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function tr(e){if(e<Rd)throw new Error("expected non-negative bigint, got "+e);return e===Rd?0:e.toString(2).length}function nb(e,t){if(typeof e!="bigint")throw new TypeError('"n" expected bigint, got type='+typeof e);return _e(t,"pos"),e>>BigInt(t)&zp}var qa=e=>(_e(e,"n"),(zp<<BigInt(e))-zp);function ob(e,t,r){if(ut(e,"hashLen"),ut(t,"qByteLen"),typeof r!="function")throw new TypeError("hmacFn must be a function");let n=y=>new Uint8Array(y),o=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1e3,c=n(e),d=n(e),f=0,u=()=>{c.fill(1),d.fill(0),f=0},l=(...y)=>r(d,ke(c,...y)),p=(y=o)=>{d=l(i,y),c=l(),y.length!==0&&(d=l(s,y),c=l())},m=()=>{if(f++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,b=[];for(;y<t;){c=l();let x=c.slice();b.push(x),y+=c.length}return ke(...b)};return(y,b)=>{u(),p(y);let x;for(;(x=b(m()))===void 0;)p();return u(),x}}function Be(e,t={},r={},n="object"){Kn(e,n),Kn(t,"fields"),Kn(r,"optFields");function o(s,a,c){let d=n==="object"?`param "${String(s)}"`:`"${n}.${String(s)}"`,f=e[s];if(!Object.hasOwn(e,s)&&(c?f!==void 0:a!=="function"))throw new TypeError(`${d} is invalid: expected own property`);if(c&&f===void 0)return;let u=typeof f;if(u!==a||f===null)throw new TypeError(`${d} is invalid: expected ${a}, got ${u}`)}let i=(s,a)=>Object.entries(s).forEach(([c,d])=>o(c,d,a));i(t,!1),i(r,!0)}var pr=()=>{throw new Error("not implemented")};var He=BigInt(0),he=BigInt(1),Jn=BigInt(2),ab=BigInt(3),Nd=BigInt(4),cb=BigInt(5),O8=BigInt(7),db=BigInt(8),C8=BigInt(9),fb=BigInt(15),ub=BigInt(16),lb=BigInt("0x10000000000000000");function Ue(e,t){if(t<=He)throw new Error("mod: expected positive modulus, got "+t);let r=e%t;return r>=He?r:t+r}function pb(e,t,r){if(r<=he)throw new Error("pow: expected modulus > 1, got "+r);if(typeof t!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof t);if(t<He)throw new Error("invalid exponent, negatives unsupported");if(t===He)return he;if(t===he)return e;let n=e%r;if(n<He&&(n+=r),t<lb){let a=he;for(;t>He;)t&he&&(a=a*n%r),n=n*n%r,t>>=he;return a}let o=[];for(;t>He;)o.push(Number(t&fb)),t>>=Nd;let i=new Array(16);i[0]=he,i[1]=n;for(let a=2;a<16;a++)i[a]=i[a-1]*n%r;let s=i[o[o.length-1]];for(let a=o.length-2;a>=0;a--){s=s*s%r,s=s*s%r,s=s*s%r,s=s*s%r;let c=o[a];c!==0&&(s=s*i[c]%r)}return s}function Fe(e,t,r){if(r<=he)throw new Error("pow2: expected modulus > 1, got "+r);if(t<He)throw new Error("pow2: expected non-negative exponent, got "+t);let n=e;for(;t-- >He;)n*=n,n%=r;return n}function ib(e,t){if(e===He)throw new Error("invert: expected non-zero number");if(t<=he)throw new Error("invert: expected modulus > 1, got "+t);let r=Ue(e,t),n=t,o=He,i=he;for(;r!==He;){let a=n/r,c=n-r*a,d=o-i*a;n=r,r=c,o=i,i=d}if(n!==he)throw new Error("invert: does not exist");return Ue(o,t)}function mb(e,t){if(t<=he)throw new Error("invertCt: expected prime modulus > 1, got "+t);let r=Ue(e,t);if(r===He)throw new Error("invertCt: expected non-zero number");let n=pb(r,t-Jn,t);if(Ue(r*n,t)!==he)throw new Error("invertCt: does not exist");return n}function qp(e,t,r){let n=e;if(!n.eql(n.sqr(t),r))throw new Error("Cannot find square root")}function jp(e,t){if((e&he)===He)throw new Error(t+": expected odd modulus, got "+e)}function hb(e,t){let r=e,n=(r.ORDER+he)/Nd,o=r.pow(t,n);return qp(r,o,t),o}function U8(e,t){let r=e,n=(r.ORDER-cb)/db,o=r.mul(t,Jn),i=r.pow(o,n),s=r.mul(t,i),a=r.mul(r.mul(s,Jn),i),c=r.mul(s,r.sub(a,r.ONE));return qp(r,c,t),c}function N8(e){let t=Nr(e),r=yb(e),n=r(t,t.neg(t.ONE)),o=r(t,n),i=r(t,t.neg(n)),s=(e+O8)/ub;return((a,c)=>{let d=a,f=d.pow(c,s),u=d.mul(f,n),l=d.mul(f,o),p=d.mul(f,i),m=d.eql(d.sqr(u),c),h=d.eql(d.sqr(l),c);f=d.cmov(f,u,m),u=d.cmov(p,l,h);let y=d.eql(d.sqr(u),c),b=d.cmov(f,u,y);return qp(d,b,c),b})}function yb(e){if(e<ab)throw new Error("sqrt is not defined for small field");jp(e,"tonelliShanks");let t=e-he,r=0;for(;t%Jn===He;)t/=Jn,r++;let n=Jn,o=Nr(e);for(;ln(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return hb;let i=o.pow(n,t),s=(t+he)/Jn;return function(c,d){let f=c;if(f.is0(d))return d;if(ln(f,d)!==1)throw new Error("Cannot find square root");let u=r,l=f.mul(f.ONE,i),p=f.pow(d,t),m=f.pow(d,s);for(;!f.eql(p,f.ONE);){if(f.is0(p))throw new Error("Cannot find square root: probably non-prime P");let h=1,y=f.sqr(p);for(;!f.eql(y,f.ONE);)if(h++,y=f.sqr(y),h===u)throw new Error("Cannot find square root");let b=he<<BigInt(u-h-1),x=f.pow(l,b);u=h,l=f.sqr(x),p=f.mul(p,l),m=f.mul(m,x)}return m}}function F8(e){return jp(e,"Fp.sqrt"),e%Nd===ab?hb:e%db===cb?U8:e%ub===C8?N8(e):yb(e)}var bb=(e,t)=>(Ue(e,t)&he)===he,M8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Nt(e){if(Kn(e,"field"),typeof e.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof e.ORDER);_e(e.BYTES,"BYTES"),_e(e.BITS,"BITS");for(let t of M8)Yo(e[t],"field."+t);if(e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=he)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function Fd(e,t,r){Nt(e);let n=e;if(typeof r!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof r);if(r<He)throw new Error("invalid exponent, negatives unsupported");if(r===He)return n.ONE;if(r===he)return t;if(r<lb){let a=n.ONE,c=t;for(;r>He;)r&he&&(a=n.mul(a,c)),c=n.sqr(c),r>>=he;return a}let o=[];for(;r>He;)o.push(Number(r&fb)),r>>=Nd;let i=new Array(16);i[0]=n.ONE,i[1]=t;for(let a=2;a<16;a++)i[a]=n.mul(i[a-1],t);let s=i[o[o.length-1]];for(let a=o.length-2;a>=0;a--){s=n.sqr(n.sqr(n.sqr(n.sqr(s))));let c=o[a];c!==0&&(s=n.mul(s,i[c]))}return s}function mr(e,t,r=!1){Nt(e),Jt(t,"nums"),Ut(r,"passZero");let n=e,o=new Array(t.length).fill(r?n.ZERO:void 0),i=t.reduce((a,c,d)=>n.is0(c)?a:(o[d]=a,n.mul(a,c)),n.ONE),s=n.inv(i);return t.reduceRight((a,c,d)=>n.is0(c)?a:(o[d]=n.mul(a,o[d]),n.mul(a,c)),s),o}function ln(e,t){Nt(e);let r=e;jp(r.ORDER,"FpLegendre");let n=(r.ORDER-he)/Jn,o=r.pow(t,n),i=r.eql(o,r.ONE),s=r.eql(o,r.ZERO),a=r.eql(o,r.neg(r.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Gp(e,t){return ln(e,t)!==-1}function H8(e,t){if(t!==void 0&&$p(t),e<=He)throw new Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);let r=tr(e);if(t!==void 0&&t<r)throw new Error(`invalid n length: expected nBitLength (${t}) >= bitLen(n) (${r})`);let n=t!==void 0?t:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var sb=new WeakMap,Ud=class{ORDER;BITS;BYTES;isLE;ZERO=He;ONE=he;_lengths;_mod;constructor(t,r={}){if(t<=he)throw new Error("invalid field: expected ORDER > 1, got "+t);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:o,nByteLength:i}=H8(t,n);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=i,Object.freeze(this)}create(t){return Ue(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return He<=t&&t<this.ORDER}is0(t){return t===He}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&he)===he}neg(t){return Ue(-t,this.ORDER)}eql(t,r){return t===r}sqr(t){return Ue(t*t,this.ORDER)}add(t,r){return Ue(t+r,this.ORDER)}sub(t,r){return Ue(t-r,this.ORDER)}mul(t,r){return Ue(t*r,this.ORDER)}pow(t,r){return pb(t,r,this.ORDER)}div(t,r){return Ue(t*ib(r,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,r){return t+r}subN(t,r){return t-r}mulN(t,r){return t*r}inv(t){return ib(t,this.ORDER)}sqrt(t){let r=sb.get(this);return r||sb.set(this,r=F8(this.ORDER)),r(this,t)}toBytes(t){return this.isLE?Lp(t,this.BYTES):Yn(t,this.BYTES)}fromBytes(t,r=!1){se(t);let{_lengths:n,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(n){if(t.length<1||!n.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let d=new Uint8Array(o);d.set(t,i?0:d.length-t.length),t=d}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=i?Xo(t):er(t);if(a&&(c=Ue(c,s)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return mr(this,t,!0)}cmov(t,r,n){return Ut(n,"condition"),n?r:t}};function Nr(e,t={}){return Object.freeze(Ud.prototype),new Ud(e,t)}function gb(e){if(typeof e!="bigint")throw new Error("field order must be bigint");if(e<=he)throw new Error("field order must be greater than 1");let t=tr(e-he);return Math.ceil(t/8)}function qi(e){let t=gb(e);return t+Math.ceil(t/2)}function ji(e,t,r=!1){se(e);let n=e.length,o=gb(t),i=Math.max(qi(t),16);if(n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=r?Xo(e):er(e),a=Ue(s,t-he)+he;return r?Lp(a,o):Yn(a,o)}var Wp=BigInt(0),ja=BigInt(1),$8=BigInt(4),Vp=16,wb=128,L8=5,xb=2**31;function Fr(e){let t=e;if(typeof t!="function")throw new TypeError('"Point" expected constructor, got type='+typeof e);Yo(t.fromAffine,"Point.fromAffine"),Yo(t.fromBytes,"Point.fromBytes"),Yo(t.fromHex,"Point.fromHex"),Kn(t.BASE,"Point.BASE"),Kn(t.ZERO,"Point.ZERO"),Nt(t.Fp),Nt(t.Fn)}function Md(e,t){Fr(e),Sb(t,e);let r=mr(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function D8(e,t,r=1){if(!Number.isSafeInteger(e)||e<r||e>t)throw new Error("invalid window size, expected ["+r+".."+t+"], got W="+e)}function q8(e,t){let r=e*(4*t+128);if(r>xb)throw new Error("invalid window size: table would need ~"+Math.ceil(r/2**20)+" MiB, max "+xb/2**20+" MiB")}function Zp(e,t){if(e!==void 0){Yo(e,"randomBytes");try{let r=e(t);if(!Qt(r)||r.length!==t)return}catch{return}return e}}function Sb(e,t){Jt(e,"points"),e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function j8(e,t,r){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((n,o)=>{if(!(r===void 0?t.isValid(n):Wn(n)&&n<r))throw new Error("invalid scalar at index "+o)})}var Eb=new WeakMap;function Kp(e){return Eb.get(e)||1}function G8(e,t){let r=e.double(),n=[e];for(let o=1;o<t;o++)n.push(n[o-1].add(r));return n}function V8(e,t){let r=2**t,n=r/2,o=BigInt(r-1),i=[];for(;e>Wp;){let s=0;e&ja&&(s=Number(e&o),s>=n&&(s-=r),e-=BigInt(s)),i.push(s),e>>=ja}return i}function K8(e,t,r){let n=2**t,o=n/2,i=BigInt(n-1),s=BigInt(t),a=[];for(let c=0;c<r;c++){let d=Number(e&i);e>>=s,d>o&&(d-=n,e+=ja),a.push(d)}if(e!==Wp)throw new Error("invalid wnaf");return a}function W8(e,t,r){let n=0;for(let i of r)n=Math.max(n,i.length);let o=e;for(let i=n-1;i>=0;i--){i!==n-1&&(o=o.double());for(let s=0;s<r.length;s++){let a=r[s][i];if(a){let c=t[s][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}var Gi=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(t,r){Fr(t),this.randomBytes=Zp(r,Vp),this.Point=t,this.BASE=t.BASE,this.ZERO=t.ZERO,this.bits=t.Fn.BITS}buildWnafTable(t,r,n){let o=Math.ceil(n/r)+1,i=2**(r-1),s=[],a=t;for(let c=0;c<o;c++){let d=a;for(let f=0;f<i;f++)s.push(d),d=d.add(a);a=s[s.length-1].double()}return{W:r,bits:n,windows:o,comp:s}}wnafCachedCT(t,r){let{W:n,windows:o,comp:i}=t,s=2**(n-1),a=K8(r,n,o),c=this.ZERO,d=this.BASE;for(let f=0;f<o;f++){let u=a[f],l=f*s,p=Math.abs(u)-1,m=i[l];for(let y=1;y<s;y++)m=y===p?i[l+y]:m;let h=m.negate();u===0?d=d.add(i[l]):c=c.add(u<0?h:m)}return{p:c,f:d}}getWnafPrecomputes(t,r,n,o){let i=this.wnafPrecomputes.get(r),s=i?.find(a=>a.W===t&&a.bits===n);return s||(s=this.buildWnafTable(r,t,n),typeof o=="function"&&(s={...s,comp:o(s.comp)}),i||(i=[],this.wnafPrecomputes.set(r,i)),i.push(s)),s}assertPoint(t){if(!(t instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof t)}validateMulInput(t,r){if(this.assertPoint(t),!Dp(r,ja,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(t,r,n,o){let i=Kp(t);return i===1?this.fixedWindowCT(t,r,n):this.wnafCachedCT(this.getWnafPrecomputes(i,t,n,o),r)}mulCT(t,r,n){return this.validateMulInput(t,r),this.runCT(t,r,this.bits,n)}mulCTBlinded(t,r,n){if(this.validateMulInput(t,r),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+wb,i=this.randomBytes(Vp);if(!Qt(i)||i.length!==Vp)throw new Error("randomBytes returned invalid byte array");i[0]=i[0]&63|128;let s=r+er(i)*this.Point.Fn.ORDER;return this.runCT(t,s,o,n)}fixedWindowCT(t,r,n){let o=L8,i=1<<o,s=qa(o),a=new Array(i);a[0]=this.ZERO;for(let f=1;f<i;f++)a[f]=a[f-1].add(t);let c=Math.ceil(n/o),d=this.ZERO;for(let f=c-1;f>=0;f--){if(f!==c-1)for(let p=0;p<o;p++)d=d.double();let u=Number(r>>BigInt(f*o)&s),l=a[0];for(let p=1;p<i;p++)l=p===u?a[p]:l;d=d.add(l)}return{p:d,f:d}}shouldBlind(t,r){return this.randomBytes===void 0?!1:r===ja?!0:t!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(t,r,n,o){return this.shouldBlind(t,n)?this.mulCTBlinded(t,r,o):this.mulCT(t,r,o)}mulUnsafe(t,r,n){if(this.assertPoint(t),!Wn(r))throw new Error("invalid scalar");let o=Kp(t);if(o===1||r>=this.Point.Fn.ORDER)return Hd(this.Point,[t],[r],!0);let i=this.getWnafPrecomputes(o,t,this.bits,n);return this.wnafCachedCT(i,r).p}setWindowSize(t,r){this.assertPoint(t),D8(r,this.bits);let n=Math.ceil((this.bits+wb)/r)+1;q8(n*2**(r-1),this.Point.Fp.BYTES),Eb.set(t,r),this.wnafPrecomputes.delete(t)}hasWindowSize(t){return Kp(t)!==1}};function Hd(e,t,r,n=!1){if(Fr(e),Sb(t,e),Ut(n,"allowOversized"),j8(r,e.Fn,n?e.Fn.ORDER**$8:void 0),t.length!==r.length)throw new Error("arrays of points and scalars must have equal length");let o=t.map(s=>G8(s,4)),i=r.map(s=>V8(s,4));return W8(e.ZERO,o,i)}function vb(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Nt(t),t}else return Nr(e,{isLE:r})}function zd(e,t,r={},n){if(e!=="weierstrass"&&e!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);Be(r);for(let c of["p","n","h"]){let d=t[c];if(!(Wn(d)&&d!==Wp))throw new Error(`CURVE.${c} must be positive bigint`)}let o=vb(t.p,r.Fp,n),i=vb(t.n,r.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}function $d(e,t){return function(n){let o=e(n);return{secretKey:o,publicKey:t(o)}}}var Ld=BigInt(0),Dd=BigInt(1),qd=BigInt(2),Z8=BigInt(4),_b=BigInt(8);function Y8(e,t,r,n){let o=e.sqr(r),i=e.sqr(n),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function Ab(e,t={}){Be(t,{},{},"extraOpts");let r=t,n=zd("edwards",e,r,r.FpFnLE),{Fp:o,Fn:i}=n,s=n.CURVE,{h:a}=s;if(ln(o,s.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(ln(o,s.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Be(r,{},{uvRatio:"function",randomBytes:"function"});let c=r.randomBytes===void 0?lr:r.randomBytes,d=qd<<BigInt(o.BYTES*8)-Dd;function f(x){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(x)}let u=r.uvRatio===void 0?(x,g)=>{try{return{isValid:!0,value:o.sqrt(o.div(x,g))}}catch{return{isValid:!1,value:Ld}}}:r.uvRatio;if(!Y8(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");let l=o.eql(s.a,o.neg(o.ONE))?x=>o.neg(x):o.eql(s.a,o.ONE)?x=>x:x=>o.mul(s.a,x);function p(x,g,w=!1){let v=w?Dd:Ld;return Xn("coordinate "+x,g,v,d),g}function m(x){if(!(x instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(s.Gx,s.Gy,o.ONE,o.mul(s.Gx,s.Gy));static ZERO=new h(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=i;X;Y;Z;T;constructor(g,w,v,E){this.X=p("x",g),this.Y=p("y",w),this.Z=p("z",v,!0),this.T=p("t",E),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){if(g instanceof h)throw new Error("extended point not allowed");let{x:w,y:v}=g||{};return p("x",w),p("y",v),new h(w,v,o.ONE,o.mul(w,v))}static fromBytes(g,w=!1){let v=o.BYTES,{a:E,d:B}=s;g=Ur(se(g,v,"point")),Ut(w,"zip215");let N=Ur(g),U=g[v-1];N[v-1]=U&-129;let R=Xo(N),T=w?d:o.ORDER;Xn("point.y",R,Ld,T);let O=o.sqr(R),H=o.sub(O,o.ONE),P=o.sub(o.mulN(B,O),E),{isValid:_,value:I}=u(H,P);if(!_)throw new Error("bad point: invalid y coordinate");let k=f(I),M=(U&128)!==0;if(!w&&o.is0(I)&&M)throw new Error("bad point: x=0 and x_0=1");return M!==k&&(I=o.neg(I)),h.fromAffine({x:I,y:R})}static fromHex(g,w=!1){return h.fromBytes(un(g),w)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=6,w=!0){return b.setWindowSize(this,g),w||this.multiply(qd),this}assertValidity(){let g=this,{a:w,d:v}=s;if(g.is0())throw new Error("bad point: ZERO");let{X:E,Y:B,Z:N,T:U}=g,R=o.sqr(E),T=o.sqr(B),O=o.sqr(N),H=o.sqr(O),P=o.mul(R,w),_=o.mul(o.add(P,T),O),I=o.add(H,o.mul(v,o.mul(R,T)));if(!o.eql(_,I))throw new Error("bad point: equation left != right (1)");let k=o.mul(E,B),M=o.mul(N,U);if(!o.eql(k,M))throw new Error("bad point: equation left != right (2)")}equals(g){m(g);let{X:w,Y:v,Z:E}=this,{X:B,Y:N,Z:U}=g,R=o.mul(w,U),T=o.mul(B,E),O=o.mul(v,U),H=o.mul(N,E);return o.eql(R,T)&&o.eql(O,H)}is0(){return this.equals(h.ZERO)}negate(){return new h(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:g,Y:w,Z:v}=this,E=o.sqr(g),B=o.sqr(w),N=o.mul(o.sqr(v),qd),U=l(E),R=o.addN(g,w),T=o.sub(o.subN(o.sqr(R),E),B),O=o.addN(U,B),H=o.subN(O,N),P=o.subN(U,B),_=o.mul(T,H),I=o.mul(O,P),k=o.mul(T,P),M=o.mul(H,O);return new h(_,I,M,k)}add(g){m(g);let{d:w}=s,{X:v,Y:E,Z:B,T:N}=this,{X:U,Y:R,Z:T,T:O}=g,H=o.mul(v,U),P=o.mul(E,R),_=o.mul(o.mulN(N,w),O),I=o.mul(B,T),k=o.sub(o.subN(o.mulN(o.addN(v,E),o.addN(U,R)),H),P),M=o.subN(I,_),$=o.addN(I,_),F=o.sub(P,l(H)),A=o.mul(k,M),z=o.mul($,F),D=o.mul(k,F),q=o.mul(M,$);return new h(A,z,q,D)}subtract(g){return m(g),this.add(g.negate())}multiply(g){if(!i.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:w,f:v}=b.mulSecret(this,g,a,y);return y([w,v])[0]}multiplyUnsafe(g){if(!i.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===Ld?h.ZERO:this.is0()||g===Dd?this:b.mulUnsafe(this,g,y)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return b.mulUnsafe(this,s.n).is0()}toAffine(g){let w=this,v=g;if(v!=null&&typeof v!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof v);let{X:E,Y:B,Z:N}=w,U=w.is0();v==null&&(v=U?o.create(_b):o.inv(N));let R=o.mul(E,v),T=o.mul(B,v),O=o.mul(N,v);if(U)return{x:o.ZERO,y:o.ONE};if(!o.eql(O,o.ONE))throw new Error("invZ was invalid");return{x:R,y:T}}clearCofactor(){return a===Dd?this:a===qd?this.double():a===Z8?this.double().double():a===_b?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:g,y:w}=this.toAffine(),v=o.toBytes(w);return v[v.length-1]|=f(g)?128:0,v}toHex(){return Zn(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let y=x=>Md(h,x),b=new Gi(h,c);return b.bits>=6&&h.BASE.precompute(6),Object.freeze(h.prototype),Object.freeze(h),h}function Tb(e,t,r={}){if(Fr(e),typeof t!="function")throw new Error('"hash" function param is required');let n=t,o=r;Be(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=e,d=n.outputLen,f=2*a.BYTES;if(d!==void 0&&(_e(d,"hash.outputLen"),d!==f))throw new Error(`hash.outputLen must be ${f}, got ${d}`);let u=o.randomBytes===void 0?lr:o.randomBytes,l=o.toMontgomery,p=o.toMontgomerySecret,m=o.adjustScalarBytes===void 0?P=>P:o.adjustScalarBytes,h=o.domain===void 0?(P,_,I)=>{if(Ut(I,"phflag"),_.length||I)throw new Error("Contexts/pre-hash are not supported");return P}:o.domain;function y(P){return c.create(Xo(P))}function b(P){let _=U.secretKey;se(P,U.secretKey,"secretKey");let I=se(n(P),2*_,"hashedSecretKey"),k=m(I.slice(0,_)),M=I.slice(_,2*_),$=y(k);return{head:k,prefix:M,scalar:$}}function x(P){let{head:_,prefix:I,scalar:k}=b(P),M=s.multiply(k),$=M.toBytes();return{head:_,prefix:I,scalar:k,point:M,pointBytes:$}}function g(P){return x(P).pointBytes}function w(P=Uint8Array.of(),..._){let I=ke(..._);return y(n(h(I,se(P,void 0,"context"),!!i)))}function v(P,_,I={}){Be(I,{},{},"options"),P=Ur(se(P,void 0,"message")),i&&(P=i(P));let{prefix:k,scalar:M,pointBytes:$}=x(_),F=w(I.context,k,P),A=s.multiply(F).toBytes(),z=w(I.context,A,$,P),D=c.create(F+z*M);if(!c.isValid(D))throw new Error("sign failed: invalid s");let q=ke(A,c.toBytes(D));return se(q,U.signature,"result")}let E={zip215:o.zip215};function B(P,_,I,k=E){Be(k);let{context:M}=k,$=k.zip215===void 0?!!E.zip215:k.zip215,F=U.signature;P=se(P,F,"signature"),_=se(_,void 0,"message"),I=se(I,U.publicKey,"publicKey"),$!==void 0&&Ut($,"zip215"),i&&(_=i(_));let A=F/2,z=P.subarray(0,A),D=Xo(P.subarray(A,F)),q,j,K;try{q=e.fromBytes(I,$),j=e.fromBytes(z,$),K=s.multiplyUnsafe(D)}catch{return!1}if(!$&&q.isSmallOrder())return!1;let W=w(M,z,I,_);return j.add(q.multiplyUnsafe(W)).subtract(K).clearCofactor().is0()}let N=a.BYTES,U={secretKey:N,publicKey:N,signature:2*N,seed:N};function R(P){return P=P===void 0?u(U.seed):P,se(P,U.seed,"seed")}function T(P){return Qt(P)&&P.length===U.secretKey}function O(P,_){try{return!!e.fromBytes(P,_===void 0?E.zip215:_)}catch{return!1}}let H={getExtendedPublicKey:x,randomSecretKey:R,isValidSecretKey:T,isValidPublicKey:O,toMontgomery(P){if(l===void 0)throw new Error("Montgomery conversion is not supported for this curve");return l(e.fromBytes(P))},toMontgomerySecret(P){if(p===void 0)throw new Error("Montgomery conversion is not supported for this curve");return p(P)}};return Object.freeze(U),Object.freeze(H),Object.freeze({keygen:$d(R,g),getPublicKey:g,sign:v,verify:B,utils:H,Point:e,lengths:U})}var Ib=BigInt(0),Mr=BigInt(1),Qn=BigInt(2),kb=BigInt(3),Bb=BigInt(4),X8=er;function Jo(e,t){if(_e(e),_e(t),t<0||t>4)throw new Error("invalid I2OSP length: "+t);if(e<0||e>2**(8*t)-1)throw new Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let n=t-1;n>=0;n--)r[n]=e&255,e>>>=8;return new Uint8Array(r)}function J8(e,t){let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e[n]^t[n];return r}function Pb(e){if(!Qt(e)&&typeof e!="string")throw new Error("DST must be Uint8Array or ascii string");let t=typeof e=="string"?Cd(e):e;if(t.length===0)throw new Error("DST must be non-empty");return t}function Q8(e,t,r,n){if(se(e),_e(r),typeof n!="function")throw new Error("expand_message_xmd: expected hash function");_e(n.outputLen,"hash.outputLen"),_e(n.blockLen,"hash.blockLen"),t=Pb(t),t.length>255&&(t=n(ke(Cd("H2C-OVERSIZE-DST-"),t)));let{outputLen:o,blockLen:i}=n,s=Math.ceil(r/o);if(r>65535||s>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=ke(t,Jo(t.length,1)),c=new Uint8Array(i),d=Jo(r,2),f=new Array(s),u=n(ke(c,e,d,Jo(0,1),a));f[0]=n(ke(u,Jo(1,1),a));for(let p=1;p<s;p++){let m=[J8(u,f[p-1]),Jo(p+1,1),a];f[p]=n(ke(...m))}return ke(...f).slice(0,r)}function ev(e,t,r,n,o){if(se(e),_e(r),_e(n,"k"),n<0)throw new Error("expand_message_xof: invalid k");if(typeof o!="function")throw new Error("expand_message_xof: expected XOF function");if(typeof o.create!="function")throw new Error("expand_message_xof: expected XOF create");if(t=Pb(t),r<0||r>65535)throw new Error("expand_message_xof: invalid lenInBytes");if(t.length>255){let i=Math.ceil(2*n/8);t=o.create({dkLen:i}).update(Cd("H2C-OVERSIZE-DST-")).update(t).digest()}if(t.length>255)throw new Error("expand_message_xof: invalid DST");return o.create({dkLen:r}).update(e).update(Jo(r,2)).update(t).update(Jo(t.length,1)).digest()}function Yp(e,t,r){Be(r,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:n,k:o,m:i,hash:s,expand:a,DST:c}=r;if(_e(s.outputLen,"valid hash"),se(e),_e(t),_e(i,"m"),_e(o,"k"),n<=BigInt(1))throw new Error("hash_to_field: expected valid field characteristic");if(t<1)throw new Error("hash_to_field: expected count >= 1");if(i<1)throw new Error("hash_to_field: expected m >= 1");if(o<0)throw new Error("hash_to_field: invalid k");let d=n.toString(2).length,f=Math.ceil((d+o)/8),u=t*i*f,l;if(a==="xmd")l=Q8(e,c,u,s);else if(a==="xof")l=ev(e,c,u,o,s);else if(a==="_internal_pass")l=e;else throw new Error('expand must be "xmd" or "xof"');let p=new Array(t);for(let m=0;m<t;m++){let h=new Array(i);for(let y=0;y<i;y++){let b=f*(y+m*i),x=l.subarray(b,b+f);h[y]=Ue(X8(x),n)}p[m]=h}return p}function Xp(e,t){Nt(e),Jt(t,"map");let r=t.map((n,o)=>{if(Jt(n,"map["+o+"]"),n.length<1)throw new Error("isogenyMap: expected non-empty coefficients");return Array.from(n).reverse()});return(n,o)=>{let[i,s,a,c]=r.map(l=>l.reduce((p,m)=>e.add(e.mul(p,n),m))),d=e.is0(s)||e.is0(c),[f,u]=mr(e,[s,c],!0);return n=e.mul(i,f),o=e.mul(o,e.mul(a,u)),d?{x:e.ZERO,y:e.ZERO}:{x:n,y:o}}}var tv="HashToScalar-";function Jp(e,t,r){if(typeof t!="function")throw new Error("mapToCurve() must be defined");Be(r);let n=c=>Object.freeze({...c,DST:Qt(c.DST)?Ur(c.DST):c.DST,...c.encodeDST===void 0?{}:{encodeDST:Qt(c.encodeDST)?Ur(c.encodeDST):c.encodeDST}}),o=n(r),i=c=>c&&c.DST!==void 0?{DST:c.DST}:void 0;function s(c){return e.fromAffine(t(c))}function a(c){let d=c.clearCofactor();return d.equals(e.ZERO)?e.ZERO:(d.assertValidity(),d)}return Object.freeze({get defaults(){return n(o)},Point:e,hashToCurve(c,d){let f=Object.assign({},o,i(d)),u=Yp(c,2,f),l=s(u[0]),p=s(u[1]);return a(l.add(p))},encodeToCurve(c,d){let f=o.encodeDST===void 0?{}:{DST:o.encodeDST},u=Object.assign({},o,f,i(d)),l=Yp(c,1,u),p=s(l[0]);return a(p)},mapToCurve(c){if(o.m===1){if(typeof c!="bigint")throw new Error("expected bigint (m=1)");return a(s([c]))}if(!Array.isArray(c))throw new Error("expected array of bigints");if(c.length!==o.m)throw new Error(`expected array of ${o.m} bigints`);for(let d of c)if(typeof d!="bigint")throw new Error("expected array of bigints");return a(s(c))},hashToScalar(c,d){let f=e.Fn.ORDER,u=Object.assign({},o,{DST:tv},i(d),{p:f,m:1});return Yp(c,1,u)[0][0]}})}function rv(e,t){let r=Nt(e),n=r.ORDER,o=Ib;for(let h=n-Mr;h%Qn===Ib;h/=Qn)o+=Mr;let i=o,s=Qn<<i-Mr-Mr,a=s*Qn,c=(n-Mr)/a,d=(c-Mr)/Qn,f=a-Mr,u=s,l=r.pow(t,c),p=r.pow(t,(c+Mr)/Qn),m=(h,y)=>{let b=l,x=r.pow(y,f),g=r.sqr(x);g=r.mul(g,y);let w=r.mul(h,g);w=r.pow(w,d),w=r.mul(w,x),x=r.mul(w,y),g=r.mul(w,h);let v=r.mul(g,x);w=r.pow(v,u);let E=r.eql(w,r.ONE);x=r.mul(g,p),w=r.mul(v,b),g=r.cmov(x,g,E),v=r.cmov(w,v,E);for(let B=i;B>Mr;B--){let N=B-Qn;N=Qn<<N-Mr;let U=r.pow(v,N),R=r.eql(U,r.ONE);x=r.mul(g,b),b=r.mul(b,b),U=r.mul(v,b),g=r.cmov(x,g,R),v=r.cmov(U,v,R)}return{isValid:!r.is0(y)&&(E||r.is0(h)),value:g}};if(r.ORDER%Bb===kb){let h=(r.ORDER-kb)/Bb,y=r.sqrt(r.neg(t));m=(b,x)=>{let g=r.sqr(x),w=r.mul(b,x);g=r.mul(g,w);let v=r.pow(g,h);v=r.mul(v,w);let E=r.mul(v,y),B=r.mul(r.sqr(v),x),N=r.eql(B,b),U=r.cmov(E,v,N);return{isValid:!r.is0(x)&&N,value:U}}}return m}function Qp(e,t){let r=Nt(e);Be(t,{},{},"opts");let{A:n,B:o,Z:i}=t;if(!r.isValidNot0(n)||!r.isValidNot0(o)||!r.isValid(i))throw new Error("mapToCurveSimpleSWU: invalid opts");if(r.eql(i,r.neg(r.ONE))||Gp(r,i))throw new Error("mapToCurveSimpleSWU: invalid opts");let s=r.mul(o,r.inv(r.mul(i,n))),a=r.add(r.add(r.mul(r.sqr(s),s),r.mul(n,s)),o);if(!Gp(r,a))throw new Error("mapToCurveSimpleSWU: invalid opts");let c=rv(r,i);if(!r.isOdd)throw new Error("Field does not have .isOdd()");return d=>{let f,u,l,p,m,h,y,b;f=r.sqr(d),f=r.mul(f,i),u=r.sqr(f),u=r.add(u,f),l=r.add(u,r.ONE),l=r.mul(l,o),p=r.cmov(i,r.neg(u),!r.eql(u,r.ZERO)),p=r.mul(p,n),u=r.sqr(l),h=r.sqr(p),m=r.mul(h,n),u=r.add(u,m),u=r.mul(u,l),h=r.mul(h,p),m=r.mul(h,o),u=r.add(u,m),y=r.mul(f,l);let{isValid:x,value:g}=c(u,h);b=r.mul(f,d),b=r.mul(b,g),y=r.cmov(y,l,x),b=r.cmov(b,g,x);let w=r.isOdd(d)===r.isOdd(b);b=r.cmov(r.neg(b),b,w);let v=mr(r,[p],!0)[0];return y=r.mul(y,v),{x:y,y:b}}}var e0=BigInt(1),Rb=BigInt(2);var nv=BigInt(5),ov=BigInt(8),t0=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),iv={p:t0,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ov,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function sv(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=t0,a=e*e%i*e%i,c=Fe(a,Rb,i)*a%i,d=Fe(c,e0,i)*e%i,f=Fe(d,nv,i)*d%i,u=Fe(f,t,i)*f%i,l=Fe(u,r,i)*u%i,p=Fe(l,n,i)*l%i,m=Fe(p,o,i)*p%i,h=Fe(m,o,i)*p%i,y=Fe(h,t,i)*f%i;return{pow_p_5_8:Fe(y,Rb,i)*e%i,b2:a}}function Ub(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var Ob=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function av(e,t){let r=t0,n=Ue(t*t*t,r),o=Ue(n*n*t,r),i=sv(e*o).pow_p_5_8,s=Ue(e*n*i,r),a=Ue(t*s*s,r),c=s,d=Ue(s*Ob,r),f=a===e,u=a===Ue(-e,r),l=a===Ue(-e*Ob,r);return f&&(s=c),(u||l)&&(s=d),bb(s,r)&&(s=Ue(-s,r)),{isValid:f||u,value:s}}var r0=Ab(iv,{uvRatio:av}),Cb=r0.Fp;function cv(e){let{y:t}=e;return Cb.toBytes(Cb.div(e0+t,e0-t))}function dv(e){let t=r0.Fp.BYTES;return St(e,t),Ub(Hp(e.subarray(0,t))).subarray(0,t)}function fv(e){return Tb(r0,Hp,Object.assign({adjustScalarBytes:Ub,toMontgomery:cv,toMontgomerySecret:dv,zip215:!0},e))}var jd=fv({});var Gd=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(t,r){if(Td(t),St(r,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?t.create().update(r).digest():r);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=t.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Or(o)}update(t){return fn(this),this.iHash.update(t),this}digestInto(t){fn(this),Di(t,this),this.finished=!0;let r=t.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a,canXOF:c}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.canXOF=c,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Nb=(()=>{let e=((t,r,n)=>new Gd(t,r).update(n).digest());return e.create=(t,r)=>new Gd(t,r),e})();var uv=BigInt(0),n0=class extends Error{constructor(t=""){super(t)}},pn={Err:n0,_tlv:{encode:(e,t)=>{let{Err:r}=pn;if(_e(e,"tag"),e<0||e>255)throw new r("tlv.encode: wrong tag");if(tb(t,"data"),t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=Da(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let i=n>127?Da(o.length/2|128):"";return Da(e)+i+o+t},decode(e,t){let{Err:r}=pn;t=se(t,void 0,"DER data");let n=0;if(e<0||e>255)throw new r("tlv.decode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let d=t.subarray(n,n+c);if(d.length!==c)throw new r("tlv.decode: length bytes not complete");if(d[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let f of d)s=s<<8|f;if(n+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(e){let{Err:t}=pn;if(Od(e),e<uv)throw new t("integer: negative integers are not allowed");let r=Da(e);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=pn;if(e.length<1)throw new t("invalid signature integer: empty");if(e[0]&128)throw new t("invalid signature integer: negative");if(e.length>1&&e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return er(e)}},toSig(e,t){let{Err:r,_int:n,_tlv:o}=pn;if(t!==void 0&&(_e(t,"maxScalarBytes"),t<1))throw new r("invalid signature: maxScalarBytes must be positive");let i=se(e,void 0,"signature"),{v:s,l:a}=o.decode(48,i);if(a.length)throw new r("invalid signature: left bytes after parsing");let{v:c,l:d}=o.decode(2,s),{v:f,l:u}=o.decode(2,d);if(u.length)throw new r("invalid signature: left bytes after parsing");if(t!==void 0&&(c.length>t||f.length>t))throw new r("invalid signature: integer too large");return{r:n.decode(c),s:n.decode(f)}},hexFromSig(e){let{_tlv:t,_int:r}=pn;Be(e,{r:"bigint",s:"bigint"},{},"sig");let n=t.encode(2,r.encode(e.r)),o=t.encode(2,r.encode(e.s)),i=n+o;return t.encode(48,i)}},Vd=(Object.freeze(pn._tlv),Object.freeze(pn._int),Object.freeze(pn));var Fb=(e,t)=>(e+(e>=0?t:-t)/Mb)/t;function lv(e,t,r){Xn("scalar",e,mn,r);let[[n,o],[i,s]]=t,a=Fb(s*e,r),c=Fb(-o*e,r),d=e-a*n-c*i,f=-a*o-c*s,u=d<mn,l=f<mn;u&&(d=-d),l&&(f=-f);let p=qa(Math.ceil(tr(r)/2))+Qo;if(d<mn||d>=p||f<mn||f>=p)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:u,k1:d,k2neg:l,k2:f}}function s0(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function o0(e,t){Be(e);let r={};for(let n of Object.keys(t))r[n]=e[n]===void 0?t[n]:e[n];return Ut(r.lowS,"lowS"),Ut(r.prehash,"prehash"),r.format!==void 0&&s0(r.format),r}var mn=BigInt(0),Qo=BigInt(1),Mb=BigInt(2),i0=BigInt(3),pv=BigInt(4);function Ga(e,t={}){let r=zd("weierstrass",e,t),n=r.Fp,o=r.Fn,i=r.CURVE,{h:s,n:a}=i;Be(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:d,clearCofactor:f,isTorsionFree:u,fromBytes:l,toBytes:p}=t,m=t.randomBytes===void 0?lr:t.randomBytes;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let h=c?{beta:c.beta,basises:c.basises.map(F=>[...F])}:void 0,y=zb(n,o);function b(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function x(F,A,z){if(A.is0()){if(!d)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:D,y:q}=A.toAffine(),j=n.toBytes(D);if(Ut(z,"isCompressed"),z){b();let K=!n.isOdd(q);return ke(Hb(K),j)}else return ke(Uint8Array.of(4),j,n.toBytes(q))}function g(F){se(F,void 0,"Point");let{publicKey:A,publicKeyUncompressed:z}=y,D=F.length,q=F[0],j=F.subarray(1);if(d&&D===1&&q===0)return{x:n.ZERO,y:n.ZERO};if(D===A&&(q===2||q===3)){let K=n.fromBytes(j);if(!n.isValid(K))throw new Error("bad point: is not on curve, wrong x");let W=N(K),Z;try{Z=n.sqrt(W)}catch(de){let ue=de instanceof Error?": "+de.message:"";throw new Error("bad point: is not on curve, sqrt error"+ue)}b();let te=n.isOdd(Z);return(q&1)===1!==te&&(Z=n.neg(Z)),{x:K,y:Z}}else if(D===z&&q===4){let K=n.BYTES,W=n.fromBytes(j.subarray(0,K)),Z=n.fromBytes(j.subarray(K,K*2));if(!U(W,Z))throw new Error("bad point: is not on curve");return{x:W,y:Z}}else throw new Error(`bad point: got length ${D}, expected compressed=${A} or uncompressed=${z}`)}let w=p===void 0?x:p,v=l===void 0?g:l,E=n.mul(i.b,i0),B=n.is0(i.a)?F=>n.ZERO:F=>n.mul(i.a,F);function N(F){let A=n.sqr(F),z=n.mul(A,F);return n.add(n.add(z,n.mul(F,i.a)),i.b)}function U(F,A){let z=n.sqr(A),D=N(F);return n.eql(z,D)}if(!U(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let R=n.mul(n.pow(i.a,i0),pv),T=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(R,T)))throw new Error("bad curve params: a or b");function O(F,A,z=!1){if(!n.isValid(A)||z&&n.is0(A))throw new Error(`bad point coordinate ${F}`);return typeof A=="object"&&A!==null?n.create(A):A}function H(F){if(!(F instanceof k))throw new Error("Weierstrass Point expected")}function P(F){if(!h||!h.basises)throw new Error("no endo");return lv(F,h.basises,o.ORDER)}function _(F,A,z,D){if(!o.isValid(D))throw new RangeError("invalid scalar: out of range");if(h){let{k1neg:q,k1:j,k2neg:K,k2:W}=P(D),Z=new k(n.mul(z.X,h.beta),z.Y,z.Z);F.push(q?z.negate():z,K?Z.negate():Z),A.push(j,W)}else F.push(z),A.push(D)}let I=new WeakSet;class k{static BASE=new k(i.Gx,i.Gy,n.ONE);static ZERO=new k(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(A,z,D){this.X=O("x",A),this.Y=O("y",z,!0),this.Z=O("z",D),Object.freeze(this)}static CURVE(){return i}static fromAffine(A){let{x:z,y:D}=A||{};if(!A||!n.isValid(z)||!n.isValid(D))throw new Error("invalid affine point");if(A instanceof k)throw new Error("projective point not allowed");return n.is0(z)&&n.is0(D)?k.ZERO:new k(z,D,n.ONE)}static fromBytes(A){let z=k.fromAffine(v(se(A,void 0,"point")));return z.assertValidity(),z}static fromHex(A){return k.fromBytes(un(A))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(A=6,z=!0){return $.setWindowSize(this,A),z||this.multiply(i0),this}assertValidity(){let A=this;if(A.is0()){if(d&&n.is0(A.X)&&n.eql(A.Y,n.ONE)&&n.is0(A.Z))return;throw new Error("bad point: ZERO")}if(I.has(A))return;let{x:z,y:D}=A.toAffine();if(!n.isValid(z)||!n.isValid(D))throw new Error("bad point: x or y not field elements");if(!U(z,D))throw new Error("bad point: equation left != right");if(!A.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");I.add(A)}hasEvenY(){let{y:A}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(A)}equals(A){H(A);let{X:z,Y:D,Z:q}=this,{X:j,Y:K,Z:W}=A,Z=n.eql(n.mul(z,W),n.mul(j,q)),te=n.eql(n.mul(D,W),n.mul(K,q));return Z&&te}negate(){return new k(this.X,n.neg(this.Y),this.Z)}double(){let{X:A,Y:z,Z:D}=this,q=n.ZERO,j=n.ZERO,K=n.ZERO,W=n.mul(A,A),Z=n.mul(z,z),te=n.mul(D,D),J=n.mul(A,z);return J=n.add(J,J),K=n.mul(A,D),K=n.add(K,K),q=B(K),j=n.mul(E,te),j=n.add(q,j),q=n.sub(Z,j),j=n.add(Z,j),j=n.mul(q,j),q=n.mul(J,q),K=n.mul(E,K),te=B(te),J=n.sub(W,te),J=B(J),J=n.add(J,K),K=n.add(W,W),W=n.add(K,W),W=n.add(W,te),W=n.mul(W,J),j=n.add(j,W),te=n.mul(z,D),te=n.add(te,te),W=n.mul(te,J),q=n.sub(q,W),K=n.mul(te,Z),K=n.add(K,K),K=n.add(K,K),new k(q,j,K)}add(A){H(A);let{X:z,Y:D,Z:q}=this,{X:j,Y:K,Z:W}=A,Z=n.ZERO,te=n.ZERO,J=n.ZERO,de=n.mul(z,j),ue=n.mul(D,K),me=n.mul(q,W),Ne=n.add(z,D),fe=n.add(j,K);Ne=n.mul(Ne,fe),fe=n.add(de,ue),Ne=n.sub(Ne,fe),fe=n.add(z,q);let we=n.add(j,W);return fe=n.mul(fe,we),we=n.add(de,me),fe=n.sub(fe,we),we=n.add(D,q),Z=n.add(K,W),we=n.mul(we,Z),Z=n.add(ue,me),we=n.sub(we,Z),J=B(fe),Z=n.mul(E,me),J=n.add(Z,J),Z=n.sub(ue,J),J=n.add(ue,J),te=n.mul(Z,J),ue=n.add(de,de),ue=n.add(ue,de),me=B(me),fe=n.mul(E,fe),ue=n.add(ue,me),me=n.sub(de,me),me=B(me),fe=n.add(fe,me),de=n.mul(ue,fe),te=n.add(te,de),de=n.mul(we,fe),Z=n.mul(Ne,Z),Z=n.sub(Z,de),de=n.mul(Ne,ue),J=n.mul(we,J),J=n.add(J,de),new k(Z,te,J)}subtract(A){return H(A),this.add(A.negate())}is0(){return this.equals(k.ZERO)}multiply(A){if(!o.isValidNot0(A))throw new RangeError("invalid scalar: out of range");let{p:z,f:D}=$.mulSecret(this,A,s,M);return M([z,D])[0]}multiplyUnsafe(A){let z=this,D=A;if(!o.isValid(D))throw new RangeError("invalid scalar: out of range");if(D===mn||z.is0())return k.ZERO;if(D===Qo)return z;if($.hasWindowSize(this))return $.mulUnsafe(z,D,M);let q=[],j=[];return _(q,j,z,D),Hd(k,q,j)}mulAddUnsafe(A,z,D){H(z);let q=[],j=[];return _(q,j,this,A),_(q,j,z,D),Hd(k,q,j)}toAffine(A){let z=this,D=A;if(D!=null&&!n.isValid(D))throw new RangeError('"invertedZ" expected valid field element');let{X:q,Y:j,Z:K}=z;if(n.eql(K,n.ONE))return{x:q,y:j};let W=z.is0();D==null&&(D=W?n.ONE:n.inv(K));let Z=n.mul(q,D),te=n.mul(j,D),J=n.mul(K,D);if(W)return{x:n.ZERO,y:n.ZERO};if(!n.eql(J,n.ONE))throw new Error("invZ was invalid");return{x:Z,y:te}}isTorsionFree(){return s===Qo?!0:u?u(k,this):$.mulUnsafe(this,a).is0()}clearCofactor(){return s===Qo?this:f?f(k,this):this.multiplyUnsafe(s)}isSmallOrder(){return s===Qo?this.is0():this.clearCofactor().is0()}toBytes(A=!0){return Ut(A,"isCompressed"),this.assertValidity(),w(k,this,A)}toHex(A=!0){return Zn(this.toBytes(A))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let M=F=>Md(k,F),$=new Gi(k,m);return $.bits>=6&&k.BASE.precompute(6),Object.freeze(k.prototype),Object.freeze(k),k}function Hb(e){return Uint8Array.of(e?2:3)}function zb(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function mv(e,t={}){Fr(e);let{Fn:r}=e,n=t.randomBytes===void 0?lr:t.randomBytes,o=Object.assign(zb(e.Fp,r),{seed:Math.max(qi(r.ORDER),16)});function i(p){try{let m=r.fromBytes(p);return r.isValidNot0(m)}catch{return!1}}function s(p,m){let{publicKey:h,publicKeyUncompressed:y}=o;try{let b=p.length;return m===!0&&b!==h||m===!1&&b!==y?!1:!e.fromBytes(p).is0()}catch{return!1}}function a(p){return p=p===void 0?n(o.seed):p,ji(se(p,o.seed,"seed"),r.ORDER)}function c(p,m=!0){return e.BASE.multiply(r.fromBytes(p)).toBytes(m)}function d(p){let{secretKey:m,publicKey:h,publicKeyUncompressed:y}=o,b=r._lengths;if(!Qt(p))return;let x=se(p,void 0,"key").length,g=x===h||x===y,w=x===m||!!b?.includes(x);if(!(g&&w))return g}function f(p,m,h=!0){if(d(p)===!0)throw new Error("first arg must be private key");if(d(m)===!1)throw new Error("second arg must be public key");let y=r.fromBytes(p),b=e.fromBytes(m);if(b.is0())throw new Error("invalid public key: point at infinity");return b.multiply(y).toBytes(h)}let u={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},l=$d(a,c);return Object.freeze(u),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:l,Point:e,utils:u,lengths:o})}function $b(e,t,r={}){Fr(e);let n=t;Td(n),Be(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},r),i=o.randomBytes===void 0?lr:o.randomBytes,s=o.hmac===void 0?(F,A)=>Nb(n,F,A):o.hmac,{Fp:a,Fn:c}=e,{ORDER:d,BITS:f}=c,u=qi(d),l=Zp(i,u),{keygen:p,getPublicKey:m,getSharedSecret:h,utils:y,lengths:b}=mv(e,o),x={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},g=d*Mb+Qo<a.ORDER;function w(F){let A=d>>Qo;return F>A}function v(F,A){if(!c.isValidNot0(A))throw new Error(`invalid signature ${F}: out of range 1..Point.Fn.ORDER`);return A}function E(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function B(F,A,z){return E(),(F===z?0:2)|Number(a.isOdd(A))}function N(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function U(F,A){s0(A);let z=b.signature,D=A==="compact"?z:A==="recovered"?z+1:void 0;return se(F,D)}class R{r;s;recovery;constructor(A,z,D){if(this.r=v("r",A),this.s=v("s",z),D!=null){if(N(),![0,1,2,3].includes(D))throw new Error("invalid recovery id");this.recovery=D}Object.freeze(this)}static fromBytes(A,z=x.format){U(A,z);let D;if(z==="der"){if(A.length>2*c.BYTES+16)throw new Vd.Err("invalid signature: DER signature too long");let{r:W,s:Z}=Vd.toSig(se(A),c.BYTES+1);return new R(W,Z)}z==="recovered"&&(D=A[0],z="compact",A=A.subarray(1));let q=b.signature/2,j=A.subarray(0,q),K=A.subarray(q,q*2);return new R(c.fromBytes(j),c.fromBytes(K),D)}static fromHex(A,z){return this.fromBytes(un(A),z)}assertRecovery(){let{recovery:A}=this;if(A==null)throw new Error("invalid recovery id: must be present");return A}addRecoveryBit(A){return new R(this.r,this.s,A)}recoverPublicKey(A){let{r:z,s:D}=this,q=this.assertRecovery(),j=q===2||q===3?z+d:z;if(!a.isValid(j))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let K=a.toBytes(j),W=e.fromBytes(ke(Hb((q&1)===0),K)),Z=c.inv(j),te=O(se(A,void 0,"msgHash")),J=c.create(-te*Z),de=c.create(D*Z),ue=e.BASE.mulAddUnsafe(J,W,de);if(ue.is0())throw new Error("invalid recovery: point at infinify");return ue.assertValidity(),ue}hasHighS(){return w(this.s)}toBytes(A=x.format){if(s0(A),A==="der")return un(Vd.hexFromSig(this));let{r:z,s:D}=this,q=c.toBytes(z),j=c.toBytes(D);return A==="recovered"?(N(),ke(Uint8Array.of(this.assertRecovery()),q,j)):ke(q,j)}toHex(A){return Zn(this.toBytes(A))}}Object.freeze(R.prototype),Object.freeze(R);let T=o.bits2int===void 0?function(A){if(A.length>8192)throw new Error("input is too large");let z=er(A),D=A.length*8-f;return D>0?z>>BigInt(D):z}:o.bits2int,O=o.bits2int_modN===void 0?function(A){return c.create(T(A))}:o.bits2int_modN,H=qa(f);function P(F){return Xn("num < 2^"+f,F,mn,H),c.toBytes(F)}function _(F,A){return se(F,void 0,"message"),A?se(n(F),void 0,"prehashed message"):F}function I(F,A,z){let{lowS:D,prehash:q,extraEntropy:j}=o0(z,x);F=_(F,q);let K=O(F),W=c.fromBytes(A);if(!c.isValidNot0(W))throw new Error("invalid private key");let Z=[P(W),P(K)];if(j!=null&&j!==!1){let ue=j===!0?i(b.secretKey):j;Z.push(se(ue,void 0,"extraEntropy"))}let te=ke(...Z),J=K;function de(ue){let me=T(ue);if(!c.isValidNot0(me))return;let Ne=e.BASE.multiply(me).toAffine(),fe=c.create(Ne.x);if(fe===mn)return;let we;if(l!==void 0){let dr=er(ji(l(u),d)),cn=c.inv(c.mul(dr,me)),dn=c.mul(dr,J),qo=c.mul(dr,W);we=c.create(cn*c.create(dn+qo*fe))}else{let dr=mb(me,d);we=c.create(dr*c.create(J+fe*W))}if(we===mn)return;let an=B(Ne.x,Ne.y,fe),Ln=we;return D&&w(we)&&(Ln=c.neg(we),an^=1),new R(fe,Ln,g?void 0:an)}return{seed:te,k2sig:de}}function k(F,A,z={}){let{seed:D,k2sig:q}=I(F,A,z);return ob(n.outputLen,c.BYTES,s)(D,q).toBytes(z.format)}function M(F,A,z,D={}){let{lowS:q,prehash:j,format:K}=o0(D,x);if(z=se(z,void 0,"publicKey"),A=_(A,j),!Qt(F)){let W=F instanceof R?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+W)}U(F,K);try{let W=R.fromBytes(F,K),Z=e.fromBytes(z);if(Z.is0()||q&&W.hasHighS())return!1;let{r:te,s:J}=W,de=O(A),ue=c.inv(J),me=c.create(de*ue),Ne=c.create(te*ue),fe=e.BASE.mulAddUnsafe(me,Z,Ne);if(fe.is0())return!1;let we=fe.toAffine();return!(c.create(we.x)!==te||K==="recovered"&&W.recovery!==B(we.x,we.y,te))}catch{return!1}}function $(F,A,z={}){let{prehash:D}=o0(z,x);return A=_(A,D),R.fromBytes(F,"recovered").recoverPublicKey(A).toBytes()}return Object.freeze({keygen:p,getPublicKey:m,getSharedSecret:h,utils:y,lengths:b,Point:e,sign:k,verify:M,recoverPublicKey:$,Signature:R,hash:n})}var c0={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},hv={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Lb=BigInt(2);function yv(e){let t=c0.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),d=e*e*e%t,f=d*d*e%t,u=Fe(f,r,t)*f%t,l=Fe(u,r,t)*f%t,p=Fe(l,Lb,t)*d%t,m=Fe(p,o,t)*p%t,h=Fe(m,i,t)*m%t,y=Fe(h,a,t)*h%t,b=Fe(y,c,t)*y%t,x=Fe(b,a,t)*h%t,g=Fe(x,r,t)*f%t,w=Fe(g,s,t)*m%t,v=Fe(w,n,t)*d%t,E=Fe(v,Lb,t);if(!a0.eql(a0.sqr(E),e))throw new Error("Cannot find square root");return E}var a0=Nr(c0.p,{sqrt:yv}),bv=Ga(c0,{Fp:a0,endo:hv}),eo=$b(bv,ur);var gv=BigInt(0),Va=BigInt(1),wv=BigInt(2),xv=BigInt(7),vv=BigInt(256),Sv=BigInt(113),jb=[],Gb=[],Vb=[];for(let e=0,t=Va,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],jb.push(2*(5*n+r)),Gb.push((e+1)*(e+2)/2%64);let o=gv;for(let i=0;i<7;i++)t=(t<<Va^(t>>xv)*Sv)%vv,t&wv&&(o^=Va<<(Va<<BigInt(i))-Va);Vb.push(o)}var Kb=Ed(Vb,!0),Ev=Kb[0],_v=Kb[1],Av=(e,t,r)=>e<<r|t>>>32-r,Tv=(e,t,r)=>t<<r|e>>>32-r,Iv=(e,t,r)=>t<<r-32|e>>>64-r,kv=(e,t,r)=>e<<r-32|t>>>64-r,Db=(e,t,r)=>r>32?Iv(e,t,r):Av(e,t,r),qb=(e,t,r)=>r>32?kv(e,t,r):Tv(e,t,r),Vi=new Uint32Array(10);function Bv(e,t=24){if(!(e instanceof Uint32Array))throw new TypeError('"s" expected Uint32Array(50), got type='+typeof e);if(e.length!==50)throw new RangeError('"s" expected Uint32Array(50), got length='+e.length);if(ut(t,"rounds"),t<1||t>24)throw new Error('"rounds" expected integer 1..24');for(let r=24-t;r<24;r++){for(let i=0;i<10;i++)Vi[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let s=(i+8)%10,a=(i+2)%10,c=Vi[a],d=Vi[a+1],f=Db(c,d,1)^Vi[s],u=qb(c,d,1)^Vi[s+1];for(let l=0;l<50;l+=10)e[i+l]^=f,e[i+l+1]^=u}let n=e[2],o=e[3];for(let i=0;i<24;i++){let s=Gb[i],a=Db(n,o,s),c=qb(n,o,s),d=jb[i];n=e[d],o=e[d+1],e[d]=a,e[d+1]=c}for(let i=0;i<50;i+=10){let s=e[i],a=e[i+1],c=e[i+2],d=e[i+3];e[i]^=~e[i+2]&e[i+4],e[i+1]^=~e[i+3]&e[i+5],e[i+2]^=~e[i+4]&e[i+6],e[i+3]^=~e[i+5]&e[i+7],e[i+4]^=~e[i+6]&e[i+8],e[i+5]^=~e[i+7]&e[i+9],e[i+6]^=~e[i+8]&s,e[i+7]^=~e[i+9]&a,e[i+8]^=~s&c,e[i+9]^=~a&d}e[0]^=Ev[r],e[1]^=_v[r]}Or(Vi)}var d0=class e{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;canXOF;enableXOF=!1;rounds;constructor(t,r,n,o=!1,i=24){if(ut(t,"blockLen"),ut(r,"suffix"),ut(i,"rounds"),Vy(o,"enableXOF"),this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.canXOF=o,this.rounds=i,ut(n,"outputLen"),!(0<t&&t<200))throw new Error('"blockLen" must be 1..199');this.state=new Uint8Array(200),this.state32=Rp(this.state)}clone(){return this._cloneInto()}keccak(){Op(this.state32),Bv(this.state32,this.rounds),Op(this.state32),this.posOut=0,this.pos=0}update(t){fn(this),St(t);let{blockLen:r,state:n,state32:o}=this,i=t.length,s=r%4===0&&t.byteOffset%4===0,a=r/4,c=s&&i>=r?Rp(t):void 0;for(let d=0;d<i;){if(c!==void 0&&this.pos===0&&d%4===0&&i-d>=r){for(let u=0,l=d/4;u<a;u++)o[u]^=c[l+u];d+=r,this.pos=r,this.keccak();continue}let f=Math.min(r-this.pos,i-d);for(let u=0;u<f;u++)n[this.pos++]^=t[d++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:t,suffix:r,pos:n,blockLen:o}=this;t[n]^=r,(r&128)!==0&&n===o-1&&this.keccak(),t[o-1]^=128,this.keccak()}writeInto(t){fn(this,!1),St(t),this.finish();let r=this.state,{blockLen:n}=this;for(let o=0,i=t.length;o<i;){this.posOut>=n&&this.keccak();let s=Math.min(n-this.posOut,i-o);t.set(r.subarray(this.posOut,this.posOut+s),o),this.posOut+=s,o+=s}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not enabled");return this.writeInto(t)}xof(t){return ut(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(Di(t,this),this.finished)throw new Error("digest() was already called");this.writeInto(t.length===this.outputLen?t:t.subarray(0,this.outputLen)),this.destroy()}digest(){let t=new Uint8Array(this.outputLen);return this.digestInto(t),t}destroy(){this.destroyed=!0,Or(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:o,rounds:i,enableXOF:s}=this;return t||=new e(r,n,o,s,i),t.blockLen=r,t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=i,t.suffix=n,t.outputLen=o,t.enableXOF=s,t.canXOF=this.canXOF,t.destroyed=this.destroyed,t}},Wb=(e,t,r,n={})=>za(()=>new d0(t,e,r),n);var Zb=Wb(6,136,32,$a(8));var Pe=Wb(1,136,32);var Yb=new TextEncoder,Xb=(...e)=>Uint8Array.from(e.flatMap(t=>Array.from(t)));function Ka(e,t,r){return Pv(e,t)===r.toLowerCase()}function Pv(e,t){if(t.length!==65||t[64]!==27&&t[64]!==28||BigInt(`0x${xd(t.subarray(32,64))}`)>eo.Point.Fn.ORDER/2n)return null;let n=Yb.encode(e),o=Pe(Xb(Yb.encode(`Ethereum Signed Message:
41
+ ${n.length}`),n));try{let i=Xb(new Uint8Array([(t[64]??27)-27]),t.subarray(0,64)),s=eo.Point.fromBytes(eo.recoverPublicKey(i,o,{prehash:!1}));return`0x${xd(Pe(s.toBytes(!1).subarray(1)).subarray(12))}`}catch{return null}}var hr=e=>({evm:0,solana:1,near:2})[e.kind];function ne(e){ae(e,["kind","id"]);let{kind:t,id:r}=e;if(typeof r!="string")throw new TypeError("invalid identity id");if(t==="near")return{kind:t,id:be(r)};if(t==="evm"){let n=r.toLowerCase();return G(n,20),{kind:t,id:n}}if(t==="solana"){let n;if(/^[a-fA-F0-9]{64}$/.test(r))n=G(`0x${r.toLowerCase()}`,32);else{if(r.length<32||r.length>44)throw new TypeError("invalid Solana key");if(n=Ct.decode(r),n.length!==32||Ct.encode(n)!==r)throw new TypeError("invalid Solana key")}return{kind:t,id:Y(n).slice(2)}}throw new TypeError("unknown identity kind")}function Tt(e){let t=ne(e);return Et(new Uint8Array([hr(t)]),t.kind==="near"?At(t.id):G(t.kind==="evm"?t.id:`0x${t.id}`,t.kind==="evm"?20:32))}var Q=e=>JSON.stringify(ne(e));function Ke(e){let t=ne(e);return t.kind==="near"?`NEAR ${t.id}`:t.kind==="evm"?`EVM ${t.id}`:`Solana ${Ct.encode(G(`0x${t.id}`,32))}`}function lt(e,t,r,n){try{let o=ne(e);if(typeof t!="string"||t.includes("\r")||t.endsWith(`
42
+ `))return!1;if(o.kind==="near")return r===void 0&&n===o.id;if(ae(r,["kind","sig"]),r.kind!==o.kind)return!1;let i=G(r.sig,o.kind==="evm"?65:64);return o.kind==="evm"?Ka(t,i,o.id):jd.verify(i,et.encode(t),G(`0x${o.id}`,32),{zip215:!1})}catch{return!1}}function f0(e,t,r){if(!(r.signedMessage instanceof Uint8Array)||Cr(r.signedMessage,et.encode(t))!==0)throw new S("invalid_signature","wallet returned different signed bytes");let n={kind:"solana",sig:Y(r.signature)};if(e.kind!=="solana"||!lt(e,t,n))throw new S("invalid_signature","the signature is not from the seller");return n}var u0="0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",Ki="17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1",Jb=e=>{let t=_t(e,128);if(t===0n)throw new RangeError("price must be positive");return je(t,16)};function Rv(e,t={}){if(ae(e,["network","contract","file_id","seller","pay2_version","cipher_hash","moderator","near","base"]),ae(e.near,["token","price","recipients","remainder"]),e.base!==null&&(ae(e.base,["usdc","price","pay_to"]),e.base.usdc!==(t.baseUsdc??u0)))throw new TypeError("invalid Base USDC");if(Gn(e.network),be(e.contract),e.pay2_version!==2)throw new TypeError("unsupported PAY2 version");let r=e.near;if(be(r.token),(t.nearUsdc!==void 0||e.network==="near:mainnet")&&r.token!==(t.nearUsdc??Ki)||r.recipients.length<1||r.recipients.length>8||!Number.isInteger(r.remainder)||r.remainder<0||r.remainder>=r.recipients.length)throw new TypeError("invalid NEAR terms");let n,o=0,i=r.recipients.map(s=>{ae(s,["identity","bps"]);let a=Tt(s.identity);if(n&&Cr(n,a)>=0)throw new TypeError("recipients must be distinct and Borsh sorted");if(n=a,!Number.isInteger(s.bps)||s.bps<=0||s.bps>1e4)throw new TypeError("invalid bps");return o+=s.bps,Et(a,je(s.bps,2))});if(o!==1e4)throw new TypeError("bps must sum to 10000");return Et(At(e.network),At(e.contract),G(e.file_id,32),Tt(e.seller),je(e.pay2_version,1),G(e.cipher_hash,32),e.moderator===null?je(0,1):Et(je(1,1),At(be(e.moderator))),At(r.token),Jb(r.price),je(i.length,4),...i,je(r.remainder,1),e.base===null?je(0,1):Et(je(1,1),G(e.base.usdc,20),Jb(e.base.price),G(e.base.pay_to,20)))}var tt=(e,t)=>Pd("annon/terms/v2",Rv(e,t));function Wa(e,t,r,n){let o=tt(e,n);return G(t,48),["Annon: list a file for sale","Signing this lets whoever holds the seller key below open the file.",`contract: ${e.contract}`,`file: ${e.file_id}`,`seller: ${Ke(e.seller)}`,`price: ${ct(e.near.price)} USDC on NEAR`,...e.near.recipients.map(i=>`split: ${Ke(i.identity)} ${(i.bps/100).toFixed(2)}%`),`remainder: ${Ke(e.near.recipients[e.near.remainder].identity)}`,e.base?`base: ${ct(e.base.price)} USDC on Base to ${e.base.pay_to}`:"base: none",`cipher: ${e.cipher_hash}`,`moderator: ${e.moderator??"(none)"}`,`terms: ${o}`,`seller key: ${t}`,`valid until: ${Vn(r)}`].join(`
43
+ `)}function l0(e,t,r){return be(e),G(t,32),G(r,32),`Annon: publish a file
44
44
  contract: ${e}
45
45
  file: ${t}
46
- header: ${r}`}var Re=class extends S{code;constructor(t,r=t){super(t,r),this.code=t,this.name="Pay2Error"}},Ae=(e,t)=>{throw new Re(e,t)},Xa=[80,65,89,50],Hr=54,ve=16,h0=65536,Wi=1024,Xb=65536,Kd=4096,yn=32,yr=65,bn="near-ckd/v1",jt=globalThis.crypto.subtle,to=new TextEncoder;function Te(...e){return st(e)}function rt(e,t){let r=new Uint8Array(t),n=new DataView(r.buffer);return t===1?n.setUint8(0,e):t===2?n.setUint16(0,e):t===4?n.setUint32(0,e):n.setBigUint64(0,BigInt(e)),r}var pt=(e,t)=>e.length===t.length&&e.every((r,n)=>r===t[n]),We=e=>new Uint8Array(e);function Zi(e){if(!(e.buffer instanceof ArrayBuffer))throw new TypeError("pass bytes over an ArrayBuffer");return e}async function Oe(...e){let t=e.length===1?Zi(e[0]):Te(...e);return new Uint8Array(await jt.digest("SHA-256",t))}async function ei(e,t,r){let n=e instanceof Uint8Array?await jt.importKey("raw",We(e),"HKDF",!1,["deriveBits"]):e,o=await jt.deriveBits({name:"HKDF",hash:"SHA-256",salt:We(t),info:typeof r=="string"?to.encode(r):We(r)},n,256);return new Uint8Array(o)}var ti=(e,t,r)=>ei(e,t,Te(to.encode("annon/pay2/chunk"),rt(r,4))),Ja=e=>Oe(to.encode("annon/pay2/key"),e);function Tv(e){let t=new Uint8Array(12);return t[11]=e?1:0,t}async function Qa(e,t,r,n){let o=await jt.importKey("raw",We(t),"AES-GCM",!1,[e]),i=await jt[e]({name:"AES-GCM",iv:Tv(r)},o,Zi(n));return new Uint8Array(i)}var ec=async(e,t,r)=>{if(e.length!==48)throw new TypeError("ckdSecret must be the 48-byte G1 point");let n=await ei(e,t,"annon/pay2/near-ckd/v1");return jt.importKey("raw",n,"AES-KW",!1,[r])},tc=e=>Oe(to.encode("annon/pay2/body"),new Uint8Array([e.version??2,e.chunkLog2]),e.fileId,rt(e.metaLen,2),rt(e.previewLen,4),rt(e.n,4),...e.commits,...e.hashes);function m0(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t)}function Ya(e,t=32){let r=typeof e=="string"?e.replace(/^0x/,""):"";if(typeof e!="string"?e.length!==t:!new RegExp(`^[0-9a-f]{${2*t}}$`,"i").test(r))throw new TypeError(`expected ${t} bytes`);return typeof e=="string"?Uint8Array.from(r.match(/../g)??[],n=>Number.parseInt(n,16)):e}function Jb(e){if(!/^0x[0-9a-f]{40}$/i.test(e))throw new TypeError("seller must be a 0x EVM address");return e.toLowerCase()}function y0(e,t=!1){(e.length<4||!Xa.every((x,g)=>e[g]===x))&&Ae("bad_magic"),e.length<Hr&&Ae("bad_header","shorter than the fixed header");let r=new DataView(e.buffer,e.byteOffset,e.byteLength);e[4]!==2&&Ae("unsupported_version");let n=e[4],o=e[7]??0,i=e[5]??0;(i<16||i>24)&&Ae("bad_chunk_size");let s=r.getUint32(8);s>h0&&Ae("header_too_large");let a=e[6]??0,c=r.getUint16(44),d=r.getUint32(46),f=r.getUint32(50),u=d>0?2:1,l=Hr+32*(u+f);(!(t?a===0&&s===0:a>=1&&a<=8&&s>=l+yn+yr)||o>2||c<256||c>Kd||c%256!==0||d>Xb||f<2||f>Wi||d>0&&f<3||e.length<(t?l:s))&&Ae("bad_header");let m=x=>e.slice(Hr+32*x,Hr+32*(x+1)),h={version:n,authKind:o,chunkLog2:i,fileId:e.slice(12,44),metaLen:c,previewLen:d,n:f,commits:Array.from({length:u},(x,g)=>m(g)),hashes:Array.from({length:f},(x,g)=>m(u+g)),prefixLen:l,headerLen:s,stanzas:[]};if(t)return h;let y=s-yn-yr,b=l;for(let x=0;x<a;x++){let g=e[b]??0;(g<1||g>32||b+3+g>y)&&Ae("bad_stanza");let w=String.fromCharCode(...e.subarray(b+1,b+1+g)),v=r.getUint16(b+1+g),E=b+3+g;(!/^[a-z0-9/.-]+$/.test(w)||v>1024||E+v>y||h.stanzas.some(N=>N.type===w))&&Ae("bad_stanza");let B=e.slice(E,E+v);w===bn&&!ri(B)&&Ae("bad_stanza"),h.stanzas.push({type:w,body:B}),b=E+v}return b!==y&&Ae("bad_header","stanzas do not end at the MAC"),h}function ri(e){let t=e[0]??0;if(t<2||t>64||e.length!==1+t+40)return;let r=String.fromCharCode(...e.subarray(1,1+t));if(/^[a-z0-9._-]+$/.test(r))return{contractId:r,wrapped:e.slice(1+t)}}function Qb(e){return Array.from({length:e.n-1},(t,r)=>r===0?e.metaLen+ve:r===1&&e.previewLen>0?e.previewLen+ve:2**e.chunkLog2+ve)}var ro=(e,t,r)=>1+(t>0?1:0)+Math.max(1,Math.ceil((e-t)/2**r));function b0(e,t){let r=p=>Ae("meta_invalid",p),n=new DataView(e.buffer,e.byteOffset,e.byteLength),i=2+n.getUint16(0);i+1>e.length&&r("name runs past the metadata");let s=e[i]??0,a=i+1+s,c=a+8;c>e.length&&r("mime runs past the metadata"),Math.ceil(c/256)*256!==e.length&&r("padding is not minimal"),e.subarray(c).some(p=>p!==0)&&r("padding is not zero");let d="";try{d=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(e.subarray(2,i))}catch{r("name is not UTF-8")}let f=e.subarray(i+1,a);f.some(p=>p<32||p>126)&&r("mime is not printable ASCII");let u=n.getBigUint64(a);u>BigInt(Number.MAX_SAFE_INTEGER)&&r("size too large");let l=Number(u);return t.previewLen>no(l)&&r("preview over the limit"),t.n!==ro(l,t.previewLen,t.chunkLog2)&&r("chunk count does not fit the size"),{name:d,mime:String.fromCharCode(...f),size:l}}async function eg(e,t,r){return tg(await rg(Zi(e),t,r),Zi(e),r)}async function ni(e,t,r){let n=Zi(e),o=await Yi(n,t,r);return n.length!==o.headerLen&&Ae("bad_header","expected the header alone"),tg(o,n,r)}var tg=async(e,t,r)=>{let n=We(t.subarray(0,e.headerLen));return{fileId:e.fileId,usable:e.stanzas.some(o=>o.type===bn&&ri(o.body)?.contractId===r),header:n,headerHash:await Oe(n)}};async function Yi(e,t,r){let n=y0(e),o=t.pay2Version??2;n.version!==o&&Ae("unsupported_version");let i=await Iv(n,t),s=typeof t.seller=="string"?ne({kind:"evm",id:Jb(t.seller)}):ne(t.seller),a=await Oe(e.subarray(0,i.headerLen-yr)),c=e.subarray(i.headerLen-yr,i.headerLen);if(hr(s)!==i.authKind&&Ae("seller_signature_invalid"),s.kind==="near")(c.some(d=>d!==0)||t.publishedHeaderHash===void 0||!pt(a,Ya(t.publishedHeaderHash)))&&Ae("seller_signature_invalid");else{s.kind==="solana"&&c[64]!==0&&Ae("seller_signature_invalid");let d=s.kind==="solana"?c.subarray(0,64):c;lt(s,p0(r,Y(i.fileId),Y(a)),{kind:s.kind,sig:Y(d)})||Ae("seller_signature_invalid")}return i}async function rg(e,t,r){let n=await Yi(e,t,r),o=Qb(n),i=e.subarray(n.headerLen),s=i.length-o.reduce((c,d)=>c+d,0);(s<ve||s>2**n.chunkLog2+ve)&&Ae("bad_body_length");let a=0;for(let[c,d]of[...o,s].entries())pt(await Oe(i.subarray(a,a+d)),n.hashes[c])||Ae("chunk_hash_mismatch",`chunk ${c}`),a+=d;return n}async function Iv(e,t){return pt(e.fileId,Ya(t.fileId))||Ae("file_id_mismatch"),pt(await tc(e),Ya(t.cipherHash))||Ae("cipher_hash_mismatch"),e}async function ng(e,t){let r=Zi(e),n=await rg(r,t.listing,t.contractId),o=n.stanzas.map(b=>b.type===bn?ri(b.body):void 0).find(b=>b?.contractId===t.contractId);if(!o)return Ae("no_usable_stanza");let i=await ec(await t.ckdSecret(n.fileId),n.fileId,"unwrapKey"),s;try{s=await jt.unwrapKey("raw",o.wrapped,i,"AES-KW","HKDF",!1,["deriveBits"])}catch{return Ae("key_unwrap_failed")}let a=await jt.importKey("raw",await ei(s,n.fileId,"annon/pay2/header"),{name:"HMAC",hash:"SHA-256"},!1,["verify"]),c=n.headerLen-yn-yr,d=r.subarray(c,c+yn);await jt.verify("HMAC",a,d,r.subarray(0,c))||Ae("header_mac_invalid");let f=Qb(n),u=r.subarray(n.headerLen);f.push(u.length-f.reduce((b,x)=>b+x,0));let l=[],p=0;for(let b of f)l.push(u.subarray(p,p+b)),p+=b;let m=async b=>{let x=await ti(s,n.fileId,b),g=n.commits[b];g&&!pt(await Ja(x),g)&&Ae("chunk_invalid",`chunk ${b} key commitment`);try{return await Qa("decrypt",x,b===n.n-1,l[b])}catch{return Ae("chunk_invalid",`chunk ${b}`)}},h=b0(await m(0),n);f.slice(1).reduce((b,x)=>b+x-ve,0)!==h.size&&Ae("meta_invalid","chunk lengths do not add up to the size");let y=[];for(let b=1;b<n.n;b++)y.push(await m(b));return{meta:h,data:Te(...y)}}function g0(e){let t=e.version??2,r=e.authKind??0;if(t!==2||![0,1,2].includes(r))throw new TypeError("invalid PAY2 version/auth kind");return{version:t,authKind:r}}async function w0(e,t,r,n,o){let i=typeof r.seller=="string"?ne({kind:"evm",id:Jb(r.seller)}):ne(r.seller);if(hr(i)!==t)throw new TypeError("seller identity does not match auth kind");if(i.kind==="near")return new Uint8Array(yr);if(!r.sign)throw new TypeError("seller signature required");if(e!==2)throw new TypeError("unsupported PAY2 version");let s=p0(r.contractId,Y(n),Y(o)),a=await r.sign(s);if(i.kind==="solana"){if(typeof a=="string"||a instanceof Uint8Array)throw new TypeError("Solana wallet must return signed bytes");let d=u0(i,s,a);return Te(Ya(d.sig,64),new Uint8Array([0]))}if(typeof a!="string"&&!(a instanceof Uint8Array))throw new TypeError("expected EVM signature bytes");let c=Ya(a,yr);if(!Wa(s,c,i.id))throw new Error("the signature is not from the seller");return c}async function og(e,t,r){if(r.fileId.length!==32||e.length!==32)throw new TypeError("fileId and K are 32 bytes");let{version:n,authKind:o}=g0(r),i=We(r.fileId),s=r.previewLen??0;if(!Number.isSafeInteger(s)||s<0||s>no(t.length))throw new RangeError(`previewLen must be 0 to ${no(t.length)}`);let a=r.chunkLog2??22;for(;r.chunkLog2===void 0&&a<24&&ro(t.length,s,a)>Wi;)a++;if(!Number.isInteger(a)||a<16||a>24)throw new RangeError("chunkLog2 must be an integer from 16 to 24");if(ro(t.length,s,a)>Wi)throw new RangeError("file too large for PAY2");let c=2**a,d=to.encode(r.name);if(!/^[\x20-\x7e]{0,255}$/.test(r.mime))throw new RangeError("mime must be printable ASCII");let f=Te(rt(d.length,2),d,rt(r.mime.length,1),to.encode(r.mime),rt(t.length,8)),u=Math.ceil(f.length/256)*256;if(u>Kd)throw new RangeError("name too long");let l=[Te(f,new Uint8Array(u-f.length))];s>0&&l.push(t.subarray(0,s));let p=t.subarray(s);for(let v=0;v<p.length||v===0;v+=c)l.push(p.subarray(v,v+c));let m=l.length,h=await Promise.all(l.map((v,E)=>ti(e,i,E))),y=await Promise.all(h.slice(0,s>0?2:1).map(v=>Ja(v))),b=await Promise.all(l.map((v,E)=>Qa("encrypt",h[E],E===m-1,v))),x=await Promise.all(b.map(v=>Oe(v))),g=Te(new Uint8Array(Xa),new Uint8Array([n,a,1,o]),new Uint8Array(4),i,rt(u,2),rt(s,4),rt(m,4),...y,...x),w;return{fileId:i,cipherHash:await tc({version:n,chunkLog2:a,fileId:i,metaLen:u,previewLen:s,n:m,commits:y,hashes:x}),async finish(v){let{contractId:E,ckdSecret:B}=v;be(E);let N=await ec(B,i,"wrapKey"),U=await jt.importKey("raw",We(e),"AES-GCM",!0,["encrypt"]),R=new Uint8Array(await jt.wrapKey("raw",U,N,"AES-KW")),T=to.encode(bn),O=Te(new Uint8Array([E.length]),to.encode(E),R),z=Te(new Uint8Array([T.length]),T,rt(O.length,2),O),P=Te(g,z);new DataView(P.buffer).setUint32(8,P.length+yn+yr);let _=await jt.importKey("raw",await ei(e,i,"annon/pay2/header"),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),I=new Uint8Array(await jt.sign("HMAC",_,P)),k=await w0(n,o,v,i,await Oe(P,I));return w=P,Te(P,I,k,...b)},async preview(v){if(!w)throw new Error("call finish first: the preview carries the final header");if(v.data&&s===0)throw new RangeError("sealed without a preview");let E=[...v.meta?[0]:[],...v.data?[1]:[]];return{v:1,header:m0(kv(w.subarray(0,g.length))),chunks:E.map(B=>({index:B,key:m0(h[B]),data:m0(b[B])}))}}}}function kv(e){let t=We(e);return t[6]=0,t.fill(0,8,12),t}var no=e=>Math.min(Xb,Math.floor(e/10));var Bv=BigInt(0),Wd=BigInt(1),ig=BigInt(2),Xi=BigInt(3);function Pv(e){let t=[];for(;e>Wd;e>>=Wd)(e&Wd)===Bv?t.unshift(0):(e&Xi)===Xi?(t.unshift(-1),e+=Wd):t.unshift(1);return t}function x0(e){if(!Array.isArray(e)||e.length===0)throw new Error("expected non-empty array")}function Rv(e,t,r,n){if(Be(e,{Fp:"object",Fr:"object",Fp2:"object",Fp12:"object"},{Fp6:"object"},"fields"),typeof t!="function")throw new TypeError('"G1_Point" expected point constructor, got type='+typeof t);if(typeof r!="function")throw new TypeError('"G2_Point" expected point constructor, got type='+typeof r);Be(n,{ateLoopSize:"bigint",xNegative:"boolean",twistType:"string"},{randomBytes:"function",postPrecompute:"function"},"params");let{Fp:o,Fr:i,Fp2:s,Fp12:a}=e,{twistType:c,ateLoopSize:d,xNegative:f,postPrecompute:u}=n,l=(k,M)=>({c0:k,c1:M}),p=({c0:k,c1:M})=>Object.freeze({c0:k,c1:M}),m=(k,M)=>l(o.add(k.c0,M.c0),o.add(k.c1,M.c1)),h=(k,M)=>l(o.sub(k.c0,M.c0),o.sub(k.c1,M.c1)),y=(k,M)=>{let $=o.mul(k.c0,M.c0),F=o.mul(k.c1,M.c1);return l(o.sub($,F),o.sub(o.mul(o.add(k.c0,k.c1),o.add(M.c0,M.c1)),o.add($,F)))},b=(k,M)=>l(o.mul(k.c0,M),o.mul(k.c1,M)),x=k=>s.mulByNonresidue(k),g=({c0:k,c1:M},$,F,A,H,D)=>{let q=b(F,H),j=b(A,D),{c0:K,c1:W,c2:Z}=k,{c0:te,c1:J,c2:de}=M,ue=y(K,$),me=y(W,q),Ne=m(x(h(y(m(W,Z),q),me)),ue),fe=h(h(y(m($,q),m(K,W)),ue),me),we=m(h(y(m(K,Z),$),ue),me),cn=x(y(de,j)),Ln=y(te,j),dr=y(J,j),dn=m(K,te),fn=m(W,J),qo=m(Z,de),jo=m(q,j),Go=y(dn,$),Vo=y(fn,jo),Ap=m(x(h(y(m(fn,qo),jo),Vo)),Go),Tp=h(h(y(m($,jo),m(dn,fn)),Go),Vo),Ip=m(h(y(m(dn,qo),$),Go),Vo);return Object.freeze({c0:Object.freeze({c0:p(m(x(dr),Ne)),c1:p(m(cn,fe)),c2:p(m(Ln,we))}),c1:Object.freeze({c0:p(h(h(Ap,Ne),cn)),c1:p(h(h(Tp,fe),Ln)),c2:p(h(h(Ip,we),dr))})})},w=({c0:k,c1:M},$,F,A,H,D)=>{let q=b($,D),j=b(F,H),{c0:K,c1:W,c2:Z}=k,{c0:te,c1:J,c2:de}=M,ue=y(K,q),me=y(W,q),Ne=y(Z,q),fe=y(te,j),we=y(J,A),cn=m(x(h(y(m(J,de),A),we)),fe),Ln=h(h(y(m(j,A),m(te,J)),fe),we),dr=m(h(y(m(te,de),j),fe),we),dn=m(K,te),fn=m(W,J),qo=m(Z,de),jo=m(q,j),Go=y(dn,jo),Vo=y(fn,A),Ap=m(x(h(y(m(fn,qo),A),Vo)),Go),Tp=h(h(y(m(jo,A),m(dn,fn)),Go),Vo),Ip=m(h(y(m(dn,qo),jo),Go),Vo);return Object.freeze({c0:Object.freeze({c0:p(m(x(dr),ue)),c1:p(m(cn,me)),c2:p(m(Ln,Ne))}),c1:Object.freeze({c0:p(h(h(Ap,ue),cn)),c1:p(h(h(Tp,me),Ln)),c2:p(h(h(Ip,Ne),dr))})})},v;if(c==="multiplicative")v=(k,M,$,F,A,H)=>g(F,k,M,$,A,H);else if(c==="divisive")v=(k,M,$,F,A,H)=>w(F,$,M,k,A,H);else throw new Error("bls: unknown twist type");let E=s.div(s.ONE,s.mul(s.ONE,ig));function B(k,M,$,F){let A=s.sqr($),H=s.sqr(F),D=s.mulByB(s.mul(H,Xi)),q=s.mul(D,Xi),j=s.sub(s.sub(s.sqr(s.add($,F)),H),A),K=s.sub(D,A),W=s.mul(s.sqr(M),Xi),Z=s.neg(j);return k.push([K,W,Z]),M=s.mul(s.mul(s.mul(s.sub(A,q),M),$),E),$=s.sub(s.sqr(s.mul(s.add(A,q),E)),s.mul(s.sqr(D),Xi)),F=s.mul(A,j),{Rx:M,Ry:$,Rz:F}}function N(k,M,$,F,A,H){let D=s.sub($,s.mul(H,F)),q=s.sub(M,s.mul(A,F)),j=s.sub(s.mul(D,A),s.mul(q,H)),K=s.neg(D),W=q;k.push([j,K,W]);let Z=s.sqr(q),te=s.mul(Z,q),J=s.mul(Z,M),de=s.add(s.sub(te,s.mul(J,ig)),s.mul(s.sqr(D),F));return M=s.mul(q,de),$=s.sub(s.mul(s.sub(J,de),D),s.mul(te,$)),F=s.mul(F,te),{Rx:M,Ry:$,Rz:F}}let U=Pv(d),R=k=>{if(!(k instanceof r))throw new TypeError('"point" expected G2 point, got type='+typeof k);let M=k,{x:$,y:F}=M.toAffine(),A=$,H=F,D=s.neg(F),q=A,j=H,K=s.ONE,W=[];for(let Z of U){let te=[];({Rx:q,Ry:j,Rz:K}=B(te,q,j,K)),Z&&({Rx:q,Ry:j,Rz:K}=N(te,q,j,K,A,Z===-1?D:H)),W.push(te)}if(u){let Z=W[W.length-1];u(q,j,K,A,H,N.bind(null,Z))}return W};function T(k,M=!1){Jt(k,"pairs",(F,A)=>{if(Jt(F,A),F.length!==3)throw new TypeError(`"${A}" expected precompute tuple`);Jt(F[0],A+"[0]")});let $=a.ONE;if(k.length){let F=k[0][0].length;for(let A=0;A<F;A++){A!==0&&($=a.sqr($));for(let[H,D,q]of k)for(let[j,K,W]of H[A])$=v(j,K,W,$,D,q)}}return f&&($=a.conjugate($)),M?a.finalExponentiate($):$}function O(k,M=!0){Jt(k,"pairs");let $=[];for(let F=0;F<k.length;F++){let A=k[F];Be(A,{g1:"object",g2:"object"},{},"pairs["+F+"]");let{g1:H,g2:D}=A;if(!(H instanceof t))throw new TypeError('"pairs['+F+'].g1" expected G1 point, got type='+typeof H);if(!(D instanceof r))throw new TypeError('"pairs['+F+'].g2" expected G2 point, got type='+typeof D);if(H.is0()||D.is0())throw new Error("pairing is not available for ZERO point");H.assertValidity(),D.assertValidity();let q=H.toAffine();$.push([R(D),q.x,q.y])}return T($,M)}function z(k,M,$=!0){if(!(k instanceof t))throw new TypeError('"Q" expected G1 point, got type='+typeof k);if(!(M instanceof r))throw new TypeError('"P" expected G2 point, got type='+typeof M);return O([{g1:k,g2:M}],$)}let P={seed:qi(i.ORDER)},_=n.randomBytes===void 0?lr:n.randomBytes,I=k=>(k=k===void 0?_(P.seed):k,se(k,P.seed,"seed"),ji(k,i.ORDER));return Object.freeze(P),{lengths:P,Fr:i,Fp12:a,millerLoopBatch:T,pairing:z,pairingBatch:O,calcPairingPrecomputes:R,randomSecretKey:I}}function sg(e,t,r,n,o,i){let{Fr:s,Fp12:a,pairingBatch:c,randomSecretKey:d,lengths:f}=e;i||(i={fromBytes:pr,fromHex:pr,toBytes:pr,toHex:pr});let u=Object.freeze({...i});function l(y){return y instanceof t?y:t.fromBytes(y)}function p(y){return y instanceof r?y:u.fromBytes(y)}function m(y){if(!(y instanceof r))throw new Error(`expected valid message hashed to ${n?"G1":"G2"} curve`);return y}let h=n?(y,b)=>({g1:b,g2:y}):(y,b)=>({g1:y,g2:b});return Object.freeze({lengths:Object.freeze({...f,secretKey:s.BYTES}),keygen(y){let b=d(y),x=this.getPublicKey(b);return{secretKey:b,publicKey:x}},getPublicKey(y){let b;try{b=t.Fn.fromBytes(y)}catch(x){throw new Error("invalid private key: "+typeof y,{cause:x})}return t.BASE.multiply(b)},sign(y,b,x){if(x!=null)throw new Error("sign() expects 2 arguments");let g=t.Fn.fromBytes(b);return m(y).assertValidity(),y.multiply(g)},verify(y,b,x,g){if(g!=null)throw new Error("verify() expects 3 arguments");y=p(y),x=l(x);let w=x.negate(),v=t.BASE,E=m(b),B=y;try{let N=c([h(w,E),h(v,B)]);return a.eql(N,a.ONE)}catch{return!1}},verifyBatch(y,b){x0(b);let x=p(y),g=b.map(N=>m(N.message)),w=b.map(N=>l(N.publicKey)),v=new Map;for(let N=0;N<w.length;N++){let U=w[N],R=g[N],T=v.get(R);T===void 0&&(T=[],v.set(R,T)),T.push(U)}let E=[],B=t.BASE;try{for(let[N,U]of v){let R=U.reduce((T,O)=>T.add(O));E.push(h(R,N))}return E.push(h(B.negate(),x)),a.eql(c(E),a.ONE)}catch{return!1}},aggregatePublicKeys(y){x0(y),y=y.map(x=>l(x));let b=y.reduce((x,g)=>x.add(g),t.ZERO);return b.assertValidity(),b},aggregateSignatures(y){x0(y),y=y.map(x=>p(x));let b=y.reduce((x,g)=>x.add(g),r.ZERO);return b.assertValidity(),b},hash(y,b){return se(y),o(y,b===void 0?void 0:{DST:b})},Signature:Object.freeze({...u})})}function Ov(e,t,r,n){let{Fp:o,Fr:i,Fp2:s,Fp6:a,Fp12:c}=e,d={Point:t},f={Point:r},u=Rv(e,t,r,n),{millerLoopBatch:l,pairing:p,pairingBatch:m,calcPairingPrecomputes:h,randomSecretKey:y,lengths:b}=u;return d.Point.BASE.precompute(4),Object.freeze(d),Object.freeze(f),Object.freeze({lengths:Object.freeze(b),millerLoopBatch:l,pairing:p,pairingBatch:m,G1:d,G2:f,fields:Object.freeze({Fr:i,Fp:o,Fp2:s,Fp6:a,Fp12:c}),params:Object.freeze({ateLoopSize:n.ateLoopSize,xNegative:n.xNegative,twistType:n.twistType,postPrecompute:n.postPrecompute}),utils:Object.freeze({randomSecretKey:y,calcPairingPrecomputes:h})})}function Cv(e,t,r,n,o){let i=Ov(e,t,r,n);Be(o,{hasherOpts:"object",hasherOptsG1:"object",hasherOptsG2:"object"},{mapToG1:"function",mapToG2:"function"},"hasherParams");let s=Qp(t,o.mapToG1===void 0?pr:o.mapToG1,{...o.hasherOpts,...o.hasherOptsG1}),a=Qp(r,o.mapToG2===void 0?pr:o.mapToG2,{...o.hasherOpts,...o.hasherOptsG2});return Object.freeze({...i,G1:s,G2:a})}function ag(e,t,r,n,o,i){let s=Cv(e,t,r,n,o),a={...s,Fr:s.fields.Fr,Fp12:s.fields.Fp12,calcPairingPrecomputes:s.utils.calcPairingPrecomputes,randomSecretKey:s.utils.randomSecretKey},c=sg(a,t,r,!1,s.G2.hashToCurve,i?.LongSignature),d=sg(a,r,t,!0,s.G1.hashToCurve,i?.ShortSignature);return Object.freeze({...s,longSignatures:c,shortSignatures:d})}var v0=BigInt(0),oo=BigInt(1),It=BigInt(2),cg=BigInt(3),Uv=BigInt(6),Nv=BigInt(12),oi=e=>!!e&&typeof e=="object";function fg(e,t,r,n,o=1,i){_e(o,"num"),_e(n,"degree");let s=i===void 0?n:i;_e(s,"divisor");let a=e;if(typeof r!="bigint"||r<=oo)throw new Error("calcFrobeniusCoefficients: expected valid modulus, got "+r);if(n<=0)throw new Error("calcFrobeniusCoefficients: expected positive degree, got "+n);if(o<=0)throw new Error("calcFrobeniusCoefficients: expected positive row count, got "+o);if(s<=0)throw new Error("calcFrobeniusCoefficients: expected positive divisor, got "+s);let c=BigInt(s),d=r**BigInt(n),f=[];for(let u=0;u<o;u++){let l=BigInt(u+1),p=[];for(let m=0,h=oo;m<n;m++){let y=l*h-l;if(y%c)throw new Error("calcFrobeniusCoefficients: inexact tower exponent");let b=y/c%d;p.push(a.pow(t,b)),h*=r}f.push(p)}return f}function ug(e,t,r){if(Ft(e),Ft(t),Be(t,{Fp:"object",frobeniusMap:"function",fromBigTuple:"function",mulByB:"function",mulByNonresidue:"function",reim:"function",Fp4Square:"function",NONRESIDUE:"object"},{}),!oi(r)||Array.isArray(r))throw new TypeError('"base" expected Fp2 element, got type='+typeof r);if(!t.isValid(r))throw new RangeError('"base" expected valid Fp2 element');let n=t.pow(r,(e.ORDER-oo)/cg),o=t.pow(r,(e.ORDER-oo)/It);function i(l,p){let m=t.mul(t.frobeniusMap(l,1),n),h=t.mul(t.frobeniusMap(p,1),o);return[m,h]}let s=t.pow(r,(e.ORDER**It-oo)/cg),a=t.pow(r,(e.ORDER**It-oo)/It);if(!t.eql(a,t.neg(t.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function c(l,p){return[t.mul(l,s),t.neg(p)]}let d=l=>(p,m)=>{if(typeof p!="function")throw new TypeError('"c" expected point constructor, got type='+typeof p);if(Mr(p),!(m instanceof p))throw new TypeError('"P" expected Point instance, got type='+typeof m);let h=m.toAffine(),y=l(h.x,h.y);return p.fromAffine({x:y[0],y:y[1]})},f=d(i),u=d(c);return{psi:i,psi2:c,G2psi:f,G2psi2:u,PSI_X:n,PSI_Y:o,PSI2_X:s,PSI2_Y:a}}var S0=class{ORDER;BITS;BYTES;isLE;ZERO;ONE;Fp;NONRESIDUE;mulByB;Fp_NONRESIDUE;Fp_div2;constructor(t,r={}){let{NONRESIDUE:n=BigInt(-1),FP2_NONRESIDUE:o,Fp2mulByB:i}=r,s=t.ORDER,a=s*s;this.Fp=t,this.ORDER=a,this.BITS=tr(a),this.BYTES=Math.ceil(tr(a)/8),this.isLE=t.isLE,this.ZERO=this.create({c0:t.ZERO,c1:t.ZERO}),this.ONE=this.create({c0:t.ONE,c1:t.ZERO}),this.Fp_NONRESIDUE=t.create(n),this.Fp_div2=t.div(t.ONE,It),this.NONRESIDUE=this.create({c0:o[0],c1:o[1]}),this.mulByB=c=>{let{c0:d,c1:f}=i(c);return Object.freeze({c0:d,c1:f})},Object.freeze(this)}fromBigTuple(t){if(!Array.isArray(t)||t.length!==2)throw new Error("invalid Fp2.fromBigTuple");let[r,n]=t;if(typeof r!="bigint"||typeof n!="bigint")throw new Error("invalid Fp2.fromBigTuple");return this.create({c0:r,c1:n})}create(t){let{Fp:r}=this,n=r.create(t.c0),o=r.create(t.c1);return Object.freeze({c0:n,c1:o})}isValid(t){if(!oi(t))throw new TypeError("invalid field element: expected object, got "+typeof t);let{c0:r,c1:n}=t,{Fp:o}=this;return o.isValid(r)&&o.isValid(n)}is0(t){if(!oi(t))return!1;let{c0:r,c1:n}=t,{Fp:o}=this;return o.is0(r)&&o.is0(n)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}eql({c0:t,c1:r},{c0:n,c1:o}){let{Fp:i}=this;return i.eql(t,n)&&i.eql(r,o)}neg({c0:t,c1:r}){let{Fp:n}=this;return Object.freeze({c0:n.neg(t),c1:n.neg(r)})}pow(t,r){return Fd(this,t,r)}invertBatch(t){return mr(this,t,!0)}add(t,r){let{Fp:n}=this,{c0:o,c1:i}=t,{c0:s,c1:a}=r;return Object.freeze({c0:n.add(o,s),c1:n.add(i,a)})}sub({c0:t,c1:r},{c0:n,c1:o}){let{Fp:i}=this;return Object.freeze({c0:i.sub(t,n),c1:i.sub(r,o)})}mul({c0:t,c1:r},n){let{Fp:o}=this;if(typeof n=="bigint")return Object.freeze({c0:o.mul(t,n),c1:o.mul(r,n)});let{c0:i,c1:s}=n,a=o.mul(t,i),c=o.mul(r,s),d=o.sub(a,c),f=o.sub(o.mul(o.add(t,r),o.add(i,s)),o.add(a,c));return Object.freeze({c0:d,c1:f})}sqr({c0:t,c1:r}){let{Fp:n}=this,o=n.add(t,r),i=n.sub(t,r),s=n.add(t,t);return Object.freeze({c0:n.mul(o,i),c1:n.mul(s,r)})}addN(t,r){return this.add(t,r)}subN(t,r){return this.sub(t,r)}mulN(t,r){return this.mul(t,r)}sqrN(t){return this.sqr(t)}div(t,r){let{Fp:n}=this;return this.mul(t,typeof r=="bigint"?n.inv(n.create(r)):this.inv(r))}inv({c0:t,c1:r}){let{Fp:n}=this,o=n.inv(n.create(t*t+r*r));return Object.freeze({c0:n.mul(o,n.create(t)),c1:n.mul(o,n.create(-r))})}sqrt(t){let{Fp:r}=this,n=this,{c0:o,c1:i}=t;if(r.is0(i))return pn(r,o)===1?n.create({c0:r.sqrt(o),c1:r.ZERO}):n.create({c0:r.ZERO,c1:r.sqrt(r.div(o,this.Fp_NONRESIDUE))});let s=r.sqrt(r.sub(r.sqr(o),r.mul(r.sqr(i),this.Fp_NONRESIDUE))),a=r.mul(r.add(s,o),this.Fp_div2);pn(r,a)===-1&&(a=r.sub(a,s));let d=r.sqrt(a),f=n.create({c0:d,c1:r.div(r.mul(i,this.Fp_div2),d)});if(!n.eql(n.sqr(f),t))throw new Error("Cannot find square root");let u=f,l=n.neg(u),{re:p,im:m}=n.reim(u),{re:h,im:y}=n.reim(l);return m>y||m===y&&p>h?u:l}isOdd(t){let{re:r,im:n}=this.reim(t),o=r%It,i=r===v0,s=n%It;return BigInt(o||i&&s)==oo}fromBytes(t){let{Fp:r}=this;if(se(t),t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);return this.create({c0:r.fromBytes(t.subarray(0,r.BYTES)),c1:r.fromBytes(t.subarray(r.BYTES))})}toBytes({c0:t,c1:r}){return ke(this.Fp.toBytes(t),this.Fp.toBytes(r))}cmov({c0:t,c1:r},{c0:n,c1:o},i){let{Fp:s}=this;return this.create({c0:s.cmov(t,n,i),c1:s.cmov(r,o,i)})}reim({c0:t,c1:r}){return{re:t,im:r}}Fp4Square(t,r){let n=this,o=n.sqr(t),i=n.sqr(r);return{first:n.add(n.mulByNonresidue(i),o),second:n.sub(n.sub(n.sqr(n.add(t,r)),o),i)}}mulByNonresidue({c0:t,c1:r}){let{Fp:n,NONRESIDUE:o}=this;return o.c0===n.ONE&&o.c1===n.ONE?Object.freeze({c0:n.sub(t,r),c1:n.add(t,r)}):o.c1===n.ONE?Object.freeze({c0:n.sub(n.mul(t,o.c0),r),c1:n.add(t,n.mul(r,o.c0))}):this.mul({c0:t,c1:r},o)}frobeniusMap(t,r){let{c0:n,c1:o}=t,{Fp:i}=this;return Object.freeze({c0:n,c1:r%2===0?o:i.neg(o)})}},E0=class{ORDER;BITS;BYTES;isLE;ZERO;ONE;Fp2;constructor(t){this.Fp2=t,this.ORDER=t.Fp.ORDER**Uv,this.BITS=3*t.BITS,this.BYTES=3*t.BYTES,this.isLE=t.isLE,this.ZERO=this.create({c0:t.ZERO,c1:t.ZERO,c2:t.ZERO}),this.ONE=this.create({c0:t.ONE,c1:t.ZERO,c2:t.ZERO}),Object.freeze(this)}get FROBENIUS_COEFFICIENTS_1(){let t=Zd.get(this);if(t)return t[0];let{Fp2:r}=this,{Fp:n}=r,o=fg(r,r.NONRESIDUE,n.ORDER,6,2,3),i=[Object.freeze(o[0]),Object.freeze(o[1])];return Zd.set(this,i),i[0]}get FROBENIUS_COEFFICIENTS_2(){let t=Zd.get(this);return t?t[1]:(this.FROBENIUS_COEFFICIENTS_1,Zd.get(this)[1])}add({c0:t,c1:r,c2:n},{c0:o,c1:i,c2:s}){let{Fp2:a}=this;return Object.freeze({c0:a.add(t,o),c1:a.add(r,i),c2:a.add(n,s)})}sub({c0:t,c1:r,c2:n},{c0:o,c1:i,c2:s}){let{Fp2:a}=this;return Object.freeze({c0:a.sub(t,o),c1:a.sub(r,i),c2:a.sub(n,s)})}mul({c0:t,c1:r,c2:n},o){let{Fp2:i}=this;if(typeof o=="bigint")return Object.freeze({c0:i.mul(t,o),c1:i.mul(r,o),c2:i.mul(n,o)});let{c0:s,c1:a,c2:c}=o,d=i.mul(t,s),f=i.mul(r,a),u=i.mul(n,c);return Object.freeze({c0:i.add(d,i.mulByNonresidue(i.sub(i.mul(i.add(r,n),i.add(a,c)),i.add(f,u)))),c1:i.add(i.sub(i.mul(i.add(t,r),i.add(s,a)),i.add(d,f)),i.mulByNonresidue(u)),c2:i.sub(i.add(f,i.mul(i.add(t,n),i.add(s,c))),i.add(d,u))})}sqr({c0:t,c1:r,c2:n}){let{Fp2:o}=this,i=o.sqr(t),s=o.mul(o.mul(t,r),It),a=o.mul(o.mul(r,n),It),c=o.sqr(n);return Object.freeze({c0:o.add(o.mulByNonresidue(a),i),c1:o.add(o.mulByNonresidue(c),s),c2:o.sub(o.sub(o.add(o.add(s,o.sqr(o.add(o.sub(t,r),n))),a),i),c)})}addN(t,r){return this.add(t,r)}subN(t,r){return this.sub(t,r)}mulN(t,r){return this.mul(t,r)}sqrN(t){return this.sqr(t)}create(t){let{Fp2:r}=this,n=r.create(t.c0),o=r.create(t.c1),i=r.create(t.c2);return Object.freeze({c0:n,c1:o,c2:i})}isValid(t){if(!oi(t))throw new TypeError("invalid field element: expected object, got "+typeof t);let{c0:r,c1:n,c2:o}=t,{Fp2:i}=this;return i.isValid(r)&&i.isValid(n)&&i.isValid(o)}is0(t){if(!oi(t))return!1;let{c0:r,c1:n,c2:o}=t,{Fp2:i}=this;return i.is0(r)&&i.is0(n)&&i.is0(o)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}neg({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return Object.freeze({c0:o.neg(t),c1:o.neg(r),c2:o.neg(n)})}eql({c0:t,c1:r,c2:n},{c0:o,c1:i,c2:s}){let{Fp2:a}=this;return a.eql(t,o)&&a.eql(r,i)&&a.eql(n,s)}sqrt(t){return pr()}div(t,r){let{Fp2:n}=this,{Fp:o}=n;return this.mul(t,typeof r=="bigint"?o.inv(o.create(r)):this.inv(r))}pow(t,r){return Fd(this,t,r)}invertBatch(t){return mr(this,t,!0)}inv({c0:t,c1:r,c2:n}){let{Fp2:o}=this,i=o.sub(o.sqr(t),o.mulByNonresidue(o.mul(n,r))),s=o.sub(o.mulByNonresidue(o.sqr(n)),o.mul(t,r)),a=o.sub(o.sqr(r),o.mul(t,n)),c=o.inv(o.add(o.mulByNonresidue(o.add(o.mul(n,s),o.mul(r,a))),o.mul(t,i)));return Object.freeze({c0:o.mul(c,i),c1:o.mul(c,s),c2:o.mul(c,a)})}fromBytes(t){let{Fp2:r}=this;if(se(t),t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);let n=r.BYTES;return this.create({c0:r.fromBytes(t.subarray(0,n)),c1:r.fromBytes(t.subarray(n,n*2)),c2:r.fromBytes(t.subarray(2*n))})}toBytes({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return ke(o.toBytes(t),o.toBytes(r),o.toBytes(n))}cmov({c0:t,c1:r,c2:n},{c0:o,c1:i,c2:s},a){let{Fp2:c}=this;return this.create({c0:c.cmov(t,o,a),c1:c.cmov(r,i,a),c2:c.cmov(n,s,a)})}fromBigSix(t){let{Fp2:r}=this;if(!Array.isArray(t)||t.length!==6)throw new Error("invalid Fp6.fromBigSix");for(let o=0;o<6;o++)if(typeof t[o]!="bigint")throw new Error("invalid Fp6.fromBigSix");let n=t;return this.create({c0:r.fromBigTuple(n.slice(0,2)),c1:r.fromBigTuple(n.slice(2,4)),c2:r.fromBigTuple(n.slice(4,6))})}frobeniusMap(t,r){let{c0:n,c1:o,c2:i}=t;if(r%6===0)return Object.freeze({c0:n,c1:o,c2:i});let{Fp2:s}=this;return Object.freeze({c0:s.frobeniusMap(n,r),c1:s.mul(s.frobeniusMap(o,r),this.FROBENIUS_COEFFICIENTS_1[r%6]),c2:s.mul(s.frobeniusMap(i,r),this.FROBENIUS_COEFFICIENTS_2[r%6])})}mulByFp2({c0:t,c1:r,c2:n},o){let{Fp2:i}=this;return Object.freeze({c0:i.mul(t,o),c1:i.mul(r,o),c2:i.mul(n,o)})}mulByNonresidue({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return Object.freeze({c0:o.mulByNonresidue(n),c1:t,c2:r})}mul1({c0:t,c1:r,c2:n},o){let{Fp2:i}=this;return Object.freeze({c0:i.mulByNonresidue(i.mul(n,o)),c1:i.mul(t,o),c2:i.mul(r,o)})}mul01({c0:t,c1:r,c2:n},o,i){let{Fp2:s}=this,a=s.mul(t,o),c=s.mul(r,i);return Object.freeze({c0:s.add(s.mulByNonresidue(s.sub(s.mul(s.add(r,n),i),c)),a),c1:s.sub(s.sub(s.mul(s.add(o,i),s.add(t,r)),a),c),c2:s.add(s.sub(s.mul(s.add(t,n),o),a),c)})}},Zd=new WeakMap,_0=class{ORDER;BITS;BYTES;isLE;ZERO;ONE;Fp6;X_LEN;finalExponentiate;constructor(t,r){let{X_LEN:n,Fp12finalExponentiate:o}=r,{Fp2:i}=t,{Fp:s}=i;this.Fp6=t,this.ORDER=s.ORDER**Nv,this.BITS=2*t.BITS,this.BYTES=2*t.BYTES,this.isLE=t.isLE,this.ZERO=this.create({c0:t.ZERO,c1:t.ZERO}),this.ONE=this.create({c0:t.ONE,c1:t.ZERO}),this.X_LEN=n,this.finalExponentiate=a=>{let c=({c0:u,c1:l})=>Object.freeze({c0:u,c1:l}),d=({c0:u,c1:l,c2:p})=>Object.freeze({c0:c(u),c1:c(l),c2:c(p)}),f=o(a);return Object.freeze({c0:d(f.c0),c1:d(f.c1)})},Object.freeze(this)}get FROBENIUS_COEFFICIENTS(){let t=dg.get(this);if(t)return t;let{Fp2:r}=this.Fp6,{Fp:n}=r,o=Object.freeze(fg(r,r.NONRESIDUE,n.ORDER,12,1,6)[0]);return dg.set(this,o),o}create(t){let{Fp6:r}=this,n=r.create(t.c0),o=r.create(t.c1);return Object.freeze({c0:n,c1:o})}isValid(t){if(!oi(t))throw new TypeError("invalid field element: expected object, got "+typeof t);let{c0:r,c1:n}=t,{Fp6:o}=this;return o.isValid(r)&&o.isValid(n)}is0(t){if(!oi(t))return!1;let{c0:r,c1:n}=t,{Fp6:o}=this;return o.is0(r)&&o.is0(n)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}neg({c0:t,c1:r}){let{Fp6:n}=this;return Object.freeze({c0:n.neg(t),c1:n.neg(r)})}eql({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:i}=this;return i.eql(t,n)&&i.eql(r,o)}sqrt(t){return pr()}inv({c0:t,c1:r}){let{Fp6:n}=this,o=n.inv(n.sub(n.sqr(t),n.mulByNonresidue(n.sqr(r))));return Object.freeze({c0:n.mul(t,o),c1:n.neg(n.mul(r,o))})}div(t,r){let{Fp6:n}=this,{Fp2:o}=n,{Fp:i}=o;return this.mul(t,typeof r=="bigint"?i.inv(i.create(r)):this.inv(r))}pow(t,r){return Fd(this,t,r)}invertBatch(t){return mr(this,t,!0)}add({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:i}=this;return Object.freeze({c0:i.add(t,n),c1:i.add(r,o)})}sub({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:i}=this;return Object.freeze({c0:i.sub(t,n),c1:i.sub(r,o)})}mul({c0:t,c1:r},n){let{Fp6:o}=this;if(typeof n=="bigint")return Object.freeze({c0:o.mul(t,n),c1:o.mul(r,n)});let{c0:i,c1:s}=n,a=o.mul(t,i),c=o.mul(r,s);return Object.freeze({c0:o.add(a,o.mulByNonresidue(c)),c1:o.sub(o.mul(o.add(t,r),o.add(i,s)),o.add(a,c))})}sqr({c0:t,c1:r}){let{Fp6:n}=this,o=n.mul(t,r);return Object.freeze({c0:n.sub(n.sub(n.mul(n.add(n.mulByNonresidue(r),t),n.add(t,r)),o),n.mulByNonresidue(o)),c1:n.add(o,o)})}addN(t,r){return this.add(t,r)}subN(t,r){return this.sub(t,r)}mulN(t,r){return this.mul(t,r)}sqrN(t){return this.sqr(t)}fromBytes(t){let{Fp6:r}=this;if(se(t),t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);return this.create({c0:r.fromBytes(t.subarray(0,r.BYTES)),c1:r.fromBytes(t.subarray(r.BYTES))})}toBytes({c0:t,c1:r}){let{Fp6:n}=this;return ke(n.toBytes(t),n.toBytes(r))}cmov({c0:t,c1:r},{c0:n,c1:o},i){let{Fp6:s}=this;return this.create({c0:s.cmov(t,n,i),c1:s.cmov(r,o,i)})}fromBigTwelve(t){let{Fp6:r}=this;if(!Array.isArray(t)||t.length!==12)throw new Error("invalid Fp12.fromBigTwelve");for(let o=0;o<12;o++)if(typeof t[o]!="bigint")throw new Error("invalid Fp12.fromBigTwelve");let n=t;return this.create({c0:r.fromBigSix(n.slice(0,6)),c1:r.fromBigSix(n.slice(6,12))})}frobeniusMap(t,r){let n=r%12;if(n===0)return Object.freeze({c0:t.c0,c1:t.c1});if(n===6)return this.conjugate(t);let{Fp6:o}=this,{Fp2:i}=o,{c0:s,c1:a,c2:c}=o.frobeniusMap(t.c1,r),d=this.FROBENIUS_COEFFICIENTS[n];return Object.freeze({c0:o.frobeniusMap(t.c0,r),c1:Object.freeze({c0:i.mul(s,d),c1:i.mul(a,d),c2:i.mul(c,d)})})}mulByFp2({c0:t,c1:r},n){let{Fp6:o}=this;return Object.freeze({c0:o.mulByFp2(t,n),c1:o.mulByFp2(r,n)})}conjugate({c0:t,c1:r}){return Object.freeze({c0:t,c1:this.Fp6.neg(r)})}_cyclotomicSquare({c0:t,c1:r}){let{Fp6:n}=this,{Fp2:o}=n,{c0:i,c1:s,c2:a}=t,{c0:c,c1:d,c2:f}=r,{first:u,second:l}=o.Fp4Square(i,d),{first:p,second:m}=o.Fp4Square(c,a),{first:h,second:y}=o.Fp4Square(s,f),b=o.mulByNonresidue(y);return Object.freeze({c0:Object.freeze({c0:o.add(o.mul(o.sub(u,i),It),u),c1:o.add(o.mul(o.sub(p,s),It),p),c2:o.add(o.mul(o.sub(h,a),It),h)}),c1:Object.freeze({c0:o.add(o.mul(o.add(b,c),It),b),c1:o.add(o.mul(o.add(l,d),It),l),c2:o.add(o.mul(o.add(m,f),It),m)})})}_cyclotomicExp(t,r){if(Xn("cyclotomic exponent",r,v0,oo<<BigInt(this.X_LEN)),r===v0)return this.ONE;let n=t;for(let o=tr(r)-2;o>=0;o--)n=this._cyclotomicSquare(n),tb(r,o)&&(n=this.mul(n,t));return n}},dg=new WeakMap;function lg(e){if(Be(e,{ORDER:"bigint",X_LEN:"number",FP2_NONRESIDUE:"object",Fp2mulByB:"function",Fp12finalExponentiate:"function"},{NONRESIDUE:"bigint"}),_e(e.X_LEN,"X_LEN"),e.X_LEN<1)throw new Error("invalid X_LEN");let t=e.FP2_NONRESIDUE;if(!Array.isArray(t)||t.length!==2)throw new Error("invalid FP2_NONRESIDUE");if(typeof t[0]!="bigint"||typeof t[1]!="bigint")throw new Error("invalid FP2_NONRESIDUE");let r=Fr(e.ORDER),n=new S0(r,e),o=new E0(n),i=new _0(o,e);return{Fp:r,Fp2:n,Fp6:o,Fp12:i}}var P0=BigInt(0),pg=BigInt(1),Yd=BigInt(2),Ji=BigInt(3),Qi=BigInt(4),ii=BigInt("0xd201000000010000"),Fv=tr(ii),rc={p:BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),n:BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"),h:BigInt("0x396c8c005555e1568c00aaab0000aaab"),a:P0,b:Qi,Gx:BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),Gy:BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1")},R0=Fr(rc.n,{modFromBytes:!0});function Mv(e,t,{g2:r,g3:n,g4:o,g5:i}){return{c0:{c0:e,c1:o,c2:n},c1:{c0:r,c1:t,c2:i}}}function zv({c0:e,c1:t}){return{g2:t.c0,g3:e.c2,g4:e.c1,g5:t.c2}}function Hv({g2:e,g3:t,g4:r,g5:n}){let{first:o,second:i}=ee.Fp4Square(r,n),{first:s,second:a}=ee.Fp4Square(e,t),c=ee.add(e,e),d=ee.add(t,t),f=ee.add(r,r),u=ee.add(n,n);return{g2:ee.add(ee.mul(ee.mulByNonresidue(i),Ji),c),g3:ee.sub(ee.mul(o,Ji),d),g4:ee.sub(ee.mul(s,Ji),f),g5:ee.add(ee.mul(a,Ji),u)}}function $v({g2:e,g3:t,g4:r,g5:n}){return ee.is0(e)?{num:ee.mul(ee.mul(r,n),Yd),den:t}:{num:ee.add(ee.sub(ee.mul(ee.sqr(r),Ji),ee.mul(t,Yd)),ee.mulByNonresidue(ee.sqr(n))),den:ee.mul(e,Qi)}}function Lv(e,{g2:t,g3:r,g4:n,g5:o}){let i=ee.mul(r,n),s=ee.add(ee.sub(ee.mul(ee.sub(ee.sqr(e),i),Yd),i),ee.mul(t,o));return ee.add(ee.mulByNonresidue(s),ee.ONE)}function Dv(e,t){let r=[],n=zv(e);for(let c of t){for(let d=0;d<c;d++)n=Hv(n);r.push(n)}let o=r.map(({g2:c,g3:d})=>ee.is0(c)&&ee.is0(d)),i=r.map($v),s=ee.invertBatch(i.map(({den:c})=>c)),a=r.map((c,d)=>{if(o[d])return ye.ONE;let f=ee.mul(i[d].num,s[d]);return Mv(Lv(f,c),f,c)});return{result:ye.mul(ye.mul(a[0],a[1]),a[2]),last:a[2]}}function qv(e){let{result:t,last:r}=Dv(e,[16,32,9]),n=t,o=r;for(let i=0;i<3;i++)o=ye._cyclotomicSquare(o);n=ye.mul(n,o);for(let i=0;i<2;i++)o=ye._cyclotomicSquare(o);return n=ye.mul(n,o),o=ye._cyclotomicSquare(o),ye.mul(n,o)}var{Fp:Ie,Fp2:ee,Fp6:jv,Fp12:ye}=lg({ORDER:rc.p,X_LEN:Fv,FP2_NONRESIDUE:[pg,pg],Fp2mulByB:({c0:e,c1:t})=>{let r=Ie.mul(e,Qi),n=Ie.mul(t,Qi);return{c0:Ie.sub(r,n),c1:Ie.add(r,n)}},Fp12finalExponentiate:e=>{let t=m=>ye.conjugate(qv(m)),r=ye.div(ye.frobeniusMap(e,6),e),n=ye.mul(ye.frobeniusMap(r,2),r),o=t(n),i=ye.mul(ye.conjugate(ye._cyclotomicSquare(n)),o),s=t(i),a=t(s),c=ye.mul(t(a),ye._cyclotomicSquare(o)),d=t(c),f=ye.frobeniusMap(ye.mul(o,a),2),u=ye.frobeniusMap(ye.mul(s,n),3),l=ye.frobeniusMap(ye.mul(c,ye.conjugate(n)),1),p=ye.mul(ye.mul(d,ye.conjugate(i)),n);return ye.mul(ye.mul(ye.mul(f,u),l),p)}}),mg,_g=()=>mg||(mg=ug(Ie,ee,ee.div(ee.ONE,ee.NONRESIDUE))),k0=(e,t)=>{let r=_g().G2psi;return k0=r,r(e,t)},Ag=(e,t)=>{let r=_g().G2psi2;return Ag=r,r(e,t)},A0=Object.freeze({DST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",encodeDST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",p:Ie.ORDER,m:2,k:128,expand:"xmd",hash:ur}),Tg={p:ee.ORDER,n:rc.n,h:BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),a:ee.ZERO,b:ee.fromBigTuple([Qi,Qi]),Gx:ee.fromBigTuple([BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")]),Gy:ee.fromBigTuple([BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")])},hg=(e,t)=>{for(let r of e)if(r!==P0)return!!(r*Yd/t);return!1},yg={encode({c0:e,c1:t}){let{BYTES:r}=Ie;return ke(Yn(t,r),Yn(e,r))},decode(e){let{BYTES:t}=Ie;return ee.create({c0:B0(e.subarray(t)),c1:B0(e.subarray(0,t))})}},bg=Ie;function B0(e){return Ie.fromBytes(e)}var Ig=(e,t,r,n,o,i)=>{let s=t,a=n,c=o,d=s.BYTES;return f=>({encode(u,l=!0){if(!l&&!f)throw new Error("invalid signature: expected compressed encoding");let p=u.is0(),{x:m,y:h}=u.toAffine(),y=l?a(m):ke(a(m),a(h)),b;return l&&!p&&(b=hg(i(h),bg.ORDER)),Vv(y,{compressed:l,infinity:p,sort:b})},decode(u){let l=f?se(u,void 0,"point"):se(u,d,"signature"),{compressed:p,infinity:m,sort:h,value:y}=Gv(l);if(!f&&!p)throw new Error("invalid signature: expected compressed encoding");let b=p?d:2*d;if(y.length!==b)throw new Error(`invalid ${e} point: expected ${b} bytes`);if(m){for(let w of y)if(w)throw new Error(`invalid ${e} point: non-canonical zero`);return{x:s.ZERO,y:s.ZERO}}let x=c(p?y:y.subarray(0,d)),g;if(p){if(g=s.sqrt(s.add(s.pow(x,Ji),r)),!g)throw new Error(`invalid ${e} point: compressed`);hg(i(g),bg.ORDER)!==h&&(g=s.neg(g))}else g=c(y.subarray(d));if(!p&&s.is0(x)&&s.is0(g))throw new Error(`invalid ${e} point: uncompressed`);return{x,y:g}}})};function kg({compressed:e,infinity:t,sort:r}){if(!e&&!t&&r||!e&&t&&r||e&&t&&r)throw new Error("invalid encoding flag")}function Gv(e){e=Nr(e);let t=e[0]&224,r=!!(t>>7&1),n=!!(t>>6&1),o=!!(t>>5&1);return kg({compressed:r,infinity:n,sort:o}),e[0]&=31,{compressed:r,infinity:n,sort:o,value:e}}function Vv(e,t){if(e[0]&224)throw new Error("setMask: non-empty mask");return kg({compressed:!!t.compressed,infinity:!!t.infinity,sort:!!t.sort}),t.compressed&&(e[0]|=128),t.infinity&&(e[0]|=64),t.sort&&(e[0]|=32),e}var gg=Ig("G1",Ie,Ie.create(rc.b),e=>Yn(e,Ie.BYTES),B0,e=>[e]),Xd={point:gg(!0),sig:gg(!1)},T0=e=>(e.assertValidity(),Xd.sig.encode(e));function wg(e){let r=kt.G1.Point.fromAffine(Xd.sig.decode(e));return r.assertValidity(),r}var xg=Ig("G2",ee,Tg.b,yg.encode,yg.decode,e=>[e.c1,e.c0]),Jd={point:xg(!0),sig:xg(!1)},I0=e=>(e.assertValidity(),Jd.sig.encode(e));function vg(e){let r=kt.G2.Point.fromAffine(Jd.sig.decode(e));return r.assertValidity(),r}var Kv={ShortSignature:{fromBytes(e){return wg(se(e))},fromHex(e){return wg(ln(e))},toBytes(e){return T0(e)},toRawBytes(e){return T0(e)},toHex(e){return Zn(T0(e))}},LongSignature:{fromBytes(e){return vg(se(e))},fromHex(e){return vg(ln(e))},toBytes(e){return I0(e)},toRawBytes(e){return I0(e)},toHex(e){return Zn(I0(e))}}},Wv={Fp:Ie,Fp2:ee,Fp6:jv,Fp12:ye,Fr:R0},Zv=Va(rc,{allowInfinityPoint:!0,Fn:R0,fromBytes:Xd.point.decode,toBytes:(e,t,r)=>Xd.point.encode(t,r),isTorsionFree:(e,t)=>{let r=BigInt("0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe"),n=new e(Ie.mul(t.X,r),t.Y,t.Z);return t.multiplyUnsafe(ii).negate().multiplyUnsafe(ii).equals(n)},clearCofactor:(e,t)=>t.multiplyUnsafe(ii).add(t)}),Yv=Va(Tg,{Fp:ee,allowInfinityPoint:!0,Fn:R0,fromBytes:Jd.point.decode,toBytes:(e,t,r)=>Jd.point.encode(t,r),isTorsionFree:(e,t)=>t.multiplyUnsafe(ii).negate().equals(k0(e,t)),clearCofactor:(e,t)=>{let r=ii,n=t.multiplyUnsafe(r).negate(),o=k0(e,t),i=t.double();return i=Ag(e,i),i=i.subtract(o),o=n.add(o),o=o.multiplyUnsafe(r).negate(),i=i.add(o),i=i.subtract(n),i.subtract(t)}}),Xv={mapToG1:nS,mapToG2:oS,hasherOpts:A0,hasherOptsG1:{...A0,m:1,DST:"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_",encodeDST:"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_"},hasherOptsG2:{...A0}},Jv={ateLoopSize:ii,xNegative:!0,twistType:"multiplicative",randomBytes:lr},kt=ag(Wv,Zv,Yv,Jv,Xv,Kv),Qv=Jp(ee,[[["0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6"],["0x0","0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d"],["0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1","0x0"]],[["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63"],["0xc","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f"],["0x1","0x0"]],[["0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706","0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706"],["0x0","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f"],["0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10","0x0"]],[["0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb"],["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3"],["0x12","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99"],["0x1","0x0"]]].map(e=>e.map(t=>ee.fromBigTuple(t.map(BigInt))))),eS=Jp(Ie,[["0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7","0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb","0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0","0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861","0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9","0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983","0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84","0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e","0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317","0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e","0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b","0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229"],["0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c","0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff","0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19","0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8","0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e","0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5","0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a","0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e","0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641","0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"],["0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33","0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696","0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6","0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb","0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb","0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0","0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2","0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29","0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587","0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30","0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132","0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e","0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8","0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133","0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b","0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604"],["0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1","0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d","0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2","0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416","0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d","0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac","0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c","0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9","0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a","0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55","0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8","0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092","0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc","0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7","0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),Sg,Eg,tS=()=>Sg||(Sg=e0(Ie,{A:Ie.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),B:Ie.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),Z:Ie.create(BigInt(11))})),rS=()=>Eg||(Eg=e0(ee,{A:ee.create({c0:Ie.create(P0),c1:Ie.create(BigInt(240))}),B:ee.create({c0:Ie.create(BigInt(1012)),c1:Ie.create(BigInt(1012))}),Z:ee.create({c0:Ie.create(BigInt(-2)),c1:Ie.create(BigInt(-1))})}));function nS(e){let{x:t,y:r}=tS()(Ie.create(e[0]));return eS(t,r)}function oS(e){let{x:t,y:r}=rS()(ee.fromBigTuple(e));return Qv(t,r)}function io(e){let t=G(e,48),r=kt.G1.Point.fromBytes(t);if(r.is0()||!r.isTorsionFree()||Y(r.toBytes(!0))!==e)throw new TypeError("invalid buyer key");return t}function iS(e,t={}){if(ae(e,["version","refund","network","contract","route","asset","file_id","terms_hash","price","nonce","buyer_key","recovery","expires_at"]),e.version!==2||e.route!=="near-usdc"&&e.route!=="base-usdc")throw new TypeError("invalid purchase version/route");if(e.route==="near-usdc"){if(Gn(e.network),be(e.asset),(t.nearUsdc!==void 0||e.network==="near:mainnet")&&e.asset!==(t.nearUsdc??Ki))throw new TypeError("invalid NEAR asset")}else{if(e.network!=="eip155:8453"||e.asset!==(t.baseUsdc??l0))throw new TypeError("invalid Base network/asset");G(e.asset,20)}be(e.contract);let r=_t(e.price,128);if(r===0n)throw new RangeError("price must be positive");return Et(je(2,1),Tt(e.refund),At(e.network),At(e.contract),je(e.route==="near-usdc"?0:1,1),At(e.asset),G(e.file_id,32),G(e.terms_hash,32),je(r,16),G(e.nonce,32),io(e.buyer_key),Tt(e.recovery),je(_t(e.expires_at,64),8))}var gn=(e,t)=>Pd("annon/purchase/v2",iS(e,t)),Qd=e=>Y(Pe(Et(et.encode("annon/base-payment/v2"),je(0,1),G(e,32))));function $r(e,t){let r=gn(e,t),n=JSON.stringify({annon:2,refund:ne(e.refund),purchase:{network:e.network,contract:e.contract,route:e.route,asset:e.asset,file_id:e.file_id,terms_hash:e.terms_hash,price:e.price,nonce:e.nonce,buyer_key:e.buyer_key,recovery:ne(e.recovery),expires_at:e.expires_at,purchase_id:r}});if(et.encode(n).length>1024)throw new RangeError("purchase message exceeds 1024 UTF-8 bytes");return n}function sS(e){if(typeof e!="string")throw new TypeError("expected message string");let t=e.slice(0,160),r=/^\{"annon":2,"refund":(\{"kind":"(?:evm|solana|near)","id":"[a-zA-Z0-9._-]+"\}),/.exec(t);if(!r)throw new TypeError("invalid refund prefix");let n=r[1],o=ne(JSON.parse(n));if(Q(o)!==n||et.encode(r[0]).length>160)throw new TypeError("noncanonical refund prefix");return o}function es(e,t){if(typeof e!="string"||e.length>1024||et.encode(e).length>1024)throw new RangeError("purchase message exceeds 1024 UTF-8 bytes");let r=sS(e),n=JSON.parse(e);if(ae(n,["annon","refund","purchase"]),n.annon!==2)throw new TypeError("invalid annon version");let o=n.purchase;ae(o,["network","contract","route","asset","file_id","terms_hash","price","nonce","buyer_key","recovery","expires_at","purchase_id"]);let i={version:2,refund:r,network:o.network,contract:o.contract,route:o.route,asset:o.asset,file_id:o.file_id,terms_hash:o.terms_hash,price:o.price,nonce:o.nonce,buyer_key:o.buyer_key,recovery:ne(o.recovery),expires_at:o.expires_at};if($r(i,t)!==e)throw new TypeError("noncanonical purchase message or incorrect purchase_id");return i}function Bg(e){return be(e.contract),G(e.purchase_id,32),G(e.file_id,32),io(e.fresh_key),G(e.nonce,32),["Annon: open a purchased file again",`contract: ${e.contract}`,`purchase: ${e.purchase_id}`,`file: ${e.file_id}`,`recovery: ${Ke(e.recovery)}`,`new key: ${e.fresh_key}`,`nonce: ${e.nonce}`,`valid until: ${Vn(e.deadline)}`].join(`
47
- `)}var ts=class extends S{code;constructor(t,r=t){super(t,r),this.code=t,this.name="NearError"}},nc=class extends ts{constructor(t="NEAR RPC rate limited (429)"){super("near_rpc_rate_limited",t),this.name="NearRpcRateLimited"}},si=(e,t)=>{throw new ts(e,t)},He=e=>si("transport",`malformed RPC answer: ${e}`),aS=e=>btoa(String.fromCharCode(...new TextEncoder().encode(e))),Pg=e=>new TextDecoder().decode(Uint8Array.from(atob(e),t=>t.charCodeAt(0))),C0=2e4,cS=0;async function dS(e,t,r){let n=`annon-${++cS}`,o,i,s=new AbortController,a=setTimeout(()=>s.abort(new Error("timed out")),C0);try{i=await fetch(e,{credentials:"omit",method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:n,method:t,params:r}),signal:s.signal});let c=()=>{if(i.status===429)throw new nc("NEAR RPC HTTP 429: rate limited (429)");return si("transport",`NEAR RPC HTTP ${i.status}`)};try{o=await i.json()}catch(d){if(!i.ok)return c();throw d}if(i.status===429||!i.ok&&(!o||typeof o!="object"||Array.isArray(o)||o.jsonrpc!=="2.0"&&o.id!==n||!("result"in o)&&!("error"in o)))return c()}catch(c){if(c instanceof ts)throw c;return si("transport",`NEAR RPC unreachable: ${c.message}`)}finally{clearTimeout(a)}if(o?.error?.code===-429)throw new nc;return o?.id!==n?He("a reply to another request"):o}async function ef(e,t,r){let n=await dS(e,t,r);if(n.error){let o=JSON.stringify(n.error.cause?.info??n.error.data??n.error.message);["CONTRACT_EXECUTION_ERROR","UNKNOWN_ACCESS_KEY","UNKNOWN_ACCOUNT"].includes(n.error.cause?.name??"")&&si("refused",o),si("transport",`NEAR RPC error: ${o}`)}return typeof n?.result!="object"||n.result===null?He("no result"):n.result}async function Lr(e,t,r,n,o){let i=await ef(e,"query",{request_type:"call_function",...o===void 0?{finality:"final"}:{block_id:o},account_id:t,method_name:r,args_base64:aS(JSON.stringify(n))});typeof i.error=="string"&&si("refused",i.error);let s=i.result;if(!Array.isArray(s)||!s.every(a=>Number.isInteger(a)&&a>=0&&a<=255))return He("view bytes");try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(s)))}catch{return He("view bytes are not JSON")}}var oc=(e,t)=>typeof e=="string"&&new RegExp(`^0x[0-9a-f]{${2*t}}$`).test(e),O0=e=>typeof e=="string"&&/^(?=.{2,64}$)(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a-z\d]+$/.test(e),fS=["illegal_content","court_order","rights_holder_notice"];async function ai(e,t,r,n){let o=await Lr(e,t,"get_file",{file_id:r},n);if(o===null)return null;try{let s=tt(o.terms,{nearUsdc:o.terms.near.token,...o.terms.base?{baseUsdc:o.terms.base.usdc}:{}});if(o.terms_hash!==s)throw new Error;if(o.purchase_storage_balance!==void 0&&(typeof o.purchase_storage_balance!="string"||!/^(0|[1-9][0-9]*)$/.test(o.purchase_storage_balance)||BigInt(o.purchase_storage_balance)>=2n**128n)||o.terms.contract!==t||o.terms.file_id!==r||!(o.header_hash===null||oc(o.header_hash,32))||!(o.sales_stopped_at===null||Number.isSafeInteger(o.sales_stopped_at)&&o.sales_stopped_at>0)||!(o.taken_down===null||typeof o.taken_down=="string"&&fS.includes(o.taken_down)))throw new Error}catch{return He("get_file")}let i=o.terms;return{purchaseStorageBalance:BigInt(o.purchase_storage_balance??"0"),terms:i,termsHash:o.terms_hash,seller:ne(i.seller),price:BigInt(i.base?.price??i.near.price),payTo:i.base?.pay_to??"",cipherHash:i.cipher_hash,moderator:i.moderator,headerHash:o.header_hash,salesStoppedAt:o.sales_stopped_at,takenDown:o.taken_down}}async function so(e,t,r){let n=await Lr(e,t,"get_purchase",{purchase_id:r});if(n===null)return null;try{if(n.purchase_id!==r||!oc(n.file_id,32)||!oc(n.terms_hash,32)||!Number.isSafeInteger(n.grants)||n.grants<1||n.grants>4294967295||!Number.isSafeInteger(n.accepted_at)||n.accepted_at<0||!["near-usdc","base-usdc"].includes(n.route)||(n.route==="base-usdc"?n.delivery!==null:!Number.isSafeInteger(n.delivery)||n.delivery<0))throw new Error;io(n.buyer_key),ne(n.recovery)}catch{return He("get_purchase")}return n}async function U0(e,t,r,n=0){if(!Number.isInteger(n)||n<0||n>4294967295)throw new TypeError("invalid grant");let o=await Lr(e,t,"get_grant",{purchase_id:r,grant:n});if(o===null)return null;try{if(o.purchase_id!==r||o.grant!==n)throw new Error;io(o.buyer_key)}catch{return He("get_grant")}return o}async function Rg(e,t,r,n=0,o=50){if(!Number.isSafeInteger(n)||n<0||n>4294967295||!Number.isSafeInteger(o)||o<1||o>100)throw new TypeError("invalid page");let i=await Lr(e,t,"purchases_of",{recovery:ne(r),from:n,limit:o});return!Array.isArray(i)||i.length>o||!i.every(s=>oc(s,32))?He("purchases_of"):i}async function ao(e,t){let r=await Lr(e,t,"get_config",{});return!O0(r?.mpc)||!Number.isSafeInteger(r?.ckd_domain)||!Number.isSafeInteger(r?.foreign_tx_domain)||!oc(r?.usdc,20)||!["near:mainnet","near:testnet","near:sandbox"].includes(r?.network)||!O0(r?.near_usdc)||!O0(r?.intents)||r?.ckd_domain<0||r?.foreign_tx_domain<0?He("get_config"):{mpc:r?.mpc,ckdDomain:r?.ckd_domain,foreignTxDomain:r?.foreign_tx_domain,usdc:r?.usdc,network:r?.network,nearUsdc:r?.near_usdc,intents:r?.intents}}var uS=new Set(["register","unlock","reopen","reopen_seller","claim_key"]),lS=e=>typeof e=="object"&&e!==null&&("SuccessValue"in e||"SuccessReceiptId"in e),tf=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(tf).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${tf(e[t])}`).join(",")}}`;function ci(e,t,r){let n=e,o=n?.transaction;if(r&&(o?.hash!==r.txHash||o?.signer_id!==r.signer))return He("an outcome for another transaction");o?.receiver_id!==t&&si("transport","the transaction was not sent to the Annon contract");let i=Array.isArray(o?.actions)?o.actions:[],s=i[0]?.FunctionCall?.method_name;if(i.length!==1||typeof s!="string")return He("not a single function call");if(r?.method!==void 0&&s!==r.method)return He("an outcome of another method");if(r?.deposit!==void 0&&i[0]?.FunctionCall?.deposit!==r.deposit)return He("an outcome with another deposit");if(r?.args!==void 0){let p;try{p=JSON.parse(Pg(String(i[0]?.FunctionCall?.args)))}catch{return He("call arguments are not JSON")}let m=JSON.parse(JSON.stringify(r.args)??"null");if(s==="register"&&p&&typeof p=="object"&&"args"in p&&!Object.hasOwn(m.args??{},"file_budget")){let h=p.args;if(Object.hasOwn(h,"file_budget")){if(typeof h.file_budget!="string"||!/^[1-9][0-9]*$/.test(h.file_budget)||BigInt(h.file_budget)>=2n**128n)return He("invalid registration budget");delete h.file_budget}}if(tf(p)!==tf(m))return He("an outcome of another call")}let a=[];for(let p of Array.isArray(n.receipts_outcome)?n.receipts_outcome:[])if(!(p?.outcome?.executor_id!==t||!lS(p.outcome.status))){for(let m of Array.isArray(p.outcome.logs)?p.outcome.logs:[])if(!(typeof m!="string"||!m.startsWith("EVENT_JSON:")))try{let h=JSON.parse(m.slice(11));h.standard==="annon"&&h.version==="2.0.0"&&typeof h.event=="string"&&a.push({event:h.event,data:h.data?.[0]??{}})}catch{}}let c=n.status;if(c==="NotStarted"||c==="Started")return{state:"pending",method:s,events:a};if(typeof c!="object"||c===null)return He("status");let d=uS.has(s);if("Failure"in c){let p=pS(c.Failure);return d?{state:"not_released",method:s,reason:p,events:a}:{state:"refused",method:s,reason:p,events:a}}if(typeof c.SuccessValue!="string")return He("status");let f=null;if(c.SuccessValue!=="")try{f=JSON.parse(Pg(c.SuccessValue))}catch{return He("return value is not JSON")}if(!d)return{state:"done",method:s,value:f,events:a};let u=f;if(u&&typeof u.big_y=="string"&&typeof u.big_c=="string")return{state:"released",method:s,answer:f,events:a};let l=u&&typeof u.error=="string"?u.error:"no key in the result";return{state:"not_released",method:s,reason:l,events:a}}function pS(e){let t=e?.ActionError?.kind?.FunctionCallError?.ExecutionError;return typeof t=="string"?t.replace(/^Smart contract panicked: /,""):JSON.stringify(e)}async function Og(e,t,r,n,o="FINAL",i){let s=await ef(e,"EXPERIMENTAL_tx_status",{tx_hash:t,sender_account_id:r,wait_until:o}),a=ci(s,n,{txHash:t,signer:r,...i});if(i?.notBefore!==void 0){let c=s.transaction_outcome?.block_hash;if(!Number.isSafeInteger(i.notBefore)||i.notBefore<0||typeof c!="string"||!c)return He("missing transaction inclusion checkpoint");let f=(await ef(e,"block",{block_id:c})).header?.timestamp_nanosec;if(typeof f!="string"||!/^(0|[1-9][0-9]*)$/.test(f))return He("transaction inclusion time");if(BigInt(f)<BigInt(i.notBefore)*1000000000n)return He("a transaction before the current attempt")}return a}async function Cg(e,t,r){return(await ef(e,"query",{request_type:"view_access_key",finality:"final",account_id:t,public_key:r})).permission==="FullAccess"}async function N0(e,t,r){let n=await Lr(e,t,"file_storage_balance",{file_id:r}),o=i=>typeof i=="string"&&/^(0|[1-9][0-9]*)$/.test(i)&&BigInt(i)<2n**128n;return!n||!o(n.available)||!o(n.admission_requirement)||BigInt(n.admission_requirement)===0n?He("file_storage_balance"):{available:BigInt(n.available),admissionRequirement:BigInt(n.admission_requirement)}}function Ug(e){return typeof e=="string"&&/prepaid|storage balance|storage[_ ]deposit/i.test(e)}function mS(e){if(e.nonce.length!==32)throw new TypeError("NEP-413 nonce must be 32 bytes");return ur(Et(je(2147484061,4),At(e.message),e.nonce,At(e.recipient),e.callbackUrl===void 0?je(0,1):Et(je(1,1),At(e.callbackUrl))))}async function rf(e,t,r,n){be(e),be(r.contractId);let o={...r.callbackUrl===void 0?{}:{callbackUrl:r.callbackUrl},message:t,recipient:r.contractId,nonce:crypto.getRandomValues(new Uint8Array(32))},i=await n({...o,nonce:o.nonce.slice()});await ic(e,o,i,r.nearRpc)}async function ic(e,t,r,n){let o=mS(t);if(!r||r.accountId!==e||!r.publicKey.startsWith("ed25519:"))throw new S("invalid_signature","NEP-413 proof belongs to another account or key type");let i=Ut.decode(r.publicKey.slice(8)),s=wd.decode(r.signature);if(i.length!==32||s.length!==64||!jd.verify(s,o,i,{zip215:!1}))throw new S("invalid_signature","invalid NEP-413 recovery signature");if(!await Cg(n,e,r.publicKey))throw new S("invalid_signature","NEP-413 recovery requires a full-access key")}function nf(e){ae(e,["v","uploadId","network","contract","fileId","termsHash","seller","cipherHash","byteSize","plaintextSize","headerSize","metadataHash","hostOrigin","issuedAt","expiresAt","signature"]);let t=e;if(t.v!==1||!/^[0-9a-f]{64}$/.test(t.uploadId)||typeof t.signature!="string"||!/^[A-Za-z0-9_-]{86}$/.test(t.signature))throw new TypeError("Invalid hosting reservation.");for(let n of["fileId","termsHash","cipherHash","metadataHash"])G(t[n],32);for(let n of["byteSize","plaintextSize","headerSize","issuedAt","expiresAt"])if(!Number.isSafeInteger(t[n])||t[n]<0)throw new TypeError("Invalid hosting reservation.");let r=new URL(t.hostOrigin);if(r.protocol!=="https:"||r.origin!==t.hostOrigin||t.byteSize<1||t.byteSize>50086016||t.plaintextSize>5e7||t.headerSize<1||t.headerSize>65536||t.byteSize<=t.headerSize||t.expiresAt!==t.issuedAt+600)throw new TypeError("Invalid hosting reservation.");return Ke(t.seller),t}var co=e=>["Annon: reserve encrypted file hosting",`network: ${e.network}`,`contract: ${e.contract}`,`seller: ${Ke(e.seller)}`,`file: ${e.fileId}`,`cipher: ${e.cipherHash}`,`terms: ${e.termsHash}`,`bytes: ${e.byteSize}`,`plaintext bytes: ${e.plaintextSize}`,`header bytes: ${e.headerSize}`,`host: ${e.hostOrigin}`,`metadata: ${e.metadataHash}`,`nonce: ${e.nonce}`,`expires: ${e.expiresAt}`].join(`
48
- `),of=new TextEncoder;function di(e){let t=new URL(e);if(t.protocol!=="https:"||t.origin!==e||t.username||t.password)throw new S("bad_request","Invalid upload origin.");return e}function sf(e){ae(e,["filename","title","description"]);let t={};for(let[r,n]of[["filename",255],["title",120],["description",500]]){let o=e[r];if(typeof o!="string")throw new S("bad_request","Invalid upload metadata.");let i=o.normalize("NFC");if(/[\p{Cc}\p{Cs}\p{Cf}\p{Zl}\p{Zp}]/u.test(i)||of.encode(i).length>n||r!=="description"&&!i)throw new S("bad_request","Invalid upload metadata.");t[r]=i}if(/[\\/]/.test(t.filename)||t.filename==="."||t.filename==="..")throw new S("bad_request","Invalid upload filename.");return t}async function F0(e){let t=sf(e);return Y(await Oe(of.encode(JSON.stringify([t.filename,t.title,t.description]))))}function ac(e){ae(e,["network","contract","seller","fileId","cipherHash","termsHash","byteSize","plaintextSize","headerSize","hostOrigin","metadataHash","nonce","expiresAt"]);let t=e;Gn(t.network),be(t.contract),di(t.hostOrigin);let r=ne(t.seller);if(r.kind!==t.seller.kind||r.id!==t.seller.id)throw new S("bad_request","Noncanonical seller.");for(let n of["fileId","cipherHash","termsHash","metadataHash","nonce"])G(t[n],32);for(let n of["byteSize","plaintextSize","headerSize","expiresAt"])if(!Number.isSafeInteger(t[n])||t[n]<0)throw new S("bad_request","Invalid upload size or time.");if(t.byteSize<=t.headerSize||t.headerSize<1||t.headerSize>65536||t.plaintextSize>5e7||t.byteSize>50086016)throw new S("bad_request","Invalid upload size.");return{...structuredClone(t),seller:r}}function M0(e){if(!e||typeof e!="object")throw new S("bad_request","Invalid upload authorization.");if("kind"in e&&e.kind==="near"){ae(e,["kind","accountId","publicKey","signature"]);let t=e;if(typeof t.accountId!="string"||typeof t.publicKey!="string"||typeof t.signature!="string")throw new S("bad_request","Invalid upload authorization.")}else{if(ae(e,["kind","sig"]),e.kind!=="evm"&&e.kind!=="solana")throw new S("bad_request","Invalid upload authorization.");G(e.sig,e.kind==="evm"?65:64)}return structuredClone(e)}function z0(e){ae(e,["intent","terms","manifest","metadata","auth"]);let t=ac(e.intent);ae(e.manifest,["version","chunkLog2","metaLen","previewLen","n","keyCommitments","chunkHashes"]);let r=e.manifest;if(![r.chunkLog2,r.metaLen,r.previewLen,r.n].every(Number.isSafeInteger)||r.version!==2||r.chunkLog2<16||r.chunkLog2>24||r.metaLen<256||r.metaLen>4096||r.metaLen%256!==0||r.previewLen<0||r.previewLen>no(t.plaintextSize)||r.n<2||r.n>1024||r.n!==ro(t.plaintextSize,r.previewLen,r.chunkLog2)||!Array.isArray(r.keyCommitments)||r.keyCommitments.length!==(r.previewLen>0?2:1)||!Array.isArray(r.chunkHashes)||r.chunkHashes.length!==r.n)throw new S("bad_request","Invalid upload manifest.");for(let n of[...r.keyCommitments,...r.chunkHashes])G(n,32);if(t.headerSize!==206+of.encode(t.contract).length+32*(r.keyCommitments.length+r.n)||t.byteSize-t.headerSize!==t.plaintextSize+r.metaLen+16*r.n)throw new S("bad_request","Invalid upload framing.");return{intent:t,terms:structuredClone(e.terms),manifest:structuredClone(r),metadata:sf(e.metadata),auth:M0(e.auth)}}async function Fg(e,t){let r=ac(e.intent),n=M0(e.auth);if(r.network!==t.network||r.contract!==t.contract||r.hostOrigin!==t.hostOrigin||r.expiresAt<=t.now||r.expiresAt>t.now+(t.authSeconds??600)||n.kind!==r.seller.kind)throw new S("bad_request","Invalid upload authorization.");if(n.kind==="near")await ic(r.seller.id,{message:co(r),recipient:r.hostOrigin,nonce:G(r.nonce,32)},n,t.nearRpc);else if(!lt(r.seller,co(r),n))throw new S("bad_request","Invalid upload signature.")}function hS(e){let t=Cy.encode(of.encode(JSON.stringify({intent:ac(e.intent),auth:M0(e.auth)})));if(t.length>8192)throw new S("bad_request","Upload authorization is too large.");return t}var rs=(e,t)=>{let r=Ko({code:e,retryAfterSeconds:t});return{ok:!1,error:Object.assign(new S(e),r.retryAfterSeconds===void 0?{}:{retryAfterSeconds:r.retryAfterSeconds})}};function Mg(e,t,r){ae(e,["uploadId","state","expiresAt","bodyUrl","headerUrl"]);let n=e;if(!/^[a-f0-9]{64}$/.test(n.uploadId)||r!==void 0&&n.uploadId!==r||n.state!=="receiving"||!Number.isSafeInteger(n.expiresAt)||n.expiresAt<0||n.bodyUrl!==`${t}/v1/uploads/${n.uploadId}/body`||n.headerUrl!==`${t}/v1/uploads/${n.uploadId}/header`)throw new S("bad_request","Invalid upload response.");return n}function zg(e,t,r){ae(e,["uploadId","state","reservation"]);let n=e,o=nf(n.reservation);if(n.uploadId!==t||n.state!=="reserved"||o.uploadId!==t||Q(o.seller)!==Q(r.seller))throw new S("bad_request","Invalid upload response.");for(let i of["network","contract","fileId","termsHash","cipherHash","byteSize","plaintextSize","headerSize","metadataHash","hostOrigin"])if(o[i]!==r[i])throw new S("bad_request","Invalid upload response.");return{...n,reservation:o}}function Hg(e,t){ae(e,["fileId","url","header","expiresAt"]);let r=e,n=`${t.hostOrigin}/f/${t.fileId.slice(2)}`;if(r.fileId!==t.fileId||r.url!==n||r.header!==`${n}/header`||r.expiresAt!==null&&(!Number.isSafeInteger(r.expiresAt)||r.expiresAt<0))throw new S("bad_request","Invalid upload response.");return r}function $g(e){if(e===null)return null;if(ae(e,["state","address","kind","salt","txHash"]),e.state!=="pending"&&e.state!=="ready"||typeof e.address!="string"||!/^0x[0-9a-fA-F]{40}$/.test(e.address)||e.kind!=="push"||e.salt!==`0x${"00".repeat(32)}`||e.txHash!==null&&(typeof e.txHash!="string"||!/^0x[0-9a-f]{64}$/.test(e.txHash)))throw new S("bad_request");return e}function Ng(e,t,r){if(!e||typeof e!="object"||!("baseSplit"in e))throw new S("bad_request");let{baseSplit:n,...o}=e,i=$g(n);if("state"in o&&o.state==="receiving")return{...Mg(o,r.hostOrigin,t),baseSplit:i};if("state"in o&&o.state==="reserved")return{...zg(o,t,r),baseSplit:i};if(ae(o,["uploadId","state","result"]),o.uploadId!==t||o.state!=="published")throw new S("bad_request");return{uploadId:t,state:"published",result:Hg(o.result,r),baseSplit:i}}var sc=class{origin;fetcher;constructor(t,r={}){this.origin=di(t),this.fetcher=r.fetch??fetch}async request(t,r,n,o,i){try{return await this.requestJson(t,r,n,o,i)}catch{return rs("operation_failed")}}async requestJson(t,r,n,o,i){let s=await this.fetcher(`${this.origin}${t}`,{method:r,credentials:"omit",redirect:"error",signal:AbortSignal.timeout(r==="PUT"?18e5:5e3),headers:{...n===void 0?{}:{"Content-Type":r==="PUT"?"application/octet-stream":"application/json"},...o?{"Annon-Upload-Authorization":hS(o)}:{}},...n===void 0?{}:{body:n},...n instanceof ReadableStream?{duplex:"half"}:{}});if(s.redirected||s.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()!=="application/json")return await s.body?.cancel(),rs("operation_failed");let a=s.body?.getReader();if(!a)return rs("operation_failed");let c=[],d=0;try{for(;;){let{value:m,done:h}=await a.read();if(h)break;if(d+=m.length,d>131072)throw new S("bad_request","Upload response is too large.");c.push(m)}}finally{await a.cancel(),a.releaseLock()}let f=new Uint8Array(d),u=0;for(let m of c)f.set(m,u),u+=m.length;let l=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(f));if(bd(l?.error))return rs(l.error,l.retryAfterSeconds);if(s.ok)try{if(!i)throw new S("bad_request");return{ok:!0,value:i(l,s.status)}}catch{return rs("operation_failed")}let p=bd(l?.error)?l.error:"operation_failed";return rs(p,p==="operation_failed"?void 0:l.retryAfterSeconds)}path(t){if(!/^[a-f0-9]{64}$/.test(t))throw new S("bad_request","Invalid upload ID.");return`/v1/uploads/${t}`}create(t){return this.request("/v1/uploads","POST",JSON.stringify(z0(t)),void 0,r=>r&&typeof r=="object"&&"baseSplit"in r?Ng(r,r.uploadId,t.intent):Mg(r,this.origin))}async body(t,r,n){return this.request(`${this.path(t)}/body`,"PUT",n,r,o=>zg(o,t,r.intent))}async header(t,r,n){return this.request(`${this.path(t)}/header`,"PUT",n,r,o=>Hg(o,r.intent))}async status(t,r){return this.request(this.path(t),"GET",void 0,r,n=>Ng(n,t,r.intent))}async baseSplit(t,r,n){if(ae(n,["kind","salt"]),n.kind!=="push"||n.salt!==`0x${"00".repeat(32)}`)throw new S("bad_request");return this.request(`${this.path(t)}/base-split`,"POST",JSON.stringify(n),r,(o,i)=>{ae(o,["baseSplit"]);let s=$g(o.baseSplit);if(!s||i!==(s.state==="pending"?202:200))throw new S("bad_request");return{baseSplit:s}})}};var fi=globalThis.crypto.subtle,cc=new TextEncoder,br=class extends S{constructor(){super("source_changed","source changed between passes"),this.name="SourceChangedError"}},ns=class{reader;pending=new Uint8Array;at=0;ended=!1;released=!1;cancellation;constructor(t){this.reader=t.getReader()}async read(t){let r=new Uint8Array(t),n=0;for(;n<t;){if(this.at===this.pending.length){if(this.pending=new Uint8Array,this.at=0,this.ended)break;let i=await this.reader.read();if(i.done){this.ended=!0;break}if(!(i.value instanceof Uint8Array))throw new TypeError("expected Uint8Array");this.pending=i.value}let o=Math.min(t-n,this.pending.length-this.at);r.set(this.pending.subarray(this.at,this.at+o),n),this.at+=o,n+=o,this.at===this.pending.length&&(this.pending=new Uint8Array,this.at=0)}return r.subarray(0,n)}cancel(t){return this.cancellation??=this.reader.cancel(t).catch(()=>{}),this.cancellation}release(){this.released||(this.released=!0,this.pending=new Uint8Array,this.reader.releaseLock())}};function H0(e,t){let r=new ns(e);async function*n(){try{yield*t(r)}finally{await r.cancel(),r.release()}}let o=n();return new ReadableStream({async pull(i){try{let s=await o.next();s.done?i.close():i.enqueue(s.value)}catch(s){i.error(s)}},async cancel(i){await r.cancel(i),await o.return(),r.release()}},{highWaterMark:0})}async function $0(e,t,r,n){if(n.fileId.length!==32||e.length!==32)throw new TypeError("fileId and K are 32 bytes");if(!Number.isSafeInteger(r)||r<0)throw new RangeError("size must be a safe unsigned integer");let{version:o,authKind:i}=g0(n),s=We(n.fileId),a=We(e),c=n.previewLen??0;if(!Number.isSafeInteger(c)||c<0||c>no(r))throw new RangeError(`previewLen must be 0 to ${no(r)}`);let d=n.chunkLog2??22;for(;n.chunkLog2===void 0&&d<24&&ro(r,c,d)>Wi;)d++;if(!Number.isInteger(d)||d<16||d>24)throw new RangeError("chunkLog2 must be an integer from 16 to 24");let f=ro(r,c,d);if(f>Wi)throw new RangeError("file too large for PAY2");let u=2**d,l=cc.encode(n.name);if(!/^[\x20-\x7e]{0,255}$/.test(n.mime))throw new RangeError("mime must be printable ASCII");let p=Te(rt(l.length,2),l,rt(n.mime.length,1),cc.encode(n.mime),rt(r,8)),m=Math.ceil(p.length/256)*256;if(m>Kd)throw new RangeError("name too long");let h=Te(p,new Uint8Array(m-p.length)),y=c>0?2:1,b=[];for(let U=0;U<y;U++)b.push(await Ja(await ti(a,s,U)));let x=Te(new Uint8Array(Xa),new Uint8Array([o,d,1,i]),new Uint8Array(4),s,rt(m,2),rt(c,4),rt(f,4),...b,new Uint8Array(32*f)),g=Array.from({length:f},(U,R)=>x.subarray(Hr+32*(y+R),Hr+32*(y+R+1)));async function*w(U,R=!1){let T=r;for(let O=0;O<f;O++){let z=O===0?m:O===1&&c>0?c:Math.min(u,T),P=O===0?h:await U.read(z);if(P.length!==z)throw R?new br:new RangeError("plaintext shorter than size");O>0&&(T-=z);let _=O===f-1;if(_&&(await U.read(1)).length!==0)throw R?new br:new RangeError("plaintext longer than size");yield await Qa("encrypt",await ti(a,s,O),_,P)}}let v=new ns(t),E=[];try{let U=0;for await(let R of w(v))U<y&&E.push(R),g[U++].set(await Oe(R))}finally{await v.cancel(),v.release()}let B=await tc({version:o,chunkLog2:d,fileId:s,metaLen:m,previewLen:c,n:f,commits:b,hashes:g}),N;return{manifest:{version:o,chunkLog2:d,metaLen:m,previewLen:c,n:f,keyCommitments:b.map(Y),chunkHashes:g.map(Y)},headerSize(U){return be(U),206+cc.encode(U).length+32*(y+f)},body(U){return H0(U,async function*(R){let T=0;for await(let O of w(R,!0)){if(!pt(await Oe(O),g[T++]))throw new br;yield O}})},fileId:We(s),cipherHash:B,async finish(U,R){let{contractId:T,ckdSecret:O}=R;be(T);let z=await ec(O,s,"wrapKey"),P=await fi.importKey("raw",a,"AES-GCM",!0,["encrypt"]),_=new Uint8Array(await fi.wrapKey("raw",P,z,"AES-KW")),I=cc.encode(bn),k=Te(new Uint8Array([T.length]),cc.encode(T),_),M=Te(new Uint8Array([I.length]),I,rt(k.length,2),k),$=Te(x,M);new DataView($.buffer).setUint32(8,$.length+yn+yr);let F=await fi.importKey("raw",await ei(a,s,"annon/pay2/header"),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),A=new Uint8Array(await fi.sign("HMAC",F,$)),H=await w0(o,i,R,s,await Oe($,A)),D=Te($,A,H);return N=D,H0(U,async function*(q){yield D;let j=0;for await(let K of w(q,!0)){if(!pt(await Oe(K),g[j++]))throw new br;yield K}})},async preview(U){if(!N)throw new Error("call finish first: the preview carries the final header");if(U.data&&c===0)throw new RangeError("sealed without a preview");let R=N.slice(0,x.length);R[6]=0,new DataView(R.buffer).setUint32(8,0);let T=z=>{let P="";for(let _ of z)P+=String.fromCharCode(_);return btoa(P)},O=[];for(let z of[0,1])(z===0?U.meta:U.data)&&O.push({index:z,key:T(await ti(a,s,z)),data:T(E[z])});return{v:1,header:T(R),chunks:O}}}}async function L0(e){let t=await e.read(Hr);if(t.length<4||!Xa.every((i,s)=>t[s]===i))throw new Re("bad_magic");if(t.length<Hr)throw new Re("bad_header");if(t[4]!==2)throw new Re("unsupported_version");let r=t[5]??0;if(r<16||r>24)throw new Re("bad_chunk_size");let o=new DataView(t.buffer).getUint32(8);if(o>h0)throw new Re("header_too_large");return Te(t,await e.read(Math.max(0,o-Hr)))}function Lg(e,t,r){return H0(e,async function*(n){let o=await L0(n);if(t.expectedHeader&&!pt(o,t.expectedHeader))throw new br;let i=await Yi(o,t.listing,t.contractId),s=i.stanzas.map(m=>m.type===bn?ri(m.body):void 0).find(m=>m?.contractId===t.contractId);if(!s)throw new Re("no_usable_stanza");let a=await ec(await t.ckdSecret(We(i.fileId)),i.fileId,"unwrapKey"),c;try{c=await fi.unwrapKey("raw",s.wrapped,a,"AES-KW","HKDF",!1,["deriveBits"])}catch{throw new Re("key_unwrap_failed")}let d=await fi.importKey("raw",await ei(c,i.fileId,"annon/pay2/header"),{name:"HMAC",hash:"SHA-256"},!1,["verify"]),f=i.headerLen-yn-yr;if(!await fi.verify("HMAC",d,o.subarray(f,f+yn),o.subarray(0,f)))throw new Re("header_mac_invalid");let u=2**i.chunkLog2,l,p=0;for(let m=0;m<i.n;m++){let h=m===i.n-1,y=m===0?i.metaLen+ve:m===1&&i.previewLen>0?i.previewLen+ve:u+ve,b=await n.read(h?u+ve+1:y);if(h?b.length<ve||b.length>u+ve:b.length!==y)throw new Re("bad_body_length");if(!pt(await Oe(b),i.hashes[m]))throw new Re("chunk_hash_mismatch",`chunk ${m}`);let x=await ti(c,i.fileId,m),g=i.commits[m];if(g&&!pt(await Ja(x),g))throw new Re("chunk_invalid",`chunk ${m} key commitment`);let w;try{w=await Qa("decrypt",x,h,b)}catch{throw new Re("chunk_invalid",`chunk ${m}`)}if(m===0){if(l=b0(w,i),r!==void 0&&l.size!==r)throw new Re("meta_invalid","chunk lengths do not add up to the size");t.onMeta?.({...l})}else{if(p+=w.length,h&&p!==l?.size)throw new Re("meta_invalid","chunk lengths do not add up to the size");yield w}}})}function Dg(e,t,r){return e instanceof ReadableStream?r?r(e,t):Promise.reject(new TypeError("a ciphertext spool is required for a single-use stream")):t(e)}function dc(e){return{size:e.size,read:()=>e.stream()}}async function ui(e,t,r){if(t instanceof Uint8Array){let i=t.slice(),s=await og(e,i,r),a=await $0(e,new Blob([i]).stream(),i.length,r),c=()=>a.body(new Blob([i]).stream());return{...s,manifest:a.manifest,headerSize:a.headerSize,body:c,stage:(d,f)=>d(c(),f),async finish(d){let f=await s.finish(d);return{consumed:()=>!0,cancel:async()=>{},file:f,header:f.subarray(0,new DataView(f.buffer).getUint32(8))}}}}let n=t.read(),o;try{o=await $0(e,n,t.size,r)}catch(i){throw await n.cancel(i).catch(()=>{}),i}return{...o,body:()=>o.body(t.read()),stage:(i,s)=>i(o.body(t.read()),s),async finish(i){let s=t.read(),a;try{a=await o.finish(s,i)}catch(h){throw await s.cancel(h).catch(()=>{}),h}let c=a.getReader(),d;try{d=(await c.read()).value}catch(h){throw await c.cancel(h),c.releaseLock(),h}let f=!1,u=()=>{f||(f=!0,c.releaseLock())},l=!0,p=!1,m=new ReadableStream({async pull(h){if(l){l=!1,h.enqueue(d);return}try{let y=await c.read();y.done?(p=!0,h.close(),u()):h.enqueue(y.value)}catch(y){h.error(y),u()}},async cancel(h){await c.cancel(h),u()}},{highWaterMark:0});return{file:m,header:d,consumed:()=>p,async cancel(h){if(!f)try{await c.cancel(h)}finally{u()}await m.cancel(h).catch(()=>{})}}}}}async function qg(e,t){let r=new ns(e.read()),n,o=0;try{n=await L0(r);let i=await Yi(n,t.listing,t.contractId),s=2**i.chunkLog2,a=-1;for(let c=0;c<i.n;c++){let d=c===i.n-1,f=c===0?i.metaLen+ve:c===1&&i.previewLen>0?i.previewLen+ve:s+ve,u=await r.read(d?s+ve+1:f);if(d?u.length<ve||u.length>s+ve:u.length!==f)throw new Re("bad_body_length");c>0&&(o+=u.length-ve),!pt(await Oe(u),i.hashes[c])&&a<0&&(a=c)}if(a>=0)throw new Re("chunk_hash_mismatch",`chunk ${a}`);if(!i.stanzas.some(c=>c.type===bn&&ri(c.body)?.contractId===t.contractId))throw new Re("no_usable_stanza")}finally{await r.cancel(),r.release()}return{header:n.slice(),async writeTo(i,s){let a;if(await Lg(e.read(),{...t,expectedHeader:n,ckdSecret:s,onMeta:c=>{a=c}},o).pipeTo(i),!a)throw new Re("meta_invalid");return a}}}var q0=kt.G1.Point,jg=kt.G2.Point,Gg=kt.fields.Fr,yS="NEAR BLS12381G1_XMD:SHA-256_SSWU_RO_",af=class extends S{code;constructor(t,r=t){super(t,r),this.code=t,this.name="CkdError"}},cf=(e,t)=>{throw new af(e,t)};function fo(){let e=Wg(kt.utils.randomSecretKey())%Gg.ORDER;return Gt(xS(e===0n?1n:e))}function Gt(e){let t=q0.BASE.multiply(Zg(e)).toBytes(!0);return{secret:e,publicKey:`bls12381g1:${Ut.encode(t)}`,publicKeyBytes:t}}var bS=(e,t)=>Kb(new TextEncoder().encode(`near-mpc v0.1.0 app_id derivation:${e},${t}`)),Vg=(e,t)=>bS(e,`file/${Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}`);function Kg(e,t){let r=e;r&&typeof r.error=="string"&&cf("ckd_failed",r.error);let n=D0(q0,r?.big_y,"bls12381g1:",48),o=D0(q0,r?.big_c,"bls12381g1:",48),i=D0(jg,t.mpcKey,"bls12381g2:",96);return gS(Zg(t.secret),n,o,i,t.appId).toBytes(!0)}function gS(e,t,r,n,o){let i=r.subtract(t.multiply(e)),s=wS(n,o),a=!1;try{a=!i.is0()&&kt.fields.Fp12.eql(kt.pairing(s,n),kt.pairing(i,jg.BASE))}catch{}return a||cf("ckd_invalid","the answer is not the key for this file and this one-time key"),i}var wS=(e,t)=>kt.shortSignatures.hash(new Uint8Array([...e.toBytes(!0),...t]),yS),Wg=e=>BigInt(`0x${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")||"0"}`),xS=e=>Uint8Array.from(e.toString(16).padStart(64,"0").match(/../g)??[],t=>Number.parseInt(t,16));function Zg(e){if(e.length!==32)throw new TypeError("the one-time secret is 32 bytes");let t=Wg(e);if(t===0n||t>=Gg.ORDER)throw new TypeError("the one-time secret is not a valid scalar");return t}function D0(e,t,r,n){if(typeof t!="string"||!t.startsWith(r))return cf("ckd_invalid","bad point");try{let o=Ut.decode(t.slice(r.length));if(o.length!==n)throw new Error("length");return e.fromBytes(o)}catch{return cf("ckd_invalid","bad point")}}var Dr=5e7,qr=50086016,df=60;var j0=["terms_review","preparing","payment_uncertain","awaiting_deposit","incomplete_deposit","processing","accepting","accepted","recovering","file_ready","refunded","failed","expired","abandoned"];function fc(e,t){if(t===null){if(e===null)throw new TypeError("nothing to remove");return}if(t.revision!==(e===null?0:e.revision+1))throw new TypeError("next must be the expected record's next revision");if(e!==null&&t.id!==e.id)throw new TypeError("next must keep the id of the record it replaces")}var vS=(e,t)=>t===null?e===null:e!==null&&e.id===t.id&&e.revision===t.revision,Yg=e=>e==null?null:JSON.parse(e);function uc(e={}){let t=e.factory??globalThis.indexedDB;if(!t)throw new TypeError("no IndexedDB here: pass a factory or use another store");let r=e.name??"annon",n,o=()=>(n??=new Promise((a,c)=>{let d=t.open(r,1);d.onupgradeneeded=()=>d.result.createObjectStore("records"),d.onsuccess=()=>a(d.result),d.onerror=()=>c(d.error)}),n),i=async a=>(await o()).transaction("records",a,{durability:"strict"}).objectStore("records"),s=async a=>{if(!a.length||new Set(a.map(d=>d.key)).size!==a.length)throw new TypeError("empty or duplicate CAS keys");for(let d of a)fc(d.expected,d.next);let c=await i("readwrite");return new Promise((d,f)=>{let u=a.length,l=!0,p=!1;for(let h of a){let y=c.get(h.key);y.onsuccess=()=>{try{if(vS(Yg(y.result),h.expected)||(l=!1),--u!==0||!l)return;for(let b of a)b.next===null?c.delete(b.key):c.put(JSON.stringify(b.next),b.key);p=!0}catch(b){f(b),c.transaction.abort()}}}c.transaction.oncomplete=()=>d(p);let m=()=>f(c.transaction.error??new Error("the IndexedDB transaction was aborted"));c.transaction.onerror=m,c.transaction.onabort=m})};return{load:async a=>{let c=await i("readonly");return new Promise((d,f)=>{let u=c.get(a);u.onsuccess=()=>d(Yg(u.result)),u.onerror=()=>f(u.error)})},compareAndSet:(a,c,d)=>s([{key:a,expected:c,next:d}]),compareAndSetMany:s}}var uf=globalThis.crypto.subtle,G0=2*1024*1024,V0="annon/purchase-backup/v1";function SS(e){if("kind"in e&&e.kind==="browser-recovery-archives"){if(G(e.purchaseId,32),e.id!==`recovery-archives:${e.purchaseId}`||!Number.isSafeInteger(e.revision)||e.revision<0||!Array.isArray(e.names)||new Set(e.names).size!==e.names.length||e.names.some(t=>typeof t!="string"||!t.startsWith(`recovery:${e.purchaseId}:revision:`)||!/^[0-9]+$/.test(t.slice(t.lastIndexOf(":")+1))))throw new TypeError("invalid recovery archive index");return}if("kind"in e&&e.kind==="browser-purchase"){Xg(e);return}if("kind"in e&&e.kind==="browser-purchase-index"){if(e.id!=="browser-index"||!Number.isSafeInteger(e.revision)||e.revision<0||!Array.isArray(e.entries)||new Set(e.entries.map(t=>t.id)).size!==e.entries.length)throw new TypeError("invalid browser purchase index");for(let t of e.entries){if(!/^[a-zA-Z0-9_-]{1,128}$/.test(t.id)||!Number.isSafeInteger(t.revision)||t.revision<0||!j0.includes(t.state)||!["near","base","1click"].includes(t.route)||!Number.isSafeInteger(t.createdAt)||!Number.isSafeInteger(t.updatedAt)||t.createdAt<0||t.updatedAt<t.createdAt)throw new TypeError("invalid browser index entry");G(t.fileId,32),t.purchaseId!==void 0&&G(t.purchaseId,32);let r=new URL(t.resourceUrl);if(!["https:","http:"].includes(r.protocol)||r.username||r.password)throw new TypeError("invalid resource URL");if(Object.keys(t).some(n=>!["id","revision","fileId","route","state","resourceUrl","purchaseId","createdAt","updatedAt"].includes(n)))throw new TypeError("index must contain metadata only")}if(et.encode(JSON.stringify(e)).length>G0)throw new TypeError("browser index too large");return}if("kind"in e&&e.kind==="browser-receipt"){ae(e,["kind","entry"]),Xg(e.entry);return}if("kind"in e&&e.kind==="seller-key"){if(ae(e,["kind","id","revision","file_id","seller","buyerSecret","deadline"]),e.id!==`seller-key:${e.file_id}`||!Number.isSafeInteger(e.revision)||e.revision<0||!Number.isSafeInteger(e.deadline)||e.deadline<0)throw new TypeError("invalid seller key record");G(e.file_id,32),e.buyerSecret!==null&&Gt(G(e.buyerSecret,32)),Q(e.seller);return}if("kind"in e&&e.kind==="sell"){if(as(e),!Object.hasOwn(e,"baseSplit")||!(e.baseSplit===null||e.baseSplit&&/^0x[0-9a-f]{40}$/.test(e.baseSplit.address)&&["push","pull"].includes(e.baseSplit.kind)&&/^0x[0-9a-f]{64}$/.test(e.baseSplit.salt)))throw new TypeError("invalid Base split provenance");if(e.id!==`sell:${e.terms.file_id}`||!Number.isSafeInteger(e.revision)||e.revision<0||!Number.isSafeInteger(e.deadline)||e.deadline<0)throw new TypeError("invalid sell record");if(e.storageBudget!==void 0&&(!/^[1-9][0-9]*$/.test(e.storageBudget)||BigInt(e.storageBudget)>=2n**128n))throw new TypeError("invalid sell storage budget");if(e.storageFunding!==void 0&&(!e.storageBudget||!["pending","funded","refused"].includes(e.storageFunding)))throw new TypeError("invalid sell funding state");if(e.published===!0){if(e.fileKey!==null||e.sellerSecret!==null||e.ckdSecret!==null)throw new TypeError("published sell retains secrets")}else G(e.fileKey,32),G(e.sellerSecret,32);e.ckdSecret!==null&&G(e.ckdSecret,48);return}if("kind"in e&&e.kind==="recovery"){if(G(e.purchase_id,32),G(e.file_id,32),G(e.nonce,32),e.id!==`recovery:${e.purchase_id}`||Y(Gt(G(e.buyerSecret,32)).publicKeyBytes)!==e.fresh_key||!Number.isSafeInteger(e.deadline)||e.deadline<0||!Number.isSafeInteger(e.revision)||e.revision<0||!(e.grant===null||Number.isInteger(e.grant)&&e.grant>=0&&e.grant<=4294967295))throw new TypeError("invalid recovery record");Q(e.recovery)}else lf(e)}function Xg(e){if(!/^[a-zA-Z0-9_-]{1,128}$/.test(e.id)||!Number.isSafeInteger(e.revision)||e.revision<0||!j0.includes(e.state)||!["near","base","1click"].includes(e.route)||typeof e.header!="string"||!/^0x(?:[0-9a-f]{2}){1,65536}$/.test(e.header)||e.needsProof!==void 0&&typeof e.needsProof!="boolean"||!["not_submitted","uncertain","submitted"].includes(e.submission))throw new TypeError("invalid browser purchase");if(e.paymentStarted!==void 0&&typeof e.paymentStarted!="boolean")throw new TypeError("invalid payment boundary");if(e.lease&&(!/^[a-zA-Z0-9_-]{1,128}$/.test(e.lease.owner)||!Number.isSafeInteger(e.lease.expiresAt)||e.lease.expiresAt<0))throw new TypeError("invalid purchase lease");if(e.recoveryArchives!==void 0){if(!Array.isArray(e.recoveryArchives)||new Set(e.recoveryArchives.map(r=>r.revision)).size!==e.recoveryArchives.length)throw new TypeError("invalid recovery archives");for(let r of e.recoveryArchives){if(r.kind!=="recovery")throw new TypeError("invalid recovery archive");if(ff(r),!e.purchase||r.purchase_id!==e.purchase.id||r.file_id!==e.fileId)throw new TypeError("recovery archive mismatch")}}if(G(e.fileId,32),_t(e.maxPrice,128)===0n)throw new TypeError("invalid browser price");let t=new URL(e.resourceUrl);if(!["https:","http:"].includes(t.protocol)||t.username||t.password)throw new TypeError("invalid resource URL");if(e.purchase&&(lf(e.purchase),e.purchase.purchase.file_id!==e.fileId||e.purchase.purchase.route!==(e.route==="base"?"base-usdc":"near-usdc")||e.purchase.payment.route!==e.route))throw new TypeError("browser purchase mismatch");if(e.recovery&&(ff(e.recovery),!e.purchase||e.recovery.purchase_id!==e.purchase.id||e.recovery.file_id!==e.fileId))throw new TypeError("browser recovery mismatch");if(e.checkpoint&&(!e.purchase||!Number.isSafeInteger(e.checkpoint.attempts)||e.checkpoint.attempts<0||!Number.isSafeInteger(e.checkpoint.errors)||e.checkpoint.errors<0))throw new TypeError("invalid browser checkpoint")}function ff(e){try{SS(e)}catch(t){throw new S("invalid_record","Invalid encrypted record.",{cause:t})}}var lc=()=>crypto.getRandomValues(new Uint8Array(32));function ES(e){if(!(e instanceof Uint8Array)||e.length!==32)throw new TypeError("backup secret must be 32 random bytes held by the user");return uf.importKey("raw",We(e),"HKDF",!1,["deriveKey"])}async function Jg(e,t){return uf.deriveKey({name:"HKDF",hash:"SHA-256",salt:We(t),info:et.encode(V0)},await ES(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function lf(e){try{_S(e)}catch(t){throw new S("invalid_record","Invalid purchase record.",{cause:t})}}function _S(e){if(typeof e.recoveryProved!="boolean")throw new TypeError("invalid recovery proof checkpoint");if(e?.schemaVersion!==2||!Object.hasOwn(e,"quote")||!(e.quote===null||e.quote&&typeof e.quote=="object"&&e.quote.request&&e.quote.response&&e.quote.deposit)||!e.payment||!["near","base","1click"].includes(e.payment.route)||e.payment.route==="base"!=(e.purchase.route==="base-usdc")||e.payment.amountBaseUnits!==e.purchase.price||e.payment.amountUsdc!==at(BigInt(e.purchase.price))||e.payment.network!==e.purchase.network||e.payment.asset?.symbol!=="USDC"||e.payment.asset.id!==e.purchase.asset||!Number.isSafeInteger(e.revision)||e.revision<0||e.id!==gn(e.purchase,e.purchase.route==="base-usdc"?{baseUsdc:e.purchase.asset}:{nearUsdc:e.purchase.asset})||e.message!==$r(e.purchase,e.purchase.route==="base-usdc"?{baseUsdc:e.purchase.asset}:{nearUsdc:e.purchase.asset})||Y(Gt(G(e.buyerSecret,32)).publicKeyBytes)!==e.purchase.buyer_key||Q(e.recovery)!==Q(e.purchase.recovery)||e.paymentState!==void 0&&!["expired","canceled"].includes(e.paymentState)||!Array.isArray(e.attempts)||!e.terms||e.terms.network!==e.purchase.network||e.terms.usdc!==e.purchase.asset||e.terms.price!==e.purchase.price||e.terms.nonce!==(e.purchase.route==="base-usdc"?Qd(e.id):e.purchase.nonce)||e.terms.contractId!==e.purchase.contract||e.terms.fileId!==e.purchase.file_id||e.terms.buyerKey!==e.purchase.buyer_key||e.terms.headerHash!==e.checkedHeaderHash)throw new TypeError("invalid purchase record");if(G(e.checkedHeaderHash,32),et.encode(JSON.stringify(e)).length>G0)throw new TypeError("purchase record too large")}async function li(e,t,r=""){ff(e);let n=crypto.getRandomValues(new Uint8Array(32)),o=crypto.getRandomValues(new Uint8Array(12)),i=await uf.encrypt({name:"AES-GCM",iv:o,additionalData:Te(et.encode(V0),et.encode(r)),tagLength:128},await Jg(t,n),et.encode(JSON.stringify(e))),s={format:"annon-purchase-backup",v:1,kdf:"HKDF-SHA256",salt:Y(n),iv:Y(o),ciphertext:Y(new Uint8Array(i))};return JSON.stringify(s)}async function os(e,t,r=""){if(typeof e!="string"||e.length>G0*2+1024)throw new TypeError("backup too large");let n=JSON.parse(e);if(ae(n,["format","v","kdf","salt","iv","ciphertext"]),n.format!=="annon-purchase-backup"||n.v!==1||n.kdf!=="HKDF-SHA256"||typeof n.ciphertext!="string"||!/^0x(?:[0-9a-f]{2}){16,}$/.test(n.ciphertext))throw new TypeError("unsupported backup format");let o=G(n.ciphertext,(n.ciphertext.length-2)/2),i=await uf.decrypt({name:"AES-GCM",iv:G(n.iv,12),additionalData:Te(et.encode(V0),et.encode(r)),tagLength:128},await Jg(t,G(n.salt,32)),o),s=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i));return ff(s),s}var pf=(e,t)=>li(e,t),K0=async(e,t)=>{let r=await os(e,t);if("kind"in r)throw new TypeError("not a purchase");return r},is=(e,t)=>li(e,t),mf=async(e,t)=>{let r=await os(e,t);if(!("kind"in r)||r.kind!=="recovery")throw new TypeError("not a recovery");return r};function pi(e,t){if(t.length!==32)throw new TypeError("backup secret must be 32 bytes");let r=We(t),n=(o,i)=>JSON.stringify([o,i.id,i.revision]);return{async load(o){let i=await e.load(o);if(!i)return null;let s=await os(i.backup,r,n(o,i));if(!("id"in s)||s.id!==i.id||s.revision!==i.revision)throw new Error("encrypted record metadata mismatch");return s},async compareAndSet(o,i,s){fc(i,s);let a=s?{id:s.id,revision:s.revision,backup:await li(s,r,n(o,s))}:null;return e.compareAndSet(o,i,a)}}}var ss=(e,t)=>pi(e,t),pc=(e,t)=>pi(e,t),wn=(e,t)=>li(e,t),W0=async(e,t)=>{let r=await os(e,t);if(!("kind"in r)||r.kind!=="sell")throw new TypeError("not a sell record");return r},hf=(e,t)=>pi(e,t),Z0=(e,t)=>li(e,t);async function AS(e,t){try{let r=await os(e,t);if(!("kind"in r)||r.kind!=="seller-key")throw new S("invalid_record");return r}catch(r){throw r instanceof S&&r.code==="invalid_record"?r:new S("invalid_record",void 0,{cause:r})}}var Qg=(e,t)=>pi(e,t),ew=(e,t)=>li(e,t);async function tw(e,t){let r=await os(e,t);if(!("kind"in r)||r.kind!=="browser-receipt")throw new S("invalid_record");return r}var rw=(e,t)=>pi(e,t),nw=(e,t)=>pi(e,t);async function yf(e,t,r){return{id:t.id,revision:t.revision,backup:await li(t,r,JSON.stringify([e,t.id,t.revision]))}}var ow=(e,t)=>pi(e,t);var hc=8453,Y0="TransferWithAuthorization",iw=[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}],sw=(e,t)=>({domain:{name:"USD Coin",version:"2",chainId:hc,verifyingContract:e},types:{[Y0]:iw},primaryType:Y0,message:t}),bf=new TextEncoder,mc=(...e)=>st(e),Ze=e=>vd(e);function Mt(e,t,r){if(!new RegExp(`^0x[0-9a-fA-F]{${2*t}}$`).test(e))throw new TypeError(`${r} must be 0x and ${t} bytes of hex`);return Uint8Array.from(e.slice(2).match(/../g)??[],n=>Number.parseInt(n,16))}function Ge(e){if(e<0n||e>=2n**256n)throw new RangeError("not a uint256");return Mt(`0x${e.toString(16).padStart(64,"0")}`,32,"word")}var mt=e=>mc(new Uint8Array(12),Mt(e,20,"address"));function gf(e,t){let r=Pe(bf.encode("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")),n=Pe(mc(r,Pe(bf.encode("USD Coin")),Pe(bf.encode("2")),Ge(BigInt(hc)),mt(e))),o=Pe(bf.encode(`${Y0}(${iw.map(s=>`${s.type} ${s.name}`)})`)),i=Pe(mc(o,mt(t.from),mt(t.to),Ge(t.value),Ge(t.validAfter),Ge(t.validBefore),Mt(t.nonce,32,"nonce")));return Pe(mc(new Uint8Array([25,1]),n,i))}function wf(e,t){if(!/^0x[0-9a-fA-F]{130}$/.test(t))return null;let r=Mt(t,65,"signature"),n=r[64]??0,o=BigInt(Ze(r.subarray(32,64)));if(n!==27&&n!==28||o>eo.Point.Fn.ORDER/2n)return null;try{let i=eo.Point.fromBytes(eo.recoverPublicKey(mc(new Uint8Array([n-27]),r.subarray(0,64)),e,{prehash:!1}));return Ze(Pe(i.toBytes(!1).subarray(1)).subarray(12))}catch{return null}}var re=class extends S{code;purchase;retryAfterSeconds;constructor(t,r=t){super(t,r),this.code=t,this.name="PayError"}},Sf=class extends re{constructor(){super("base_rpc_rate_limited","Base RPC rate limited (429)"),this.name="BaseRpcRateLimited"}},ie=(e,t)=>{throw new re(e,t)},Bt=e=>ie("transport",`malformed Base RPC answer: ${e}`),TS=0;async function aw(e,t,r){let n=`annon-base-${++TS}`,o;try{let i=await fetch(e,{credentials:"omit",method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:n,method:t,params:r}),signal:AbortSignal.timeout(C0)}),s=()=>{if(i.status===429)throw new Sf;return ie("transport",`Base RPC HTTP ${i.status}`)};try{o=await i.json()}catch(a){if(!i.ok)return s();throw a}if(i.status===429||!i.ok&&(!o||typeof o!="object"||Array.isArray(o)||o.jsonrpc!=="2.0"&&o.id!==n||!("result"in o)&&!("error"in o)))return s()}catch(i){if(i instanceof re)throw i;return ie("transport",`Base RPC unreachable: ${i.message}`)}return o?.id!==n?Bt("a reply to another request"):o}async function uo(e,t,r){let n=await aw(e,t,r);return n.error&&ie(t==="eth_call"&&n.error.code===3?"refused":"transport",`Base RPC error: ${JSON.stringify(n.error)}`),n.result===void 0?Bt(`no result for ${t}`):n.result}var bc=e=>typeof e=="string"&&/^0x([0-9a-fA-F]{2})*$/.test(e),yc=(e,t)=>{if(typeof e!="string"||!/^0x(0|[1-9a-f][0-9a-f]*)$/i.test(e))return Bt(t);let r=Number.parseInt(e,16);return Number.isSafeInteger(r)?r:Bt(t)},hi=e=>`0x${e.toString(16)}`,J0=e=>Pe(new TextEncoder().encode(e)).subarray(0,4),Q0=(...e)=>Ze(Uint8Array.from(e.flatMap(t=>Array.from(t))));async function lo(e){return await uo(e,"eth_chainId",[])!=="0x2105"&&ie("network_mismatch","the Base RPC is not on Base mainnet (chain 8453)"),cs(e,"latest")}async function cs(e,t){let r=await uo(e,"eth_getBlockByNumber",[typeof t=="number"?hi(t):t,!1]);return{number:yc(r?.number,"block number"),timestamp:yc(r?.timestamp,"timestamp"),...typeof r?.hash=="string"?{hash:r.hash.toLowerCase()}:{}}}async function em(e,t,r,n){let o=await uo(e,"eth_call",[{to:t,data:r},hi(n)]);return!bc(o)||o.length!==66?Bt("eth_call result"):o.toLowerCase()}var cw=async(e,t,r,n)=>BigInt(await em(e,t,r,n)),Ef=(e,t,r,n)=>cw(e,t,Q0(J0("balanceOf(address)"),mt(r)),n),IS=async(e,t,r,n,o)=>await cw(e,t,Q0(J0("authorizationState(address,bytes32)"),mt(r),Mt(n,32,"nonce")),o)!==0n;async function tm(e,t,r){let n=await uo(e,"eth_getCode",[t,hi(r)]);return bc(n)?n.toLowerCase():Bt("eth_getCode result")}var _f=async(e,t,r)=>await tm(e,t,r)!=="0x";function kS(e,t){let r=Mt(t,65,"signature");return Q0(J0("transferWithAuthorization(address,address,uint256,uint256,uint256,bytes32,uint8,bytes32,bytes32)"),mt(e.from),mt(e.to),Ge(e.value),Ge(e.validAfter),Ge(e.validBefore),Mt(e.nonce,32,"nonce"),Ge(BigInt(r[64]??0)),r.subarray(0,32),r.subarray(32,64))}async function dw(e,t,r,n){let o=await aw(e,"eth_call",[{from:r.from,to:t,data:kS(r,n)},"latest"]);if(o.error){let i=String(o.error.message??"");o.error.code===3&&ie("payment_rejected",`USDC refused the authorization: ${i}`),ie("transport",`Base RPC error: ${JSON.stringify(o.error)}`)}bc(o.result)||Bt("eth_call result")}var BS=[["parentHash","bytes"],["sha3Uncles","bytes"],["miner","bytes"],["stateRoot","bytes"],["transactionsRoot","bytes"],["receiptsRoot","bytes"],["logsBloom","bytes"],["difficulty","int"],["number","int"],["gasLimit","int"],["gasUsed","int"],["timestamp","int"],["extraData","bytes"],["mixHash","bytes"],["nonce","bytes"],["baseFeePerGas","int"],["withdrawalsRoot","bytes"],["blobGasUsed","int"],["excessBlobGas","int"],["parentBeaconBlockRoot","bytes"],["requestsHash","bytes"]],fw=(e,t)=>{if(e<56)return[t+e];let r=[];for(let n=e;n>0;n=Math.floor(n/256))r.unshift(n%256);return[t+55+r.length,...r]},PS=e=>e.length===1&&(e[0]??0)<128?[...e]:[...fw(e.length,128),...e],RS=e=>{let t=BigInt(e);if(t===0n)return new Uint8Array;let r=t.toString(16);return Uint8Array.from((r.length%2?`0${r}`:r).match(/../g)??[],n=>Number.parseInt(n,16))},OS=(e,t)=>bc(e)?Uint8Array.from(e.slice(2).match(/../g)??[],r=>Number.parseInt(r,16)):Bt(`header ${t}`);async function uw(e,t){let r=await uo(e,"eth_getBlockByHash",[t,!1]),o=BS.filter(([s])=>r?.[s]!==void 0).flatMap(([s,a])=>PS(a==="int"?RS(String(r[s])):OS(r[s],s))),i=Uint8Array.from([...fw(o.length,192),...o]);return Ze(Pe(i))!==t.toLowerCase()?ie("transport",`block ${t}: the rebuilt header does not hash to it`):Ze(i)}var X0=e=>Ze(Pe(new TextEncoder().encode(e))),mi={authorizationUsed:X0("AuthorizationUsed(address,bytes32)"),authorizationCanceled:X0("AuthorizationCanceled(address,bytes32)"),transfer:X0("Transfer(address,address,uint256)")},xf=(e,t)=>typeof e=="string"&&/^0x[0-9a-fA-F]{64}$/.test(e)?e.toLowerCase():Bt(t);function rm(e){return typeof e?.address!="string"||!/^0x[0-9a-fA-F]{40}$/.test(e.address)?Bt("log address"):!Array.isArray(e.topics)||!bc(e.data)||typeof e.removed!="boolean"?Bt("log"):{address:e.address.slice(2).toLowerCase(),block_hash:xf(e.blockHash,"log blockHash").slice(2),block_number:yc(e.blockNumber,"log blockNumber"),data:e.data.toLowerCase(),log_index:yc(e.logIndex,"log logIndex"),removed:e.removed,topics:e.topics.map(t=>xf(t,"log topic").slice(2)),transaction_hash:xf(e.transactionHash,"log transactionHash").slice(2),transaction_index:yc(e.transactionIndex,"log transactionIndex")}}var gr=e=>e.slice(2).toLowerCase(),vf=e=>gr(Ze(mt(e)));function CS(e,t){let r=e;if(r?.status!=="0x1"||!Array.isArray(r.logs))return null;let n=xf(r.transactionHash,"receipt transactionHash").slice(2),o=r.logs.map(rm),i=(f,u)=>l=>l.transaction_hash===n&&!l.removed&&l.address===gr(f)&&l.topics.length===3&&l.topics[0]===gr(u),s=(f,u)=>BigInt(`0x${f.slice(2+u*64,2+(u+1)*64)||"0"}`),a=o.findIndex(f=>i(t.usdc,mi.authorizationUsed)(f)&&f.topics[1]===vf(t.from)&&f.topics[2]===gr(t.nonce)),[c,d]=[o[a],o[a+1]];return a<0||!c||!d||!i(t.usdc,mi.transfer)(d)||d.log_index!==c.log_index+1||d.topics[1]!==vf(t.from)||d.topics[2]!==vf(t.to)||d.data.length!==66?null:s(d.data,0)===t.price?[c,d]:null}async function US(e,t,r,n){let o=Math.max(1,(Number(r)-(await cs(e,t)).timestamp)*5);for(let i=t+o;;i+=o,o*=2){if(i>=n.number)return n.number;if(BigInt((await cs(e,i)).timestamp)>=r)return i}}async function NS(e,t,r,n){for(let o=r;o<=n;o+=1e4){let i=Math.min(n,o+9999),s=[mi.authorizationCanceled,Ze(mt(t.from)),t.nonce.toLowerCase()],a=await uo(e,"eth_getLogs",[{address:t.usdc,fromBlock:hi(o),toBlock:hi(i),topics:s}]);if(!Array.isArray(a))return Bt("eth_getLogs result");for(let c of a.map(rm).filter(d=>!d.removed))return c.address!==gr(t.usdc)||c.topics.join()!==s.map(gr).join()||c.block_number<o||c.block_number>i?Bt("eth_getLogs returned a log the query did not ask for"):c.block_number}return null}async function lw(e,t){let r=await cs(e,"finalized"),n=await lo(e),o=await US(e,t.block,t.validBefore,n),i={address:t.usdc,fromBlock:hi(t.block),toBlock:hi(o),topics:[[mi.authorizationUsed,mi.authorizationCanceled],Ze(mt(t.from)),t.nonce.toLowerCase()]},s=await uo(e,"eth_getLogs",[i]);if(!Array.isArray(s))return Bt("eth_getLogs result");let a=s.map(rm).filter(f=>!f.removed);for(let f of a)if(f.address!==gr(t.usdc)||f.topics.length!==3||!i.topics[0].some(u=>gr(u)===f.topics[0])||f.topics[1]!==vf(t.from)||f.topics[2]!==gr(t.nonce)||f.block_number<t.block||f.block_number>o)return Bt("eth_getLogs returned a log the query did not ask for");let c=a.find(f=>f.topics[0]===gr(mi.authorizationUsed));if(c){let f=await uo(e,"eth_getTransactionReceipt",[`0x${c.transaction_hash}`]),u=CS(f,t);return!u?.[0]||u[0].transaction_hash!==c.transaction_hash?ie("transport","the authorization was used, but not for this purchase as expected"):{state:"paid",txHash:`0x${u[0].transaction_hash}`,logIndex:u[0].log_index,logs:u}}let d=a.find(f=>f.topics[0]===gr(mi.authorizationCanceled));if(d)return d.block_number<=r.number?{state:"canceled"}:{state:"pending"};if(await IS(e,t.usdc,t.from,t.nonce,n.number)){let f=await NS(e,t,o+1,n.number);return f!==null?f<=r.number?{state:"canceled"}:{state:"pending"}:ie("transport","USDC marks the authorization used, but the RPC returned no log for it")}return BigInt(r.timestamp)>=t.validBefore?{state:"expired"}:{state:"pending"}}function om(e){let t=e.recipients.length;if(e.allocations.length!==t)throw new TypeError("one allocation per recipient");if(!Number.isInteger(e.distributionIncentive)||e.distributionIncentive<0||e.distributionIncentive>65535)throw new RangeError("distributionIncentive is a uint16");let r=st([Ge(BigInt(t)),...e.recipients.map(mt)]),n=st([Ge(BigInt(t)),...e.allocations.map(Ge)]),o=st([Ge(4n*32n),Ge(4n*32n+BigInt(r.length)),Ge(e.totalAllocation),Ge(BigInt(e.distributionIncentive))]);return st([Ge(32n),o,r,n])}var FS=e=>Ze(Pe(om(e))),mw=[{kind:"push",factory:"0x8e8eb0cc6ae34a38b67d5cf91aca38f60bc3ecf4",implementation:"0x1e2086a7e84a32482ac03000d56925f607ccb708"},{kind:"pull",factory:"0x6b9118074ab15142d7524e8c4ea8f62a3bdb98f1",implementation:"0x98254aedb6b2c30b70483064367f0ba24ca86244"}],hw=e=>`0x36602c57343d527f9e4ac34f21c619cefc926c8bd93b54bf5a39c7ab2127a895af1cc0691d7e3dff593da1005b3d3d3d3d363d3d37363d73${e.slice(2).toLowerCase()}5af43d3d93803e605757fd5bf3`;function MS(e,t,r,n){let o=st([Ge(64n),mt(r),om(t).subarray(32)]),i;"salt"in n?i=Pe(st([o,Mt(n.salt,32,"salt")])):i=Pe(st([Pe(o),Ge(n.nonce)]));let s=st([Mt("0x60593d8160093d39f3",9,"init"),Mt(hw(e.implementation),89,"clone"),new Uint8Array(15)]),a=Pe(st([Uint8Array.of(255),Mt(e.factory,20,"factory"),i,Pe(s)]));return Ze(a.subarray(12))}var nm=`0x${"00".repeat(20)}`,yw=e=>Ze(Pe(new TextEncoder().encode(e)).subarray(0,4)),zS=(e,...t)=>yw(e)+Ze(st(t)).slice(2),HS="(address[],uint256[],uint256,uint16)",$S=e=>om(e).subarray(32);var pw=100;function bw(e){e.recipients.length>pw&&ie("bad_requirements",`the split has more than ${pw} recipients`),e.recipients.some(t=>BigInt(t)===0n)&&ie("bad_requirements","the split pays the zero address"),e.totalAllocation<1n&&ie("bad_requirements","the split allocates nothing"),e.totalAllocation>=2n**128n&&ie("bad_requirements","the split allocations are too large to distribute")}function Af(e,t,r){if(bw(t),t.allocations.reduce((i,s)=>i+s,0n)!==t.totalAllocation)throw new RangeError("the allocations must add up to totalAllocation");let n=mw.find(i=>i.kind===e);if(!n)throw new TypeError("kind is push or pull");let o=zS(`createSplitDeterministic(${HS},address,address,bytes32)`,Ge(128n),mt(nm),mt(nm),Mt(r,32,"salt"),$S(t));return{to:n.factory,data:o,address:MS(n,t,nm,{salt:r})}}async function gw(e,t,r){if(!/^0x[0-9a-fA-F]{40}$/.test(t))throw new TypeError("address must be 0x and 20 bytes");return bw(r),LS(e,t.toLowerCase(),r,mw)}async function LS(e,t,r,n){let o=(await lo(e)).number,i=await tm(e,t,o),s=n.find(f=>i===hw(f.implementation));if(!s)return ie("bad_requirements",`${t} is not deployed as a known V2.2 clone`);let a=f=>em(e,t,yw(f),o).catch(u=>{throw u instanceof re&&u.code==="refused"&&ie("bad_requirements",`${t} does not answer ${f}: not an 0xSplits v2 split`),u});await a("splitHash()")!==FS(r)&&ie("bad_requirements","the split on chain is not the one described"),BigInt(await a("owner()"))!==0n&&ie("bad_requirements","the split has an owner who could change where the money goes"),BigInt(await a("paused()"))!==0n&&ie("bad_requirements","the split is paused");let c=(f,u)=>Number(f*1000000n/u)/1e4,d=1e6-r.distributionIncentive;return{kind:s.kind,shares:r.recipients.map((f,u)=>({recipient:f.toLowerCase(),percent:c(r.allocations[u]??0n,r.totalAllocation)*d/1e6})),distributorPercent:r.distributionIncentive/1e4}}function Tf(e,t){if(!/^(0|[1-9][0-9]*)$/.test(t.fixed)||!Number.isSafeInteger(t.bps)||t.bps<0||t.bps>1e4)throw new TypeError("invalid protocol fee");let r=BigInt(e);if(r<=0n)throw new TypeError("positive price required");let n=(BigInt(t.fixed)*10000n+r*BigInt(t.bps)+r-1n)/r;if(n>=10000n)throw new TypeError("protocol fee leaves no seller share");return Number(n)}function DS(e,t){let r=new Map;for(let f of t){if(!f.bps)continue;if(!f.identity)throw new TypeError("sponsorship treasury unavailable");let u=ne(f.identity),l=Q(u),p=e.recipients.find(m=>Q(m.identity)===l)?.bps??0;r.set(l,{identity:u,bps:Math.max(p,f.bps,r.get(l)?.bps??0)})}if(!r.size||[...r].every(([f,u])=>e.recipients.some(l=>Q(l.identity)===f&&l.bps>=u.bps))){let f=structuredClone(e),u=e.recipients[e.remainder];if(u&&r.has(Q(u.identity))){let l=e.recipients.findIndex(p=>!r.has(Q(p.identity)));l>=0&&(f.remainder=l)}return f}let n=e.recipients[e.remainder]?.identity,o=e.recipients.filter(f=>!r.has(Q(f.identity))),i=[...r.values()],s=1e4-i.reduce((f,u)=>f+u.bps,0),a=o.reduce((f,u)=>f+u.bps,0);if(!o.length||s<=0||o.length+i.length>8)throw new TypeError("fee requires seller share and one of eight recipient slots");let c=o.map(f=>({...f,bps:Math.floor(f.bps*s/a)}));c.push(...i);let d=c.find(f=>n&&!r.has(Q(f.identity))&&Q(f.identity)===Q(n))??c[0];if(!d)throw new TypeError("seller recipient required");if(d.bps+=1e4-c.reduce((f,u)=>f+u.bps,0),c.some(f=>f.bps<=0))throw new TypeError("fee rounds a recipient to zero");return c.sort((f,u)=>Ur(Tt(f.identity),Tt(u.identity))),{...e,recipients:c,remainder:c.indexOf(d)}}function If(e,t,r){if(r&&t.treasuryEvm?.kind!=="evm")throw new TypeError("EVM treasury required");return DS(e,[{identity:r?t.treasuryEvm:t.treasuryNear??t.treasuryEvm,bps:Math.max(Tf(e.price,t),r?Tf(r,t):0)}])}var qS=Object.freeze({fixed:"30000",bps:100});function ds(e,t,r=qS){for(let o of[t,r])if(!/^(0|[1-9][0-9]*)$/.test(o.fixed)||!Number.isSafeInteger(o.bps)||o.bps<0||o.bps>1e4)throw new TypeError("invalid protocol fee");let n=BigInt(e);if(n<=0n)throw new TypeError("positive price required");return BigInt(t.fixed)*10000n+n*BigInt(t.bps)>BigInt(r.fixed)*10000n+n*BigInt(r.bps)}function po(e,t){let r=(n,o)=>{let i=Tf(n,t);if(i&&(!o||!e.near.recipients.some(s=>Q(s.identity)===Q(o)&&s.bps>=i)))throw new TypeError("required treasury share missing")};if(r(e.near.price,e.base?t.treasuryEvm:t.treasuryNear??t.treasuryEvm),e.base){if(t.treasuryEvm?.kind!=="evm"&&Tf(e.base.price,t))throw new TypeError("EVM treasury required");r(e.base.price,t.treasuryEvm)}}var Vt=class extends S{constructor(r,n){super("transaction_uncertain","Transaction submission is uncertain. Check the saved purchase and transaction hash before retrying.");this.txHash=r;this.purchaseId=n;this.name="TransactionUncertain"}txHash;purchaseId;code="transaction_uncertain"};var fs=e=>({nearUsdc:e.near.token,...e.base?{baseUsdc:e.base.usdc}:{}}),jr=`0x${"00".repeat(32)}`;function kf(e){return e.kind==="near"?["stage","deposit","register","fund","publish"]:e.kind==="evm"?["stage","split","register","publish"]:["stage","register","publish"]}function as(e){let t=e.hosting;if(!t)return;let r=e.terms;if(tt(r,fs(r)),!t||typeof t!="object"||t.origin!==di(t.origin)||!Array.isArray(t.steps)||!Array.isArray(t.completed)||JSON.stringify(t.steps)!==JSON.stringify(kf(r.seller))||t.completed.some((o,i)=>o!==t.steps[i])||t.completed.length>t.steps.length||typeof t.backupConfirmed!="boolean")throw new Error("Invalid hosted record.");if(r.seller.kind==="evm"&&(!r.base||!e.baseSplit||e.baseSplit.kind!=="push"||e.baseSplit.salt!==jr||e.baseSplit.address!==r.base.pay_to))throw new Error("Invalid Base terms.");if(r.seller.kind==="near"&&t.fee!==null)throw new Error("Invalid direct fee.");if(t.fee!==null&&t.fee===void 0)throw new Error("Missing fee.");if(t.fee&&po(r,t.fee),r.seller.kind!=="evm"&&(r.base!==null||e.baseSplit!==null))throw new Error("Invalid seller routes.");if(t.pending!==null&&(!t.pending||t.pending.step!==t.steps[t.completed.length]||typeof t.pending.token!="string"))throw new Error("Invalid pending operation.");if(t.pending?.operation&&["deposit","fund"].includes(t.pending.step)){let{snapshot:o,validUntil:i}=t.pending;if(t.pending.step==="deposit"&&typeof t.pending.storageAccountExisted!="boolean"||typeof o!="string"||!/^(0|[1-9][0-9]*)$/.test(o)||BigInt(o)>=2n**128n||!Number.isSafeInteger(i)||(i??-1)<0)throw new Error("Invalid funding snapshot.")}if(t.pending?.startedAt!==void 0&&(!Number.isSafeInteger(t.pending.startedAt)||t.pending.startedAt<0))throw new Error("Invalid operation checkpoint.");if(t.lease!==null&&(!t.lease||typeof t.lease.owner!="string"||!Number.isSafeInteger(t.lease.until)))throw new Error("Invalid lease.");if(t.completed.length&&!t.backupConfirmed)throw new Error("Missing backup confirmation.");if(t.uploadId!==null&&!/^[0-9a-f]{64}$/.test(t.uploadId))throw new Error("Invalid upload.");let n=z0({intent:t.intent,manifest:t.manifest,terms:r,metadata:t.metadata,auth:t.authorization?.auth??(r.seller.kind==="near"?{kind:"near",accountId:r.seller.id,publicKey:"",signature:""}:{kind:r.seller.kind,sig:`0x${"00".repeat(r.seller.kind==="evm"?65:64)}`})});if(n.intent.termsHash!==tt(r,fs(r))||n.intent.fileId!==r.file_id||n.intent.cipherHash!==r.cipher_hash||n.intent.hostOrigin!==t.origin||Q(n.intent.seller)!==Q(r.seller))throw new Error("Invalid hosted binding.");if(t.authorization&&JSON.stringify(t.authorization.intent)!==JSON.stringify(t.intent))throw new Error("Invalid authorization binding.");if(r.seller.kind==="near"&&(!t.listingStorage||!e.storageBudget||!/^[1-9][0-9]*$/.test(t.listingStorage)||BigInt(t.listingStorage)>=2n**128n))throw new Error("Missing approved funding.");if(t.reservation){let o=nf(t.reservation);for(let i of["fileId","termsHash","cipherHash","metadataHash","hostOrigin","byteSize","plaintextSize","headerSize","network","contract"])if(o[i]!==t.intent[i])throw new Error("Invalid reservation binding.");if(o.uploadId!==t.uploadId||Q(o.seller)!==Q(r.seller))throw new Error("Invalid reservation.")}if(t.split!==null&&(!t.split||r.seller.kind!=="evm"||!["pending","ready"].includes(t.split.state)||t.split.address.toLowerCase()!==r.base?.pay_to||t.split.kind!=="push"||t.split.salt!==jr||!(t.split.txHash===null||typeof t.split.txHash=="string")))throw new Error("Invalid split checkpoint.");if(t.completed.includes("split")&&t.split?.state!=="ready")throw new Error("Missing split confirmation.");if(t.result!==null){let o=t.result,i=`${t.origin}/f/${r.file_id.slice(2)}`;if(!o||o.fileId!==r.file_id||o.url!==i||o.header!==`${i}/header`||o.expiresAt!==null&&(!Number.isSafeInteger(o.expiresAt)||o.expiresAt<=0)||t.completed.at(-1)!=="publish"||!t.header||!e.published)throw new Error("Invalid publication.")}if(!!e.published!=(t.result!==null))throw new Error("Invalid completion.");t.header!==null&&G(t.header,(t.header.length-2)/2)}function Bf(e){let t=e instanceof Uint8Array?e.length:e.size;if(!Number.isSafeInteger(t)||t<0)throw new S("invalid_arguments");if(t>5e7)throw new S("too_large");return t}var ww=172800;function mo(e){if(!e.ok)throw e.error;return e.value}function xw(e){if(e.identity.kind!=="near"||!("call"in e))throw new S("near_wallet_required");return e}var Pf=class{constructor(t,r){this.o=t;this.context=r;this.store=hf(t.rawStore,t.backupSecret)}o;context;store;quotes=new Map;async direct(t,r,n,o){let i=await xw(t).call({receiverId:this.o.contractId,method:r,args:n,deposit:o});if(!i||typeof i!="object"||!("transaction"in i))return i;let s=i.transaction;try{let a=ci(i,this.o.contractId,{txHash:s.hash,signer:t.identity.id,method:r,args:n});if(a.state==="released")return a.answer;if(a.state==="done")return a.value}catch{throw new Vt(s.hash)}throw new Vt(s.hash)}async fundingBalance(t,r){let n=r==="deposit"?await Lr(this.o.nearRpc,this.o.contractId,"storage_balance_of",{account_id:t.terms.seller.id}):(await this.context.file(t.terms.file_id))?.purchaseStorageBalance?.toString();if(n===null&&r==="deposit")return null;if(typeof n!="string"||!/^(0|[1-9][0-9]*)$/.test(n)||BigInt(n)>=2n**128n)throw new S("invalid_response");return BigInt(n)}now(){return(this.o.now??(()=>Math.floor(Date.now()/1e3)))()}key(t){return G(t,32),`annon/sell/${t}`}async load(t){try{let r=await this.store.load(this.key(t));if(!r?.hosting||r.terms.network!==this.o.network||r.terms.contract!==this.o.contractId)throw new Error;if(as(r),await F0(r.hosting.metadata)!==r.hosting.intent.metadataHash)throw new Error;return r}catch(r){throw new S("invalid_record",void 0,{cause:r})}}async save(t,r){if(as(r),!await this.store.compareAndSet(this.key(r.terms.file_id),t,r))throw new S("store_conflict");return await this.o.writeBackup(r.id,await wn(r,this.o.backupSecret)),r}async quote(t){if(!t.hosting?.origin)throw new S("transport_required");let r=di(t.hosting.origin),n=Bf(t.data),o=ne(t.seller.identity);if(o.kind==="near"&&(!t.listingStorage||!t.storageBudget))throw new S("storage_required");for(let E of[t.listingStorage,t.storageBudget])if(E!==void 0&&(E<=0n||E>=2n**128n))throw new S("invalid_arguments");if(o.kind!=="near"&&(t.listingStorage!==void 0||t.storageBudget!==void 0))throw new S("near_wallet_required");let i=sf({filename:t.name,title:t.title??t.name,description:t.description??""}),s=await this.context.config();if(s.network!==this.o.network)throw new S("network_mismatch");let a=t.near?.recipients??[{identity:o,bps:1e4}],c=t.near?.remainder??o,d={token:s.nearUsdc,price:t.price,recipients:structuredClone(a),remainder:a.findIndex(E=>Q(E.identity)===Q(c))},f=null;if(o.kind!=="near"&&this.o.sponsorship){if(f=(await this.o.sponsorship()).fee,ds(t.price,f,this.o.maxProtocolFee)&&!t.onSplit)throw new S("protocol_fee_above_max");d=If(d,f,o.kind==="evm"?t.price:void 0)}let u=d.recipients[d.remainder]?.identity;d.recipients.sort((E,B)=>Ur(Tt(E.identity),Tt(B.identity))),d.remainder=d.recipients.findIndex(E=>Q(E.identity)===Q(X(u)));let l=`0x${Y(crypto.getRandomValues(new Uint8Array(32))).slice(2)}`,p=crypto.getRandomValues(new Uint8Array(32)),m=await ui(p,t.data,{fileId:G(l,32),name:i.filename,mime:t.mime,authKind:hr(o)}),h={network:s.network,contract:this.o.contractId,file_id:l,seller:o,pay2_version:2,cipher_hash:Y(m.cipherHash),moderator:null,near:d,base:null},y=null;if(o.kind==="evm"){if(d.recipients.some(B=>B.identity.kind!=="evm"))throw new S("bad_requirements");let E=Af("push",{recipients:d.recipients.map(B=>B.identity.id),allocations:d.recipients.map(B=>BigInt(B.bps)),totalAllocation:10000n,distributionIncentive:0},jr);y={address:E.address,kind:"push",salt:jr},h.base={usdc:s.usdc,price:t.price,pay_to:E.address}}let b=tt(h,{nearUsdc:s.nearUsdc,baseUsdc:s.usdc});f&&po(h,f);let x=m.headerSize(this.o.contractId),g={network:s.network,contract:this.o.contractId,seller:o,fileId:l,cipherHash:h.cipher_hash,termsHash:b,byteSize:x+n+m.manifest.metaLen+16*m.manifest.n,plaintextSize:n,headerSize:x,hostOrigin:r,metadataHash:await F0(i),nonce:Y(crypto.getRandomValues(new Uint8Array(32))),expiresAt:this.now()+600},w={kind:"sell",id:`sell:${l}`,revision:0,terms:h,baseSplit:y,fileKey:Y(p),sellerSecret:Y(fo().secret),deadline:this.now()+540,name:i.filename,mime:t.mime,previewLen:0,ckdSecret:null,...t.storageBudget?{storageBudget:String(t.storageBudget)}:{},hosting:{origin:r,metadata:i,fee:f,intent:g,manifest:m.manifest,authorization:null,uploadId:null,reservation:null,split:null,steps:kf(o),completed:[],pending:null,lease:null,backupConfirmed:!1,listingStorage:t.listingStorage?String(t.listingStorage):null,header:null,result:null}},v=crypto.randomUUID();return this.quotes.set(v,{job:structuredClone(w),input:t}),structuredClone({quoteId:v,fileId:l,terms:h,fee:f,steps:w.hosting.steps,metadata:i,listingStorage:w.hosting.listingStorage,storageBudget:w.storageBudget??null})}async begin(t){let r=this.quotes.get(t);if(!r)throw new S("invalid_arguments");let n=await this.save(null,structuredClone(r.job));return this.quotes.delete(t),n}async confirmBackup(t){let r=await this.load(t),n=r.hosting;if(n.backupConfirmed)return r;if(n.pending||n.lease)throw Object.assign(new S("lease_busy"),{retryAfterSeconds:5});return this.save(r,{...r,revision:r.revision+1,hosting:{...n,backupConfirmed:!0}})}async discard(t){let r=await this.load(t);if(r.hosting.lease&&r.hosting.lease.until>this.now())throw Object.assign(new S("lease_busy"),{retryAfterSeconds:5});if(!await this.store.compareAndSet(this.key(t),r,null))throw new S("store_conflict")}async backup(t){return wn(await this.load(t),this.o.backupSecret)}async prepared(t,r){let n=Bf(r.data);if(!t.fileKey)throw new S("invalid_record");if(n!==t.hosting?.intent.plaintextSize)throw new S("source_changed");let o=await ui(G(t.fileKey,32),r.data,{fileId:G(t.terms.file_id,32),name:t.name,mime:t.mime,authKind:hr(t.terms.seller)});if(Y(o.cipherHash)!==t.terms.cipher_hash)throw new S("source_changed");return o}async verifySource(t,r){await this.prepared(await this.load(t),{data:r})}async next(t,r){return await this.advance(t,r),this.load(t)}async advance(t,r){let n=await this.load(t);if(r.expectedRevision!==void 0&&r.expectedRevision!==n.revision)throw new S("store_conflict");if(Q(ne(r.seller.identity))!==Q(n.terms.seller))throw new S("wrong_identity");if(di(r.hosting.origin)!==n.hosting.origin)throw new S("config_conflict");if(n.published)return n;if(!n.hosting.backupConfirmed)throw new S("backup_secret_required");if(n.hosting.lease&&n.hosting.lease.until>this.now())throw Object.assign(new S("lease_busy"),{retryAfterSeconds:5});let o=crypto.randomUUID();n=await this.save(n,{...n,revision:n.revision+1,hosting:{...n.hosting,lease:{owner:o,until:this.now()+120}}});let i=async()=>{let T=await this.load(t);if(l||T.revision!==n.revision||T.hosting.lease?.owner!==o||T.hosting.lease.until<=this.now())throw Object.assign(new S("lease_busy"),{retryAfterSeconds:5});if(Q(ne(r.seller.identity))!==Q(n.terms.seller))throw new S("wrong_identity")},s=!1,a=!1,c=!1,d=null,f="",u=Promise.resolve(),l=!1,p=async(T,O={})=>{if(await i(),n=await this.save(n,{...n,...T,revision:n.revision+1,hosting:{...n.hosting,...O,lease:O.lease===null?null:{owner:o,until:this.now()+120}}}),d&&O.lease!==null){await i();let z={...n,revision:d.revision+1,hosting:{...n.hosting,lease:null}};if(!await this.store.compareAndSet(f,d,z))throw new S("store_conflict");d=z}},m=(T,O={})=>{let z=u.then(()=>p(T,O));return u=z.catch(()=>{}),z},h=setInterval(()=>{m({},{lease:{owner:o,until:this.now()+120}}).catch(()=>{l=!0})},3e4),y=async T=>{await u,await i();let O=await T();return await u,await i(),O},b=new sc(n.hosting.origin,this.o.fetch?{fetch:this.o.fetch}:{}),x=async()=>{let T={...n.hosting.intent,expiresAt:this.now()+600};s=!0;let O=await y(async()=>{if(n.terms.seller.kind==="near"){if(!r.hosting.signUpload)throw new S("missing_method");return r.hosting.signUpload(structuredClone(T))}let z=await r.seller.authorize(co(T));if(!z||!lt(n.terms.seller,co(T),z))throw new S("invalid_signature");return z});s=!1,await y(()=>Fg({intent:T,auth:O},{network:this.o.network,contract:this.o.contractId,hostOrigin:n.hosting.origin,now:this.now(),nearRpc:this.o.nearRpc})),await m({},{intent:T,authorization:{intent:T,auth:O}})},g=async(T,O)=>{if(!r.hosting.spool)throw new S("transport_required","A ciphertext spool is required.");await T.stage(r.hosting.spool,async z=>{let P=r.hosting.body?await r.hosting.body(z):z.read(),_=mo(await y(()=>b.body(O,X(n.hosting.authorization),P)));await m({},{reservation:_.reservation})})},w=async()=>{let T=n.hosting,O=mo(await y(()=>b.create({...X(T.authorization),terms:n.terms,manifest:T.manifest,metadata:T.metadata})));if(T.uploadId&&T.uploadId!==O.uploadId)throw new S("upload_conflict");return await m({},{uploadId:O.uploadId,...O.state==="reserved"?{reservation:O.reservation}:{}}),O},v=async()=>n.hosting.authorization&&n.hosting.intent.expiresAt<=this.now()?(await x(),w()):null,E=async()=>m({},{completed:[...n.hosting.completed,X(n.hosting.pending).step],pending:null}),B=async()=>{if(await i(),d&&!await this.store.compareAndSet(f,d,null))throw new S("store_conflict");d=null,await m({},{pending:null})},N=async(T,O,z)=>{a=!0;let P=await this.direct(r.seller,T,O,z);return a=!1,P},U=(T=30)=>Object.assign(new S("transaction_uncertain"),{retryAfterSeconds:T}),R=async(T,O)=>{let z=X(n.hosting.pending),P=!z.txHash,_=z.validUntil===void 0?z.startedAt:z.validUntil-ww;if(P&&_===void 0)throw U();return y(async()=>{try{return await Og(this.o.nearRpc,O,n.terms.seller.id,this.o.contractId,"FINAL",{...T,...P?{notBefore:X(_)}:{}})}catch(I){throw P?U():I}})};try{let T=n.hosting,O=T.steps[T.completed.length];if(!O)throw new S("invalid_record");if(f=`annon/share-operation/${t}/${O}`,d=await this.store.load(f),await i(),d&&!T.pending){if(tt(d.terms,fs(d.terms))!==T.intent.termsHash)throw new S("invalid_record");if(await m({...d,revision:n.revision},{...X(d.hosting),lease:T.lease}),n.hosting.completed.includes(O)||n.published)return n;T=n.hosting}if(r.txHash!==void 0&&(typeof r.txHash!="string"||!r.txHash||n.terms.seller.kind!=="near"||!T.pending?.operation||!["deposit","fund","publish"].includes(O)))throw new S("invalid_arguments");if(T.pending&&(O==="stage"&&!T.authorization||O==="publish"&&!T.header||O==="register"&&n.terms.seller.kind!=="near"&&!T.pending.auth)&&(await B(),T=n.hosting),T.pending){if(O==="register"){let P=await y(()=>this.context.file(t));if(P){if(P.termsHash!==T.intent.termsHash)throw new S("file_mismatch");await E()}else{let _=T.pending,k=_.operation?.args?.args?.deadline;if(typeof k=="number"&&this.now()>k+60)await B();else if(_.operation?.method==="register"&&_.auth){let M=await y(()=>this.context.call("register",{...X(_.operation).args,auth:_.auth,hostingReservation:T.reservation,...n.baseSplit?{baseSplit:{kind:"push",salt:jr}}:{}},r.seller)),$=await y(()=>this.context.answer(M,Gt(G(X(n.sellerSecret),32)).secret,t));await m({ckdSecret:Y($)}),await E()}else throw new S("transaction_uncertain")}}else if(["deposit","fund"].includes(O)){let P=T.pending;if(!P.operation)await B();else if(P.txHash||r.txHash){let _=await R(P.operation,X(P.txHash??r.txHash));if(_.state==="refused")await B();else{if(_.state!=="done")throw U();await E()}}else{let _=await y(()=>this.fundingBalance(n,O));if(O==="deposit"&&P.storageAccountExisted===!1?(_??0n)>0n:(_??0n)>=BigInt(X(P.snapshot))+BigInt(P.operation.deposit))await E();else if(this.now()>X(P.validUntil))await B();else throw U(Math.max(1,X(P.validUntil)-this.now()))}}else if(T.authorization&&["stage","split","publish"].includes(O)){await v(),n.hosting.uploadId||await w(),T=n.hosting;let P=mo(await y(()=>b.status(X(T.uploadId),X(T.authorization))));if(O==="stage"&&P.state!=="published")P.state==="receiving"?await g(await this.prepared(n,r),X(T.uploadId)):await m({},{reservation:P.reservation}),await E();else if(O==="split"){let _=P.baseSplit?.state==="ready"?P.baseSplit:mo(await y(()=>b.baseSplit(X(T.uploadId),X(T.authorization),{kind:"push",salt:jr}))).baseSplit;if(this.checkSplit(n,_),await m({},{split:_}),_?.state!=="ready")throw new S("settlement_pending");await E()}else if(O==="publish"&&P.state==="published")await this.finishPublication(P.result,n,m);else if(O==="publish"&&T.header){if(n.terms.seller.kind==="near"){let I=await y(()=>this.context.file(t)),k=G(T.header,(T.header.length-2)/2);if(I?.headerHash!==Y(await Oe(k.subarray(0,k.length-65)))){let M=X(T.pending),$=M.txHash??r.txHash;if($){let F=X(M.operation),A=await R(F,$);if(A.state==="refused")return await B(),n;if(A.state!=="done")throw U()}else return await B(),n}}let _=mo(await y(()=>b.header(X(T.uploadId),X(T.authorization),new Uint8Array(G(X(T.header),(X(T.header).length-2)/2)))));await this.finishPublication(_,n,m)}else throw new S("transaction_uncertain")}else throw new S("transaction_uncertain");return n}c=!0;let z=await this.prepared(n,r);if(await i(),await m({},{pending:{step:O,token:crypto.randomUUID(),startedAt:this.now()}}),!d){let P={...n,revision:0,hosting:{...n.hosting,lease:null}};if(await i(),!await this.store.compareAndSet(f,null,P))throw new S("store_conflict");d=P}if(O!=="stage"&&await v(),T=n.hosting,O==="stage"){await x();let P=await w();if(P.state==="published")return await this.finishPublication(P.result,n,m),n;P.state==="receiving"&&await g(z,P.uploadId)}else if(O==="split"){if(n.terms.seller.kind!=="evm"||!n.terms.base)throw new S("route_unavailable");await this.live(n,b,y);let P=mo(await y(()=>b.baseSplit(X(T.uploadId),X(T.authorization),{kind:"push",salt:jr}))).baseSplit;if(this.checkSplit(n,P),await m({},{split:P}),P?.state!=="ready")throw new S("settlement_pending")}else if(O==="deposit"||O==="fund"){await this.live(n,b,y);let P=xw(r.seller),_={method:O==="deposit"?"storage_deposit":"fund_file_storage",args:O==="deposit"?{account_id:P.identity.id}:{file_id:t},deposit:O==="deposit"?X(T.listingStorage):X(n.storageBudget)},I=await y(()=>this.fundingBalance(n,O));await m({},{pending:{...X(n.hosting.pending),operation:_,snapshot:(I??0n).toString(),...O==="deposit"?{storageAccountExisted:I!==null}:{},validUntil:this.now()+ww}}),await y(()=>N(_.method,_.args,BigInt(_.deposit)))}else if(O==="register"){let P=await y(()=>this.context.file(t));if(P){if(P.termsHash!==T.intent.termsHash)throw new S("file_mismatch")}else{await this.live(n,b,y);let _=Gt(G(X(n.sellerSecret),32)),I={terms:n.terms,seller_key:Y(_.publicKeyBytes),deadline:this.now()+540};await m({},{pending:{...X(n.hosting.pending),operation:{method:"register",args:{args:I},deposit:"0"}}});let k=await y(async()=>{if(n.terms.seller.kind==="near")return N("register",{args:I},0n);s=!0;let $=await r.seller.authorize(Za(n.terms,I.seller_key,I.deadline,fs(n.terms)));if(s=!1,!$||!lt(n.terms.seller,Za(n.terms,I.seller_key,I.deadline,fs(n.terms)),$))throw new S("invalid_signature");return await m({},{pending:{...X(n.hosting.pending),auth:$}}),await i(),this.context.call("register",{args:I,auth:$,hostingReservation:n.hosting.reservation,...n.baseSplit?{baseSplit:{kind:"push",salt:jr}}:{}},r.seller)}),M=await y(()=>this.context.answer(k,_.secret,t));await m({ckdSecret:Y(M)})}}else if(O==="publish"){if(!n.ckdSecret){let _=await y(()=>this.context.reopen(t,r.seller));await m({ckdSecret:Y(_)})}let P=await y(()=>z.finish({contractId:this.o.contractId,seller:n.terms.seller,ckdSecret:G(X(n.ckdSecret),48),...n.terms.seller.kind==="near"?{}:{sign:async _=>{s=!0;let I=await y(()=>r.seller.authorize(_));if(s=!1,!I||!lt(n.terms.seller,_,I))throw new S("invalid_signature");let k=G(I.sig,n.terms.seller.kind==="evm"?65:64);return n.terms.seller.kind==="solana"?{signature:k,signedMessage:new TextEncoder().encode(_)}:k}}}));try{if(P.file instanceof ReadableStream){let I=P.file.getReader();try{for(;!(await I.read()).done;);}finally{I.releaseLock()}}if(!P.consumed())throw new S("upload_incomplete");if(await m({},{header:Y(P.header)}),n.terms.seller.kind==="near"){let I={method:"publish_header",args:{file_id:t,header_hash:Y(await Oe(P.header.subarray(0,P.header.length-65)))},deposit:"0"};await m({},{pending:{...X(n.hosting.pending),operation:I}}),await y(()=>N(I.method,I.args,0n))}let _=mo(await y(()=>b.header(X(T.uploadId),X(T.authorization),new Uint8Array(P.header))));return await this.finishPublication(_,n,m),n}catch(_){throw await P.cancel(_).catch(()=>{}),_}}return await E(),n}catch(T){if((c&&n.hosting.pending?.step==="register"&&T instanceof S&&["budget","limited","rate_limited","not_sponsored","bad_request","bad_signature","bad_deadline","upload_expired"].includes(T.code)&&!("txHash"in T)||c&&(s||a)&&T instanceof S&&T.code==="rejected"&&!("txHash"in T))&&await B(),T instanceof S&&"txHash"in T&&typeof T.txHash=="string")try{await m({},{pending:{...X(n.hosting.pending),txHash:T.txHash}})}catch{}throw T}finally{clearInterval(h),await u;try{await i(),await m({},{lease:null})}catch{}}}checkSplit(t,r){if(!r||t.terms.seller.kind!=="evm"||r.address.toLowerCase()!==t.terms.base?.pay_to||r.kind!=="push"||r.salt!==jr)throw new S("bad_response")}async live(t,r,n){let o=t.hosting;if(!o)throw new S("invalid_record");if(!o.uploadId||!o.authorization)throw new S("upload_incomplete");let i=mo(await n(()=>r.status(X(o.uploadId),X(o.authorization))));if(i.state!=="reserved"||i.reservation.expiresAt<=this.now()||i.reservation.termsHash!==o.intent.termsHash)throw new S("upload_expired")}async finishPublication(t,r,n){let o=t.expiresAt;if(o!==null){if(!Number.isSafeInteger(o)||o<=0)throw new S("bad_response");let i=this.now();if(o<=i)throw new S("file_expired")}await n({published:!0,fileKey:null,sellerSecret:null,ckdSecret:null},{result:t,completed:[...r.hosting?.steps??[]],pending:null})}};function us(e,t=Date.now()){if(!e?.trim())return;let r=e.trim();if(/^\d+$/.test(r)){let o=Number(r)*1e3;return Number.isSafeInteger(o)?o:void 0}if(!/^[A-Za-z]{3}, /.test(r))return;let n=Date.parse(r);return Number.isFinite(n)?Math.max(0,n-t):void 0}function gc(e,t){return new Promise((r,n)=>{if(t?.aborted){n(t.reason);return}let o=()=>{clearTimeout(i),n(t?.reason)},i=setTimeout(()=>{t?.removeEventListener("abort",o),r()},e);t?.addEventListener("abort",o,{once:!0})})}var jS="ANNON-BUYER-PROOF-V1_BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_",Ew="Annon-Buyer-Proof",vw=kt.longSignatures,im=new TextEncoder,GS=e=>Uint8Array.from([...im.encode("annon/v1.1 buyer proof"),10,...im.encode(e)]),_w=e=>btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"");function VS(e,t){return _w(vw.sign(vw.hash(GS(t),jS),e).toBytes(!0))}function Sw(e){if(!URL.canParse(e))return null;let t=new URL(e);return t.hash="",t.href}function Rf(e,t){let r=Sw(e);return r!==null&&r===Sw(t)}function Aw(e,t,r,n=0){if(!/^0x[0-9a-f]{64}$/.test(r)||!Number.isInteger(n)||n<0||n>4294967295)throw new TypeError("invalid purchase/grant");return _w(im.encode(JSON.stringify({purchase_id:r,grant:n,signature:VS(e,t)})))}var $e=class extends S{code;retryAfterSeconds;purchaseId;fileId;constructor(t,r=t){super(t,r),this.code=t,this.name="DownloadError"}},xn=(e,t)=>{throw new $e(e,t)};function KS(e){let t=new URL(e),r=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&r))throw new TypeError(`${e} must be https`);return t}var WS=e=>{try{return e===null?null:JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(e),t=>t.charCodeAt(0))))}catch{return null}};function Iw(e){KS(e.url);let t=We(e.header),r=y0(t),n=Array.from({length:r.n-1},(_,I)=>I===0?r.metaLen+ve:I===1&&r.previewLen>0?r.previewLen+ve:2**r.chunkLog2+ve),o=Math.min(e.maxBytes??50086016,50086016),i=_=>{_>o&&xn("too_large","File exceeds the 50 MB size limit.")};i(t.length+n.reduce((_,I)=>_+I,0)+ve);let s=2**r.chunkLog2+ve,a=e.fetch??globalThis.fetch,c=new AbortController,d=()=>{c.abort(),O?.cancel().catch(()=>{})};e.signal?.aborted&&xn("cancelled");let f=()=>e.signal?.removeEventListener("abort",d),u=()=>{c.signal.aborted&&xn("cancelled")};async function l(_){let I=()=>{},k=new Promise((M,$)=>{I=()=>$(new $e("cancelled")),c.signal.addEventListener("abort",I,{once:!0}),c.signal.aborted&&I()});try{return await Promise.race([_,k])}finally{c.signal.removeEventListener("abort",I)}}async function p(_){await l(e.wait?e.wait(_):gc(_,c.signal))}let m=0,h=0,y=t.length,b=!1,x=e.retries??3,g=e.payment,w="";if(g){let _=WS(g.header)?.resource?.url;if(typeof _!="string"||!Rf(_,e.url))throw new TypeError("the payment names another resource than the file URL");w=_}e.signal?.addEventListener("abort",d,{once:!0});let v=0,E,B=(_,I)=>(u(),l(a(e.url,{redirect:"error",credentials:"omit",signal:c.signal,headers:{..._,range:`bytes=${I}-`}}).then(async k=>(c.signal.aborted&&await k.body?.cancel().catch(()=>{}),k)))),N=_=>_.body&&(_.status===200||_.status===206);async function U(){let _=y,I=Aw(e.proof.secret,w||e.url,e.proof.purchase_id,e.proof.grant);for(let k=0;;k++){let M=await B({[Ew]:I,...g?{"PAYMENT-SIGNATURE":g.header}:{}},_);if(c.signal.aborted&&(await M.body?.cancel().catch(()=>{}),u()),N(M))return{response:M,start:_};if(M.status===416&&_>t.length){await M.body?.cancel().catch(()=>{}),_=t.length;continue}let $=M.status===503||M.status===402||M.status===429,F=M.status===429?"rate_limited":M.status===503?"unavailable":"settlement_pending",A;if([429,403,503].includes(M.status)){let j=M.body?.getReader();try{let K=[],W=0;if(j)for(;;){let Z=await l(j.read());if(Z.done||(W+=Z.value.length,W>8192))break;K.push(Z.value)}if(W<=8192){let Z=new Uint8Array(W),te=0;for(let de of K)Z.set(de,te),te+=de.length;let J=JSON.parse(new TextDecoder().decode(Z));(M.status===429&&(J.error==="download_limited"||J.error==="download_in_progress")||M.status===403&&J.error==="not_sponsored"||M.status===503&&J.error==="relayer_unavailable")&&(F=J.error),typeof J.retryAfterSeconds=="number"&&Number.isFinite(J.retryAfterSeconds)&&J.retryAfterSeconds>=0&&Number.isSafeInteger(Math.ceil(J.retryAfterSeconds))&&(A=Math.ceil(J.retryAfterSeconds))}}catch{}finally{await j?.cancel().catch(()=>{})}}else await M.body?.cancel().catch(()=>{});let H=us(M.headers.get("Retry-After"),(e.now?.()??Date.now()/1e3)*1e3);H!==void 0&&(A=Math.max(A??0,Math.ceil(H/1e3)));let D=()=>Object.assign(new $e(F),{fileId:e.fileId,purchaseId:e.proof.purchase_id,...A===void 0?{}:{retryAfterSeconds:A}});if(F==="download_limited"||F==="not_sponsored")throw D();if(!$)return xn("not_authorized",`the host answered ${M.status}`);let q=Math.max(1,A??(M.status===402?3:5))*1e3;if(k+1>=(e.settleTries??40)||q>60*1e3-m||q>60*1e3)throw D();m+=q,await p(q)}}async function R(){let{response:_,start:I}=await U(),k=Number(_.headers.get("content-length")??Number.NaN),M=Number((/\/(\d+)$/.exec(_.headers.get("content-range")??"")??[])[1]);try{i(_.status===200?k:I+k),_.status===206&&i(M)}catch(D){throw await _.body?.cancel().catch(()=>{}),D}let $=_.body.getReader(),F=_.status===200?0:I,A={cancel:()=>$.cancel(),async read(){let D=await $.read();if(u(),!D.done){F+=D.value.length;try{i(F)}catch(q){throw await $.cancel().catch(()=>{}),q}}return D}};if(O=A,_.status===200){let D=Number(_.headers.get("content-length")??Number.NaN);return E=Number.isSafeInteger(D)?D:void 0,v=y,{reader:A,rest:await Tw(A,y,t)}}let H=/^bytes (\d+)-(\d+)\/(\d+|\*)$/.exec(_.headers.get("content-range")??"");return!H||Number(H[1])!==I||Number(H[2])<I||H[3]!=="*"&&Number(H[2])>=Number(H[3])?(await A.cancel().catch(()=>{}),xn("bad_response","the host resumed from another offset")):(E=Number(H[2])+1,i(E),v=y,{reader:A,rest:I<y?await Tw(A,y-I,new Uint8Array(0)):new Uint8Array(0)})}let T,O,z=new Uint8Array(0);async function P(_,I){_=Math.min(_,Math.max(0,o-y)+1);let k=new Uint8Array(_),M=0;for(;M<_;){if(z.length===0&&!T){let F=await R();T=F.reader,z=F.rest}if(z.length===0){let F=await T.read();if(F.done){if(I&&(E===void 0||v>=E))break;throw new Error("the connection ended early")}z=F.value}let $=Math.min(_-M,z.length);k.set(z.subarray(0,$),M),z=z.subarray($),M+=$,v+=$}return k.subarray(0,M)}return new ReadableStream({async pull(_){if(u(),!b){b=!0,_.enqueue(We(t));return}for(;;)try{let I=h===r.n-1,k=await P(I?s+1:n[h],I);I&&(k.length<ve||k.length>s)&&xn("file_mismatch","the last chunk has a wrong length, or bytes follow it"),pt(await Oe(k),r.hashes[h])||xn("file_mismatch",`chunk ${h} is not the one the header names`),_.enqueue(k),h++,y+=k.length,I&&(f(),_.close(),await T?.cancel().catch(()=>{}));return}catch(I){if(await O?.cancel().catch(()=>{}),T=void 0,z=new Uint8Array(0),c.signal.aborted&&(f(),xn("cancelled")),I instanceof $e||x--<=0)throw c.abort(),f(),I}},async cancel(){c.abort(),f(),await O?.cancel().catch(()=>{})}},{highWaterMark:0})}async function Tw(e,t,r){let n=t;for(;;){let o=await e.read();if(o.done)throw new Error("the connection ended before the resume point");let i=t-n,s=Math.min(o.value.length,n,Math.max(0,r.length-i));if(pt(o.value.subarray(0,s),r.subarray(i,i+s))||xn("file_mismatch","the host sent another header"),o.value.length>=n)return o.value.subarray(n);n-=o.value.length}}function kw(e,t,r){let n=e.startsWith("0x")?e.slice(2):e;if(!new RegExp(`^[0-9a-fA-F]{${2*t}}$`).test(n))throw new TypeError(`${r} must be ${t} bytes of hex`);return`0x${n.toLowerCase()}`}function Bw(e,t,r){if(e!==t.terms.contract)throw new TypeError("terms contract mismatch");return io(t.seller_key),Za(t.terms,t.seller_key,t.deadline,r)}var Pw=e=>Bg(e);function Rw(e,t,r){return io(t.key??""),["Annon: open a file again","Signing this lets whoever holds the one-time key below open the file.",`contract: ${e}`,`file: ${kw(t.file_id,32,"file_id")}`,`seller: ${Ke(r)}`,`one-time key: ${t.key}`,`valid until: ${Vn(t.deadline)}`].join(`
49
- `)}function Ow(e,t,r){return["Annon: stop selling a file","Signing this is final: the file can't be sold again. Past buyers keep access.",`contract: ${e}`,`file: ${kw(t.file_id,32,"file_id")}`,`seller: ${Ke(r)}`,`valid until: ${Vn(t.deadline)}`].join(`
50
- `)}function sm(e){if(G(e.file_id,32),G(e.nonce,32),_t(e.amount,128)<=0n||!Number.isSafeInteger(e.deadline)||e.deadline<0)throw new TypeError("Invalid file funding authorization.");return["Annon: request sponsored file storage",`network: ${e.network}`,`contract: ${e.contract}`,`seller: ${Ke(e.seller)}`,`file: ${e.file_id}`,`amount: ${e.amount}`,`nonce: ${e.nonce}`,`expires: ${e.deadline}`].join(`
51
- `)}qh();var s4=["eth","base","arb","arbitrum","op","optimism","polygon","pol","bera","scroll","monad","xlayer","abs","plasma","bsc","avax","avalanche","gnosis"];function a4(e){return s4.includes(e)?"evm":e==="sol"||e==="solana"?"solana":e==="near"?"near":"other"}function P6(e){let t=a4(e);if(t==="other")throw new TypeError("unsupported origin chain or purchase window");return t}function c4(e,t,r,n){if(e.filter(i=>i.assetId===t&&i.blockchain===r).length!==1)throw new TypeError("select an exact catalog asset and blockchain");let o=P6(r);return jh(o,n),{asset:t,blockchain:r,chain:o,refundTo:n,refundType:"ORIGIN_CHAIN"}}function jh(e,t){if(typeof t!="string"||!t||/\s/.test(t))throw new TypeError("invalid refund address");if(e==="evm"){if(!pe(t)||/^0x0{40}$/i.test(t))throw new TypeError("invalid EVM refund address")}else if(e==="solana"){if(!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(t)||Ut.decode(t).length!==32)throw new TypeError("invalid Solana refund address")}else if(e==="near")be(t);else if(e!=="other")throw new TypeError("unsupported refund chain family")}function Gh(e){if(!e||typeof e.asset!="string"||!e.asset.startsWith("nep141:")||!e.asset.slice(7)||/\s/.test(e.asset))throw new TypeError("invalid origin asset");if(e.blockchain&&P6(e.blockchain)!==e.chain)throw new TypeError("origin chain family mismatch");if(e.depositMode!==void 0&&!["SIMPLE","MEMO"].includes(e.depositMode))throw new TypeError("invalid deposit mode");if(e.refundType!==void 0&&!["ORIGIN_CHAIN","INTENTS"].includes(e.refundType))throw new TypeError("invalid refund type");jh(e.chain,e.refundTo),e.refundType==="INTENTS"&&be(e.refundTo)}var nd=class extends S{constructor(r=0){super("transport","1Click transport unavailable");this.retryAfterMs=r;this.name="TransportError"}retryAfterMs},d4=["PENDING_DEPOSIT","KNOWN_DEPOSIT_TX","PROCESSING","SUCCESS","REFUNDED","FAILED","INCOMPLETE_DEPOSIT"],od=class extends S{code="quote_expired";constructor(){super("quote_expired","The 1Click quote expired. Run buy again."),this.name="OneClickQuoteExpired"}},Dl=class extends S{code="quote_refused";minimumAmountUsdc;constructor(t){super("quote_refused",t),this.name="OneClickRefused";let r=/^Amount is too low for bridge, try at least ([0-9]{1,39})[.]?$/i.exec(t);r?.[1]&&(this.minimumAmountUsdc=at(r[1]))}};function f4(e){return typeof e=="string"&&(/^Amount is too low for bridge, try at least [0-9]{1,39}[.]?$/i.test(e)||/^(No routes found|No liquidity available|Amount is too low|Amount is too high|Unsupported (origin|destination) asset)[.]?$/i.test(e))}function u4(e,t){let r=t.quote;if(!r||r.amountOut!==e.amount||r.minAmountOut!==void 0&&_t(r.minAmountOut,128)<BigInt(e.amount))throw new Error("1Click quote has wrong output");let n=t.quoteRequest;if(!n||Object.entries(e).some(([o,i])=>n[o]!==i))throw new Error("1Click quoteRequest echo mismatch");if(typeof r.timeEstimate!="number"||!Number.isFinite(r.timeEstimate)||r.timeEstimate<0||r.timeEstimate>600)throw new Error("1Click delivery estimate exceeds purchase delivery window");if(typeof r.amountIn!="string"||_t(r.amountIn,128)===0n)throw new Error("invalid quote input amount");return{request:e,amountIn:r.amountIn,amountOut:e.amount,timeEstimate:r.timeEstimate}}var Mi=class{constructor(t={}){this.options=t}options;async request(t,r,n){n?.throwIfAborted();let o;try{o=await(this.options.fetch??fetch)(`${this.options.endpoint??"https://1click.chaindefuser.com/v0"}${t}`,{credentials:"omit",method:r===void 0?"GET":"POST",...r===void 0?{}:{headers:{"content-type":"application/json"},body:JSON.stringify(r)},signal:n?AbortSignal.any([n,AbortSignal.timeout(2e4)]):AbortSignal.timeout(2e4)})}catch{throw n?.throwIfAborted(),new nd}if(o.status===429||o.status>=500){let s=us(o.headers.get("retry-after"),this.now()*1e3)??0;throw new nd(Math.max(0,Math.min(3e5,s||0)))}if(!o.ok){if(t==="/quote"&&o.status>=400&&o.status<500){let a=(await o.json().catch(()=>null))?.message;throw new Dl(f4(a)?a:"The 1Click quote was refused.")}throw new Error(`1Click HTTP ${o.status}`)}let i=await o.json();if(!i||typeof i!="object"||Array.isArray(i)&&t!=="/tokens")throw new Error("malformed 1Click response");return i}now(){return(this.options.now??(()=>Math.floor(Date.now()/1e3)))()}async tokens(t){let r=await this.request("/tokens",void 0,t);if(!Array.isArray(r))throw new Error("malformed token catalog");return r.filter(n=>!!n&&typeof n=="object"&&typeof n.assetId=="string"&&n.assetId.startsWith("nep141:")&&!!n.assetId.slice(7)&&typeof n.blockchain=="string"&&!!n.blockchain&&typeof n.symbol=="string"&&Number.isInteger(n.decimals)&&n.decimals>=0&&n.decimals<=255)}async preview(t,r,n={}){return this.quote(t,r,{...n,dry:!0})}async quote(t,r,n={}){let o=es(t);if(o.route!=="near-usdc"||o.asset!==Ki)throw new TypeError("1Click requires the NEAR USDC route");let i=(this.options.now??(()=>Math.floor(Date.now()/1e3)))(),s=Number(o.expires_at)-600;if(!Number.isSafeInteger(s)||s<=i)throw new Error("purchase expired or insufficient delivery window");Gh(r);let a=r.refundType??"ORIGIN_CHAIN";a==="INTENTS"&&be(r.refundTo);let c=n.slippageTolerance??100;if(!Number.isInteger(c)||c<0||c>1e4)throw new TypeError("invalid slippage");let d={dry:n.dry??!1,swapType:"EXACT_OUTPUT",slippageTolerance:c,originAsset:r.asset,depositType:"ORIGIN_CHAIN",...r.depositMode?{depositMode:r.depositMode}:{},destinationAsset:`nep141:${Ki}`,amount:o.price,refundTo:r.refundTo,refundType:a,recipient:o.contract,recipientType:"DESTINATION_CHAIN",deadline:new Date(s*1e3).toISOString(),customRecipientMsg:t},f=await this.request("/quote",d,n.signal),u=u4(d,f);if(d.dry)return u;let l=f.quote,p=typeof l.deadline=="string"?Date.parse(l.deadline):NaN;if(!Number.isFinite(p)||p<s*1e3)throw new Error("1Click deposit address deadline expires before the deposit cutoff");if(typeof l.depositAddress!="string"||!l.depositAddress||l.depositAddress.length>256)throw new Error("quote has no deposit address");let m=l.depositMemo;if(r.depositMode==="MEMO"&&(typeof m!="string"||!m)||m!==void 0&&(typeof m!="string"||m.length>256||Array.from(m).some(y=>y.charCodeAt(0)<32)))throw new Error("invalid deposit memo");let h={address:l.depositAddress,amount:u.amountIn,asset:r.asset,chain:r.chain,...r.blockchain?{blockchain:r.blockchain}:{},depositBefore:d.deadline,purchaseExpiresAt:new Date(Number(o.expires_at)*1e3).toISOString(),...m===void 0?{}:{memo:m}};return{request:d,response:f,deposit:{...h,qrData:JSON.stringify(h)}}}async status(t,r={}){if(!t||t.length>256)throw new TypeError("invalid deposit address");let n=await this.request(`/status?depositAddress=${encodeURIComponent(t)}${r.memo===void 0?"":`&depositMemo=${encodeURIComponent(r.memo)}`}`,void 0,r.signal);if(!d4.includes(n.status))throw new Error("unknown 1Click status");return n}async poll(t,r={}){let n=r.maxPolls??1200;if(!Number.isInteger(n)||n<1)throw new TypeError("invalid poll count");let o=r.intervalMs??3e3;if(!Number.isFinite(o)||o<0||o>3e4)throw new TypeError("invalid poll interval");let i=r.checkpoint??{address:t,...r.memo===void 0?{}:{memo:r.memo},attempts:0,errors:0};if(i.address!==t||i.memo!==r.memo||!Number.isSafeInteger(i.attempts)||i.attempts<0||!Number.isSafeInteger(i.errors)||i.errors<0||i.nextPollAt!==void 0&&(!Number.isFinite(i.nextPollAt)||i.nextPollAt<0))throw new TypeError("invalid poll checkpoint");if(r.signal?.throwIfAborted(),i.lastStatus&&["SUCCESS","REFUNDED","FAILED"].includes(i.lastStatus.status))return await r.onProgress?.(structuredClone(i)),i.lastStatus;i.nextPollAt&&i.nextPollAt>this.now()*1e3&&await(this.options.wait??gc)(Math.min(3e5,i.nextPollAt-this.now()*1e3),r.signal);for(let s=0;s<n;s++){r.signal?.throwIfAborted();let a,c=o;try{a=await this.status(t,r)}catch(d){if(!Na(d))throw d;c=Math.max(Math.min(3e4,o*2**Math.min(i.errors,8)),d instanceof nd?d.retryAfterMs:0)}if(i={...i,attempts:i.attempts+1,errors:a?0:i.errors+1,...a?{lastStatus:a}:{},nextPollAt:this.now()*1e3+c},await r.onProgress?.(structuredClone(i)),a&&["SUCCESS","REFUNDED","FAILED"].includes(a.status))return a;s+1<n&&await(this.options.wait??gc)(c,r.signal)}throw new S("settlement_pending","1Click status still pending")}};var ft=e=>`annon/purchase/${e}`;function R6(e){if(!e.attempts.length)throw new TypeError("a purchase record has at least one attempt");return{block:Math.min(...e.attempts.map(t=>t.searchFromBlock)),validBefore:e.attempts.reduce((t,r)=>BigInt(r.validBefore)>t?BigInt(r.validBefore):t,0n)}}function O6(e,t){for(let r of[...e.attempts].reverse())if(r.payload&&BigInt(r.validBefore)>BigInt(t))return r.payload;return null}var sn=e=>Array.from(crypto.getRandomValues(new Uint8Array(e)),t=>t.toString(16).padStart(2,"0")).join("");var jl="eip155:8453",U6="annon-exact";var ql="payment-identifier";var C6="builder-code",l4="bc_lq0mq0v9";var p4=e=>e===void 0?[]:Array.isArray(e)?e:[e];var m4=new TextEncoder,h4=e=>{let t="";for(let r of m4.encode(e))t+=String.fromCharCode(r);return btoa(t)};function N6(e,t,r,n,o,i){let s=e.extensions?.[ql],a=e.extensions?.[C6],c=p4(a?.info?.s),d={...a??{},info:{...a?.info??{},s:[...new Set([l4,...c])]}},f=e.extensions?.annon;$r(o,{baseUsdc:t.asset});let u={...f?.info??{},version:3,network:"near:mainnet",contract:o.contract,fileId:o.file_id,purchase:$r(o,{baseUsdc:t.asset}),purchase_id:gn(o,{baseUsdc:t.asset})};return h4(JSON.stringify({x402Version:2,...e.resource===void 0?{}:{resource:e.resource},accepted:t,payload:{signature:n,authorization:{from:r.from,to:r.to,value:r.value.toString(),validAfter:r.validAfter.toString(),validBefore:r.validBefore.toString(),nonce:r.nonce}},extensions:{...e.extensions??{},annon:{...f??{},info:u},...s&&i?{[ql]:{...s,info:{...s.info,id:i}}}:{},[C6]:d}}))}var y4=180,b4=60,Gl=e=>typeof e=="string"?e.toLowerCase():void 0,g4=e=>typeof e=="string"&&/^0x[0-9a-fA-F]{40}$/.test(e);async function F6(e,t,r,n,o){let i={fileId:n,cipherHash:o.cipherHash,seller:o.seller,...o.headerHash?{publishedHeaderHash:o.headerHash}:{}},s;try{s=await(t?eg:ni)(e,i,r)}catch(a){if(a instanceof Re)return ie("file_invalid",`the PAY2 file failed its check: ${a.code}`);throw a}return s.usable||ie("file_invalid","the PAY2 header has no key for this contract"),s}async function M6(e,t,r){let n=await ai(e,t,r);return n?(n.takenDown&&ie("taken_down",`the file was taken down (${n.takenDown})`),n.salesStoppedAt!==null&&ie("sales_stopped","the seller stopped selling this file"),n):ie("unknown_file","the file is not registered on the Annon contract")}async function z6(e){if(!/^0x[0-9a-f]{64}$/.test(e.fileId))throw new TypeError("fileId must be 0x and 32 bytes of lowercase hex");if(!g4(e.buyer))throw new TypeError("buyer must be a 0x EVM address");let t=e.buyer.toLowerCase(),r=e.paymentRequired,n=r?.resource?.url;(typeof n!="string"||!Rf(n,e.url))&&ie("bad_requirements","resource.url is not the URL that answered with this 402");let o=(Array.isArray(r?.accepts)?r.accepts:[]).filter(y=>y?.scheme===U6&&y?.network===jl),[i]=o;if(o.length!==1||!i)return ie("network_mismatch","no single Annon offer on Base");let s=i.extra??{},a=r.extensions?.annon?.info;a&&(a.contract!==e.contractId||Gl(a.fileId)!==e.fileId)&&ie("file_mismatch","the payment request is for another Annon contract or file");let c=i.maxTimeoutSeconds;(!Number.isSafeInteger(c)||c<1)&&ie("bad_requirements","maxTimeoutSeconds must be a positive integer"),(typeof i.amount!="string"||!/^\d{1,78}$/.test(i.amount))&&ie("bad_requirements","amount must be a decimal string");let d=await M6(e.nearRpc,e.contractId,e.fileId);d.moderator!==null&&!(e.moderators??[]).includes(d.moderator)&&ie("unknown_moderator",`the file's moderator ${d.moderator} is not one you trust`);let f=await ao(e.nearRpc,e.contractId);if((d.terms.network!==f.network||d.terms.near.token!==f.nearUsdc||d.terms.base&&d.terms.base.usdc!==f.usdc)&&ie("network_mismatch"),!(e.pay2 instanceof Uint8Array))throw new TypeError("pay2 must be the PAY2 header bytes");let u=await F6(e.pay2,a?.public===!0,e.contractId,e.fileId,d);d.terms.base||ie("method_mismatch","the file has no Base route");let l=d.payTo;(Gl(i.asset)!==f.usdc||s.name!=="USD Coin"||s.version!=="2")&&ie("token_mismatch","the payment request is not for USDC on Base");let p=s.assetTransferMethod;p!==void 0&&p!=="eip3009"&&ie("method_mismatch","the offer is not a plain Annon transfer");let m=s.paymentFlow;(a?.version!==3||i.extra?.nonceVersion!==2||m!=="upfront")&&ie("method_mismatch",`unsupported payment flow ${String(s.paymentFlow)}`),s.splits!==void 0&&!(Array.isArray(s.splits)&&s.splits.length===0)&&ie("method_mismatch","the offer splits the payment; Annon pays the registered pay_to only"),Gl(i.payTo)!==l&&ie("recipient_mismatch","the payment request pays an address the registration does not"),BigInt(i.amount)!==d.price&&ie("price_mismatch","the payment request asks a different price than the registration"),d.price>e.maxPrice&&ie("price_above_max","the price is above your limit");let h=await lo(e.baseRpc);return await _f(e.baseRpc,t,h.number)&&ie("smart_wallet_unsupported","the wallet is a contract or delegated (EIP-7702); pay from a plain account"),await Ef(e.baseRpc,f.usdc,t,h.number)<d.price&&ie("insufficient_balance","not enough USDC on Base"),{nearRpc:e.nearRpc,baseRpc:e.baseRpc,contractId:e.contractId,fileId:e.fileId,buyer:t,seller:d.seller,to:l,usdc:f.usdc,price:d.price,validity:Math.min(c,y4),file:d,paymentRequired:r,offer:i,header:u.header}}var w4=(e,t=e.attempts[0])=>({from:e.terms.buyer,to:e.terms.to,value:BigInt(e.terms.price),validAfter:0n,validBefore:BigInt(t.validBefore),nonce:e.terms.nonce});async function H6(e,t){if(Gl(t.wallet.address)!==e.buyer)throw new TypeError("the wallet is not the buyer the quote was made for");let r=t.purchase,n=gn(r,{baseUsdc:e.usdc}),o=$r(r,{baseUsdc:e.usdc});if(r.route!=="base-usdc"||r.contract!==e.contractId||r.file_id!==e.fileId||r.terms_hash!==e.file.termsHash||r.price!==e.price.toString()||r.asset!==e.usdc||Ze(Gt(t.buyerSecret).publicKeyBytes)!==r.buyer_key||BigInt(r.expires_at)<=BigInt(Math.floor(Date.now()/1e3)))throw new TypeError("purchase does not match the checked quote/key");let i=await lo(e.baseRpc),s=Math.floor(Date.now()/1e3);Math.abs(i.timestamp-s)>b4&&ie("transport","the Base RPC is not at the current time; its deadline would be wrong");let a=await M6(e.nearRpc,e.contractId,e.fileId);(a.termsHash!==e.file.termsHash||a.price!==e.price||a.payTo!==e.file.payTo||a.moderator!==e.file.moderator||a.cipherHash!==e.file.cipherHash)&&ie("price_mismatch","the registration changed since the quote; check it again"),await F6(e.header,!1,e.contractId,e.fileId,a);let c=await cs(e.baseRpc,"finalized"),d=Math.min(i.timestamp,s),f={schemaVersion:2,recoveryProved:!1,payment:{route:"base",amountUsdc:at(e.price),amountBaseUnits:e.price.toString(),asset:{symbol:"USDC",id:e.usdc},network:jl},id:n,purchase:r,message:o,buyerSecret:Ze(t.buyerSecret),quote:null,recovery:r.recovery,checkedHeaderHash:Ze(ur(e.header)),revision:0,terms:{network:jl,contractId:e.contractId,fileId:e.fileId,buyer:e.buyer,seller:e.seller,to:e.to,usdc:e.usdc,price:e.price.toString(),buyerKey:r.buyer_key,nonce:Qd(n),headerHash:Ze(ur(e.header)),cipherHash:e.file.cipherHash,moderator:e.file.moderator},attempts:[{attemptId:sn(16),...e.paymentRequired.extensions?.[ql]?{paymentId:`pay_${sn(16)}`}:{},preparedAt:d,searchFromBlock:Math.min(c.number,i.number),validBefore:Math.min(d+e.validity,Number(r.expires_at)).toString(),paymentRequired:e.paymentRequired}]},u=ft(n);await t.store.compareAndSet(u,null,f)||ie("purchase_open","this wallet has an open purchase of this file: follow its nextStep");let l=f.attempts[0],p=w4(f),m=await t.wallet.signTypedData(sw(e.usdc,p));(typeof m!="string"||wf(gf(e.usdc,p),m)!==e.buyer)&&ie("bad_signature","the wallet did not return a plain signature from the buyer");let h=N6(e.paymentRequired,e.offer,p,m,r,l.paymentId),y={...f,revision:1,attempts:[{...l,payload:h}]};if(!await t.store.compareAndSet(u,f,y)){let b=new re("store_conflict","the purchase changed while the wallet signed");throw b.purchase=f,b}try{await dw(e.baseRpc,e.usdc,p,m)}catch(b){throw b instanceof re&&(b.purchase=y),b}return{header:h,purchase:y}}var $6=(e,t)=>lw(e,{usdc:t.terms.usdc,to:t.terms.to,from:t.terms.buyer,nonce:t.terms.nonce,price:BigInt(t.terms.price),...R6(t)});async function L6(e,t){if(await so(t.nearRpc,e.purchase.contract,e.id))return{step:"claim_key",args:{purchase_id:e.id,grant:0}};if(e.purchase.route==="near-usdc")return{step:"wait"};let r=await $6(t.baseRpc,e);if(r.state==="pending"){let n=O6(e,Math.floor(Date.now()/1e3));return n?{step:"resend",header:n}:{step:"wait"}}if(r.state!=="paid"){if(e.paymentState!==r.state&&!await t.store.compareAndSet(ft(e.id),e,{...e,revision:e.revision+1,paymentState:r.state}))throw new re("store_conflict");return{step:"buy"}}return{step:"unlock",args:{purchase:e.message,logs:r.logs,header:await uw(t.baseRpc,`0x${r.logs[0].block_hash}`)}}}var x4=65536,q6=30,j6=new WeakMap,G6=e=>JSON.stringify([e.deployment,e.file.terms,e.file.termsHash,e.file.salesStoppedAt,e.file.takenDown,e.relayer,e.baseRpc]),id=e=>(e.now??(()=>Math.floor(Date.now()/1e3)))(),Vl=(e,t)=>Number.isSafeInteger(e)&&e>=0&&Math.abs(t-e)<=q6,Qe=(e,t)=>Object.assign(new S(e),{code:e,...t===void 0?{}:{retryAfterSeconds:t}}),D6=e=>typeof e=="string"&&/^(0|[1-9][0-9]*)$/.test(e)&&e.length<=39&&BigInt(e)<2n**128n;function v4(e){let t=new URL(e);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw Qe("relayer_unavailable");return t.origin}async function S4(e){if(!e.body)throw Qe("relayer_unavailable");let t=e.body.getReader(),r=[],n=0;try{for(;;){let a=await t.read();if(a.done)break;if(n+=a.value.length,n>x4)throw Qe("relayer_unavailable");r.push(a.value)}}finally{await t.cancel().catch(()=>{})}let o=new Uint8Array(n),i=0;for(let a of r)o.set(a,i),i+=a.length;let s=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(o));if(!s||typeof s!="object"||Array.isArray(s))throw Qe("relayer_unavailable");return s}function Vh(e,t){if(!e)return!1;let r=j6.get(e),n=id(t);return!!r&&r.binding===G6(t)&&r.value===JSON.stringify(e)&&Vl(e.checkedAt,n)&&e.splitCheckedAt<=n&&Vl(e.splitCheckedAt,n)}async function Kh(e,t){if(!t)throw Qe("relayer_unavailable");let r=e.terms;if(!r.base||e.takenDown!==null||e.salesStoppedAt!==null||r.near.recipients.some(n=>n.identity.kind!=="evm"))throw Qe("not_sponsored");try{await gw(t,r.base.pay_to,{recipients:r.near.recipients.map(n=>n.identity.id),allocations:r.near.recipients.map(n=>BigInt(n.bps)),totalAllocation:10000n,distributionIncentive:0})}catch(n){throw n instanceof re&&n.code==="network_mismatch"?n:Qe(n instanceof re&&!Na(n)?"not_sponsored":"relayer_unavailable")}}async function Wh(e){if(!e.relayer)throw Qe("transport_required");let t;try{let r=v4(e.relayer),n=e.deployment,o=e.file.terms;if(o.near.recipients.some(u=>u.identity.kind!=="evm")||o.network!==n.network||o.contract!==n.contractId||o.near.token!==n.nearUsdc||o.base?.usdc!==n.baseUsdc||tt(o,{nearUsdc:n.nearUsdc,baseUsdc:n.baseUsdc})!==e.file.termsHash)throw Qe("not_sponsored");let i=e.fetch??globalThis.fetch,s=async(u,l)=>{let p=await i(new URL(u,r),{redirect:"error",credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(2e4),...l?{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(l)}:{}}),m=us(p.headers.get("Retry-After"),id(e)*1e3);if(m!==void 0&&(t=Math.max(1,Math.ceil(m/1e3))),!p.ok)throw await p.body?.cancel(),Qe("relayer_unavailable",t);return S4(p)},a=await s("/v1/capabilities");if(a.network!==n.network||a.contract!==n.contractId||a.nearUsdc!==n.nearUsdc||a.baseUsdc!==n.baseUsdc||!Array.isArray(a.methods)||!a.methods.includes("unlock")||typeof a.disabled!="boolean"||typeof a.baseSponsorship!="boolean"||typeof a.acceptingNewBasePayments!="boolean")throw Qe("relayer_unavailable");if(a.disabled||!a.baseSponsorship||!a.acceptingNewBasePayments)throw Qe("relayer_unavailable",t??5);let c=await s("/v1/base-eligibility",{fileId:o.file_id,termsHash:e.file.termsHash});if(c.network!==n.network||c.contract!==n.contractId||c.fileId!==o.file_id||c.termsHash!==e.file.termsHash||typeof c.eligible!="boolean")throw Qe("relayer_unavailable");if(!c.eligible)throw Qe("not_sponsored");if(!["listed","pool","legacy","external"].includes(String(c.tier))||typeof c.policyVersion!="string"||!c.policyVersion||!D6(c.minPrice)||!c.fee||typeof c.fee!="object"||!Vl(c.checkedAt,id(e))||!Number.isSafeInteger(c.decidedAt)||c.decidedAt<0||c.decidedAt>c.checkedAt)throw Qe("relayer_unavailable");let d=c.fee;if(!D6(d.fixed)||!Number.isSafeInteger(d.bps)||d.bps<0||d.bps>1e4||!Object.hasOwn(d,"treasuryNear")||!Object.hasOwn(d,"treasuryEvm"))throw Qe("relayer_unavailable");try{if(!o.base||BigInt(o.base.price)<BigInt(c.minPrice))throw new Error;po(o,d)}catch{throw Qe("not_sponsored")}await Kh(e.file,e.baseRpc);let f={network:n.network,contract:n.contractId,fileId:o.file_id,termsHash:e.file.termsHash,eligible:!0,tier:c.tier,policyVersion:c.policyVersion,minPrice:c.minPrice,fee:{fixed:d.fixed,bps:d.bps,treasuryNear:d.treasuryNear===null?null:ne(d.treasuryNear),treasuryEvm:d.treasuryEvm===null?null:ne(d.treasuryEvm)},decidedAt:c.decidedAt,checkedAt:c.checkedAt,splitCheckedAt:id(e)};if(!Vl(f.checkedAt,id(e)))throw Qe("relayer_unavailable");return j6.set(f,{binding:G6(e),value:JSON.stringify(f)}),f}catch(r){throw r&&typeof r=="object"&&"code"in r&&["not_sponsored","relayer_unavailable","network_mismatch"].includes(String(r.code))?r:Qe("relayer_unavailable",t)}}le();le();var np=class extends L{constructor(t){super(`Call bundle failed with status: ${t.statusCode}`,{name:"BundleFailedError"}),Object.defineProperty(this,"result",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.result=t}};vt();ep();oy();Il();pl();Ar();Eo();eu();Pt();rd();Ye();le();ul();vi();or();Pt();xe();ed();dd();var ay="0x5792579257925792579257925792579257925792579257925792579257925792",cy=V(0,{size:32});async function op(e,t){let{account:r=e.account,chain:n=e.chain,experimental_fallback:o,experimental_fallbackDelay:i=32,forceAtomic:s=!1,id:a,version:c="2.0.0"}=t,d=r?ce(r):null,f=t.capabilities;e.dataSuffix&&!t.capabilities?.dataSuffix&&(typeof e.dataSuffix=="string"?f={...t.capabilities,dataSuffix:{value:e.dataSuffix,optional:!0}}:f={...t.capabilities,dataSuffix:{value:e.dataSuffix.value,...e.dataSuffix.required?{}:{optional:!0}}});let u=t.calls.map(l=>{let p=l,m=p.abi?Yt({abi:p.abi,functionName:p.functionName,args:p.args}):p.data;return{data:p.dataSuffix&&m?_r([m,p.dataSuffix]):m,to:p.to,value:p.value?V(p.value):void 0}});try{let l=await e.request({method:"wallet_sendCalls",params:[{atomicRequired:s,calls:u,capabilities:f,chainId:V(n.id),from:d?.address,id:a,version:c}]},{retryCount:0});return typeof l=="string"?{id:l}:l}catch(l){let p=l;if(o&&(p.name==="MethodNotFoundRpcError"||p.name==="MethodNotSupportedRpcError"||p.name==="UnknownRpcError"||p.details.toLowerCase()==="this request method is not supported"||p.details.toLowerCase().includes("does not exist / is not available")||p.details.toLowerCase().includes("missing or invalid. request()")||p.details.toLowerCase().includes("did not match any variant of untagged enum")||p.details.toLowerCase().includes("account upgraded to unsupported contract")||p.details.toLowerCase().includes("eip-7702 not supported")||p.details.toLowerCase().includes("unsupported wc_ method")||p.details.toLowerCase().includes("feature toggled misconfigured")||p.details.toLowerCase().includes("jsonrpcengine: response has no error or result for request"))){if(f&&Object.values(f).some(b=>!b.optional)){let b="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new Ro(new L(b,{details:b}))}if(s&&u.length>1){let y="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new Oo(new L(y,{details:y}))}let m=[];for(let y of u){try{let b=await Ho(e,{account:d,chain:n,data:y.data,to:y.to,value:y.value?De(y.value):void 0});m.push({status:"fulfilled",value:b})}catch(b){m.push({reason:b,status:"rejected"})}i>0&&await new Promise(b=>setTimeout(b,i))}if(m.every(y=>y.status==="rejected"))throw m[0].reason;let h=m.map(y=>y.status==="fulfilled"?y.value:cy);return{id:_r([...h,V(n.id,{size:32}),ay])}}throw No(l,{...t,account:d,chain:t.chain})}}async function ip(e,t){async function r(f){if(f.endsWith(ay.slice(2))){let l=Kr(Su(f,-64,-32)),p=Su(f,0,-64).slice(2).match(/.{1,64}/g),m=await Promise.all(p.map(y=>cy.slice(2)!==y?e.request({method:"eth_getTransactionReceipt",params:[`0x${y}`]},{dedupe:!0}):void 0)),h=m.some(y=>y===null)?100:m.every(y=>y?.status==="0x1")?200:m.every(y=>y?.status==="0x0")?500:600;return{atomic:!1,chainId:Xe(l),receipts:m.filter(Boolean),status:h,version:"2.0.0"}}return e.request({method:"wallet_getCallsStatus",params:[f]})}let{atomic:n=!1,chainId:o,receipts:i,version:s="2.0.0",...a}=await r(t.id),[c,d]=(()=>{let f=a.status;return f>=100&&f<200?["pending",f]:f>=200&&f<300?["success",f]:f>=300&&f<700?["failure",f]:f==="CONFIRMED"?["success",200]:f==="PENDING"?["pending",100]:[void 0,f]})();return{...a,atomic:n,chainId:o?Xe(o):void 0,receipts:i?.map(f=>({...f,blockNumber:De(f.blockNumber),gasUsed:De(f.gasUsed),status:$h[f.status]}))??[],statusCode:d,status:c,version:s}}var t5=new WeakMap,I4=0;function r5(e){let t=t5.get(e);return t===void 0&&(t=++I4,t5.set(e,t)),t}async function sp(e,t){let{id:r,pollingInterval:n=e.pollingInterval,status:o=({statusCode:h})=>h===200||h>=300,retryCount:i=4,retryDelay:s=({count:h})=>~~(1<<h)*200,timeout:a=6e4,throwOnFailure:c=!1}=t,d=qe(["waitForCallsStatus",e.uid,r,{pollingInterval:n,retryCount:i,retryDelay:typeof t.retryDelay=="function"?["function",r5(t.retryDelay)]:t.retryDelay,status:t.status?r5(t.status):void 0,throwOnFailure:c}]),{promise:f,resolve:u,reject:l}=Sa(),p,m=zi(d,{resolve:u,reject:l},h=>{let y=tp(async()=>{let b=x=>{clearTimeout(p),y(),x(),m()};try{let x=await Ui(async()=>{let g=await oe(e,ip,"getCallsStatus")({id:r});if(c&&g.status==="failure")throw new np(g);return g},{retryCount:i,delay:s});if(!o(x))return;b(()=>h.resolve(x))}catch(x){b(()=>h.reject(x))}},{interval:n,emitOnBegin:!0});return y});return p=a?setTimeout(()=>{m(),clearTimeout(p),l(new dy({id:r}))},a):void 0,await f.finally(()=>m())}var dy=class extends L{constructor({id:t}){super(`Timed out while waiting for call bundle with id "${t}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}};Ye();var ap=256,cp;function dp(e=11){if(!cp||ap+e>256*2){cp="",ap=0;for(let t=0;t<256;t++)cp+=(256+Math.random()*256|0).toString(16).substring(1)}return cp.substring(ap,ap+++e)}function i5(e){let{batch:t,chain:r,ccipRead:n,dataSuffix:o,key:i="base",name:s="Base Client",tokens:a,type:c="base"}=e,d=e.experimental_blockTag??(typeof r?.experimental_preconfirmationTime=="number"?"pending":void 0),f=r?.blockTime??12e3,u=Math.min(Math.max(Math.floor(f/2),500),4e3),l=e.pollingInterval??u,p=e.cacheTime??l,m=e.account?ce(e.account):void 0,{config:h,request:y,value:b}=e.transport({account:m,chain:r,pollingInterval:l}),x={...h,...b},g={account:m,batch:t,cacheTime:p,ccipRead:n,chain:r,dataSuffix:o,key:i,name:s,pollingInterval:l,request:y,tokens:a,transport:x,type:c,uid:dp(),...d?{experimental_blockTag:d}:{}};return s5(g)}var n5=new WeakSet,k4=0;function s5(e){function t(n,o){return i=>{let s=i(n);for(let f in e)f!=="scope"&&delete s[f];let a={...n,...s};for(let f in s){let u=n[f],l=s[f];o5(u)&&o5(l)&&(a[f]={...u,...l})}let c=[...o,i],{scope:d}=a;return Object.assign(a,{extend:t(a,c),scope:typeof d=="function"&&n5.has(d)?r(c):d})}}function r(n){let o=new WeakMap,i=(s={})=>{let a=s.signal&&o.get(s.signal);if(a)return a;let c=`scope.${k4++}`,d=new AbortController,{signal:f}=s;f?.aborted?d.abort(f.reason):f?.addEventListener("abort",()=>d.abort(f.reason),{once:!0});let u=(p,m)=>e.request(p,{...m,signal:m?.signal??d.signal,uid:m?.uid??c}),l=n.reduce((p,m)=>p.extend(m),s5({...e,request:u,uid:c}));return f&&o.set(f,l),l};return n5.add(i),i}return Object.assign(e,{extend:t(e,[]),scope:r([])})}function o5(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ud(e,t){let r=(n={})=>t(e,n);for(let n of["call","calls","callWithPeriod","estimateGas","prepare","prepareRecipient","predict","simulate"])if(Object.hasOwn(t,n)){let o=t[n];r[n]=(i={})=>o.length===1?o(i):o(e,i)}for(let n of["extractEvent","extractEvents"])Object.hasOwn(t,n)&&(r[n]=t[n]);return r}Jc();qm();ty();ry();fd();ld();async function zn(e,t){return zn.inner(Pr,e,t)}(function(e){async function t(s,a,c){return await s(a,{...c,...e.call(a,c)})}e.inner=t;function r(s,a){return pp(U4(s,a))}e.call=r;async function n(s,a){return Xl(s,{...Ba(a),...e.call(s,a)})}e.estimateGas=n;async function o(s,a){return Jl(s,{...Ba(a),...e.call(s,a)})}e.simulate=o;function i(s){let[a]=Ru({abi:Ni,logs:s,eventName:"Approval",strict:!0});if(!a)throw new Error("`Approval` event not found.");return a}e.extractEvent=i})(zn||(zn={}));function U4(e,t){let{amount:r,spender:n,token:o}=t,{address:i,decimals:s}=$o(e,{token:o});return{abi:Ni,address:i,args:[n,up(r,s)],functionName:"approve"}}Dh();yp();ld();async function my(e,t){let{amount:r,token:n,throwOnReceiptRevert:o=!0}=t,{decimals:i}=$o(e,{token:n}),s=lp(r,i),a=await zn.inner(Pa,e,{...t,throwOnReceiptRevert:o}),{args:c}=zn.extractEvent(a.logs);return{...c,...s===void 0?{}:{decimals:s,formatted:Ll(c.value,s)},receipt:a}}Jc();qm();ty();ry();fd();ld();async function Hn(e,t){return Hn.inner(Pr,e,t)}(function(e){async function t(s,a,c){return await s(a,{...c,...e.call(a,c)})}e.inner=t;function r(s,a){return pp(N4(s,a))}e.call=r;async function n(s,a){return Xl(s,{...Ba(a),...e.call(s,a)})}e.estimateGas=n;async function o(s,a){return Jl(s,{...Ba(a),...e.call(s,a)})}e.simulate=o;function i(s){let[a]=Ru({abi:Ni,logs:s,eventName:"Transfer",strict:!0});if(!a)throw new Error("`Transfer` event not found.");return a}e.extractEvent=i})(Hn||(Hn={}));function N4(e,t){let{amount:r,from:n,to:o,token:i}=t,{address:s,decimals:a}=$o(e,{token:i}),c=up(r,a);return n?{abi:Ni,address:s,args:[n,o,c],functionName:"transferFrom"}:{abi:Ni,address:s,args:[o,c],functionName:"transfer"}}Dh();yp();ld();async function hy(e,t){let{amount:r,token:n,throwOnReceiptRevert:o=!0}=t,{decimals:i}=$o(e,{token:n}),s=lp(r,i),a=await Hn.inner(Pa,e,{...t,throwOnReceiptRevert:o}),{args:c}=Hn.extractEvent(a.logs);return{...c,...s===void 0?{}:{decimals:s,formatted:Ll(c.value,s)},receipt:a}}Jh();Mo();xe();async function m5(e,{chain:t}){let{id:r,name:n,nativeCurrency:o,rpcUrls:i,blockExplorers:s}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:V(r),chainName:n,nativeCurrency:o,rpcUrls:i.default.http,blockExplorerUrls:s?Object.values(s).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}Mm();dd();function h5(e,t){let{abi:r,args:n,bytecode:o,...i}=t,s=Nc({abi:r,args:n,bytecode:o});return Ho(e,{...i,...i.authorizationList?{to:null}:{},data:s})}hs();async function y5(e){return e.account?.type==="local"?[e.account.address]:(await e.request({method:"eth_accounts"},{dedupe:!0})).map(r=>An(r))}Ye();xe();async function b5(e,t={}){let{account:r=e.account,chainId:n}=t,o=r?ce(r):void 0,i=n?[o?.address,[V(n)]]:[o?.address],s=await e.request({method:"wallet_getCapabilities",params:i}),a={};for(let[c,d]of Object.entries(s)){a[Number(c)]={};for(let[f,u]of Object.entries(d))f==="addSubAccount"&&(f="unstable_addSubAccount"),a[Number(c)][f]=u}return typeof n=="number"?a[n]:a}async function g5(e){return await e.request({method:"wallet_getPermissions"},{dedupe:!0})}Ye();Mn();Si();vt();Mo();Lh();async function bp(e,t){let{account:r=e.account,chainId:n,nonce:o}=t;if(!r)throw new it({docsPath:"/docs/eip7702/prepareAuthorization"});let i=ce(r),s=(()=>{if(t.executor)return t.executor==="self"?t.executor:ce(t.executor)})(),a={address:t.contractAddress??t.address,chainId:n,nonce:o};return typeof a.chainId>"u"&&(a.chainId=e.chain?.id??await oe(e,qt,"getChainId")({})),typeof a.nonce>"u"&&(a.nonce=await oe(e,Fl,"getTransactionCount")({address:i.address,blockTag:"pending"}),(s==="self"||s?.address&&Ht(s.address,i.address))&&(a.nonce+=1)),a}cd();hs();async function w5(e){return(await e.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>N1(r))}async function x5(e,t){return e.request({method:"wallet_requestPermissions",params:[t]},{retryCount:0})}vt();async function v5(e,t){let{chain:r=e.chain}=t,n=t.timeout??Math.max((r?.blockTime??0)*3,5e3),o=await oe(e,op,"sendCalls")(t);return await oe(e,sp,"waitForCallsStatus")({...t,id:o.id,timeout:n})}iy();uy();dd();py();async function S5(e,t){let{id:r}=t;await e.request({method:"wallet_showCallsStatus",params:[r]})}Ye();Mn();async function E5(e,t){let{account:r=e.account}=t;if(!r)throw new it({docsPath:"/docs/eip7702/signAuthorization"});let n=ce(r);if(!n.signAuthorization)throw new ar({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});let o=await bp(e,t);return n.signAuthorization(o)}Ye();Mn();xe();async function _5(e,{account:t=e.account,message:r}){if(!t)throw new it({docsPath:"/docs/actions/wallet/signMessage"});let n=ce(t);if(n.signMessage)return n.signMessage({message:r});let o=typeof r=="string"?_c(r):r.raw instanceof Uint8Array?ht(r.raw):r.raw;return e.request({method:"personal_sign",params:[o,n.address]},{retryCount:0})}Ye();Mn();Cl();xe();Fi();vt();Uo();Mo();async function A5(e,t){let{account:r=e.account,chain:n=e.chain,...o}=t;if(!r)throw new it({docsPath:"/docs/actions/wallet/signTransaction"});let i=ce(r);Dt({account:i,...t});let s=await oe(e,qt,"getChainId")({});n!==null&&Ea({currentChainId:s,chain:n});let c=(n?.formatters||e.chain?.formatters)?.transactionRequest?.format||sr;return i.signTransaction?i.signTransaction({...o,account:i,chainId:s},{serializer:e.chain?.serializers?.transaction}):await e.request({method:"eth_signTransaction",params:[{...c({...o,account:i},"signTransaction"),chainId:V(s),from:i.address}]},{retryCount:0})}Ye();Mn();I6();async function T5(e,t){let{account:r=e.account,domain:n,message:o,primaryType:i}=t;if(!r)throw new it({docsPath:"/docs/actions/wallet/signTypedData"});let s=ce(r),a={EIP712Domain:T6({domain:n}),...t.types};if(A6({domain:n,message:o,primaryType:i,types:a}),s.signTypedData)return s.signTypedData({domain:n,message:o,primaryType:i,types:a});let c=_6({domain:n,message:o,primaryType:i,types:a});return e.request({method:"eth_signTypedData_v4",params:[s.address,c]},{retryCount:0})}xe();async function I5(e,{id:t}){await e.request({method:"wallet_switchEthereumChain",params:[{chainId:V(t)}]},{retryCount:0})}async function k5(e,t){return await e.request({method:"wallet_watchAsset",params:t},{retryCount:0})}fd();yp();function B5(e){return{addChain:t=>m5(e,t),deployContract:t=>h5(e,t),fillTransaction:t=>Zl(e,t),getAddresses:()=>y5(e),getCallsStatus:t=>ip(e,t),getCapabilities:t=>b5(e,t),getChainId:()=>qt(e),getPermissions:()=>g5(e),prepareAuthorization:t=>bp(e,t),prepareTransactionRequest:t=>zo(e,t),requestAddresses:()=>w5(e),requestPermissions:t=>x5(e,t),sendCalls:t=>op(e,t),sendCallsSync:t=>v5(e,t),sendRawTransaction:t=>rp(e,t),sendRawTransactionSync:t=>mp(e,t),sendTransaction:t=>Ho(e,t),sendTransactionSync:t=>hp(e,t),showCallsStatus:t=>S5(e,t),signAuthorization:t=>E5(e,t),signMessage:t=>_5(e,t),signTransaction:t=>A5(e,t),signTypedData:t=>T5(e,t),switchChain:t=>I5(e,t),waitForCallsStatus:t=>sp(e,t),watchAsset:t=>k5(e,t),writeContract:t=>Pr(e,t),writeContractSync:t=>Pa(e,t),token:{approve:ud(e,zn),approveSync:ud(e,my),transfer:ud(e,Hn),transferSync:ud(e,hy)}}}function yy(e){let{key:t="wallet",name:r="Wallet Client",transport:n}=e;return i5({...e,key:t,name:r,transport:n,type:"walletClient"}).extend(B5)}O2();function P5({key:e,methods:t,name:r,request:n,retryCount:o=3,retryDelay:i=150,timeout:s,type:a},c){let d=dp();return{config:{key:e,methods:t,name:r,request:n,retryCount:o,retryDelay:i,timeout:s,type:a},request:R2(n,{methods:t,retryCount:o,retryDelay:i,uid:d}),value:c}}function by(e,t={}){let{key:r="custom",methods:n,name:o="Custom Provider",retryDelay:i}=t;return({retryCount:s})=>P5({key:r,methods:n,name:o,request:e.request.bind(e),retryCount:t.retryCount??s,retryDelay:i,type:"custom"})}var R5={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}};Pt();Hh();Aa();rd();var O5={block:v6({format(e){return{transactions:e.transactions?.map(r=>{if(typeof r=="string")return r;let n=Fn(r);return n.typeHex==="0x7e"&&(n.isSystemTx=r.isSystemTx,n.mint=r.mint?De(r.mint):void 0,n.sourceHash=r.sourceHash,n.type="deposit"),n}),stateRoot:e.stateRoot}}}),transaction:x6({format(e){let t={};return e.type==="0x7e"&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?De(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}}),transactionReceipt:S6({format(e){return{...e.depositNonce?{depositNonce:De(e.depositNonce)}:{},...e.depositReceiptVersion?{depositReceiptVersion:Xe(e.depositReceiptVersion)}:{},l1GasPrice:e.l1GasPrice?De(e.l1GasPrice):null,l1GasUsed:e.l1GasUsed?De(e.l1GasUsed):null,l1Fee:e.l1Fee?De(e.l1Fee):null,l1FeeScalar:e.l1FeeScalar?Number(e.l1FeeScalar):null}}})};Vr();Zt();or();xe();Ou();_h();function F4(e,t){return z4(e)?M4(e):A2(e,t)}var C5={transaction:F4};function M4(e){H4(e);let{sourceHash:t,data:r,from:n,gas:o,isSystemTx:i,mint:s,to:a,value:c}=e,d=[t,n,a??"0x",s?ht(s):"0x",c?ht(c):"0x",o?ht(o):"0x",i?"0x1":"0x",r??"0x"];return Le(["0x7e",Tr(d)])}function z4(e){return e.type==="deposit"||typeof e.sourceHash<"u"}function H4(e){let{from:t,to:r}=e;if(t&&!pe(t))throw new Ce({address:t});if(r&&!pe(r))throw new Ce({address:r})}var gy={blockTime:2e3,contracts:R5,formatters:O5,serializers:C5};y6();var pd=1,gp=Fh({...gy,id:8453,name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://basescan.org",apiUrl:"https://api.basescan.org/api"}},contracts:{...gy.contracts,disputeGameFactory:{[pd]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[pd]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[pd]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[pd]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:pd}),$4=Fh({...gp,experimental_preconfirmationTime:200,rpcUrls:{default:{http:["https://mainnet-preconf.base.org"]}}});function U5(e,t){let r="provider"in e?e.provider:e,n=ne({kind:"evm",id:t}),o=yy({chain:gp,transport:by(r)}),i=async()=>{let s=await r.request({method:"eth_accounts"});if(!Array.isArray(s)||!s.some(a=>typeof a=="string"&&a.toLowerCase()===n.id))throw new S("wrong_identity","wallet does not control the selected identity")};return{identity:n,address:n.id,async authorize(s){await i();let c={kind:"evm",sig:await o.signMessage({account:n.id,message:s})};if(!lt(n,s,c))throw new S("invalid_signature","wallet signature does not match identity");return c},async signTypedData(s){return await i(),o.signTypedData({...s,account:n.id})}}}function L4(e,t,r,n){return{identity:ne({kind:"near",id:e}),...n?{proveControl:n}:{},async authorize(i){await t()},async call(i){return await t(),r(i)},async transferPurchase(i,s){let a=es(i,s);if(a.route!=="near-usdc")throw new TypeError("not a NEAR USDC purchase");if(BigInt(a.expires_at)<=BigInt(Math.floor(Date.now()/1e3)))throw new S("payment_expired","purchase expired");return await t(),r({receiverId:a.asset,method:"ft_transfer_call",args:{receiver_id:a.contract,amount:a.price,msg:i},gas:150000000000000n,deposit:1n})}}}function N5(e,t,r){return L4(t,async()=>{if(!(await e.getAccounts()).some(n=>n.accountId===t))throw new S("wrong_identity","wallet does not control the NEAR account")},n=>e.signAndSendTransaction({signerId:t,receiverId:n.receiverId,actions:[{type:"FunctionCall",params:{methodName:n.method,args:n.args,gas:String(n.gas??300000000000000n),deposit:String(n.deposit??0n)}}]}),r??((n,o)=>{if(!e.signMessage)throw new S("missing_method","NEAR recovery requires NEP-413 signMessage");return rf(t,n,o,i=>e.signMessage?.(i)??Promise.resolve(void 0))}))}var Hi=class extends S{code="funding_refused";constructor(){super("funding_refused","File funding was refused."),this.name="FileFundingRefused"}};async function wy(e,t,r,n,o=!1){if(n<=0n||n>=2n**128n||!/^0x[0-9a-f]{64}$/.test(r))throw new RangeError("invalid file funding");let i={receiverId:be(t),method:"fund_file_storage",args:{file_id:r,amount:n.toString()},deposit:o?0n:n,gas:30000000000000n},s=c=>{if(!c||typeof c!="object"||!("transaction"in c))return!1;try{let d=c.transaction;return ci(c,t,{txHash:d.hash,signer:d.signer_id,method:i.method,args:i.args}).state==="refused"}catch{return!1}},a;try{a=await e.call(i)}catch(c){throw c&&typeof c=="object"&&"transactionResult"in c&&s(c.transactionResult)?new Hi:c}if(s(a))throw new Hi;return a}var Lo=e=>{if(e.identity.kind!=="near"||!("call"in e)||typeof e.call!="function")throw new S("near_wallet_required","a NEAR transaction wallet is required");return e},F5=e=>({nearUsdc:e.near.token,...e.base?{baseUsdc:e.base.usdc}:{}}),wp=(e,t)=>({fileId:e,cipherHash:t.cipherHash,seller:t.seller,...t.headerHash?{publishedHeaderHash:t.headerHash}:{}}),Do=class extends S{constructor(r,n){let o=n?.cause,i=o instanceof S||o instanceof br?o.code:"sell_incomplete";super(i,o instanceof Error?o.message:"Sell incomplete; resume with fileId.",n);this.fileId=r;this.name="SellError";let s=Ko(o);s.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=s.retryAfterSeconds),o instanceof S&&"txHash"in o&&typeof o.txHash=="string"&&(this.txHash=o.txHash)}fileId;txHash;retryAfterSeconds},$i=class{constructor(t){this.o=t;be(t.contractId),Gn(t.network),this.hosted=new Pf(t,{config:()=>ao(t.nearRpc,t.contractId),file:r=>ai(t.nearRpc,t.contractId,r),call:(r,n,o)=>this.call(r,n,o),answer:(r,n,o)=>this.answer(r,n,o),reopen:(r,n)=>this.reopenSeller({fileId:r,seller:n})}),this.store=this.withBackup(ss(t.rawStore,t.backupSecret),r=>pf(r,t.backupSecret)),this.sellerKeys=this.withBackup(Qg(t.rawStore,t.backupSecret),r=>Z0(r,t.backupSecret)),this.sells=this.withBackup(hf(t.rawStore,t.backupSecret),r=>wn(r,t.backupSecret)),this.recoveries=this.withBackup(pc(t.rawStore,t.backupSecret),r=>is(r,t.backupSecret))}o;store;hosted;sellerKeys;sells;recoveries;selfUnlockWallets=new Map;unlocked=new Map;withBackup(t,r){return{load:n=>t.load(n),compareAndSet:async(n,o,i)=>{let s=await t.compareAndSet(n,o,i);return s&&i&&await this.o.writeBackup(i.id,await r(i)),s}}}now(){return(this.o.now??(()=>Math.floor(Date.now()/1e3)))()}async auth(t,r){let n=ne(t.identity),o=await t.authorize(r);if(!lt(n,r,o,n.kind==="near"?n.id:void 0))throw new S("invalid_signature","wallet did not authorize the exact text");return o}async call(t,r,n){let o=n?.identity.kind==="near"?Lo(n):void 0,i=this.o.send?await this.o.send(t,r,o):o?await o.call({receiverId:this.o.contractId,method:t,args:r}):(()=>{throw new S("transport_required","configure a transaction transport for relayed calls")})();if(i&&typeof i=="object"&&"transaction"in i){let s=i.transaction,a=ci(i,this.o.contractId,{txHash:s.hash,signer:s.signer_id,method:t,args:t==="fund_file_storage"?{file_id:r.args.file_id,amount:r.args.amount}:t==="register"?Object.fromEntries(Object.entries(r).filter(([c])=>c!=="baseSplit"&&c!=="hostingReservation")):r});if(a.state==="released")return a.answer;if(a.state==="done")return a.value;throw Ug("reason"in a?a.reason:"")?new re("storage_required"):new S(a.state==="pending"?"settlement_pending":"refused")}return i}async fund(t,r,n,o={}){if(G(t,32),r<=0n||r>=2n**128n)throw new re("bad_requirements");let i=await ai(this.o.nearRpc,this.o.contractId,t);if(!i)throw new re("unknown_file");if(i.terms.network!==this.o.network||i.terms.contract!==this.o.contractId)throw new re("network_mismatch");if(Q(ne(n.identity))!==Q(i.seller))throw new re("wrong_identity");if(i.takenDown!==null)throw new re("taken_down");if(i.salesStoppedAt!==null)throw new re("sales_stopped");if(n.identity.kind==="near")return wy(Lo(n),this.o.contractId,t,r);let s=o.deadline??this.now()+600;if(!Number.isSafeInteger(s)||s<=this.now()||s>this.now()+600)throw new re("bad_requirements");let a={file_id:t,amount:String(r),nonce:o.nonce??`0x${sn(32)}`,deadline:s},c=sm({...a,network:this.o.network,contract:this.o.contractId,seller:i.seller}),d=await this.auth(n,c);return this.call("fund_file_storage",{args:a,auth:d},n)}async answer(t,r,n){let o=t&&typeof t=="object"&&"answer"in t?t.answer:t,i=await ao(this.o.nearRpc,this.o.contractId),s=await Lr(this.o.nearRpc,i.mpc,"public_key",{domain_id:i.ckdDomain});if(typeof s!="string"||!s.startsWith("bls12381g2:"))throw new S("ckd_invalid","MPC domain has no CKD key");if(this.o.mpcKey&&this.o.mpcKey!==s)throw new S("ckd_invalid","configured MPC key differs from the contract MPC domain");return Kg(o,{secret:r,appId:Vg(this.o.contractId,G(n,32)),mpcKey:s})}async file(t,r=!1){let n=await ai(this.o.nearRpc,this.o.contractId,t);if(!n)throw new re("unknown_file");if(n.takenDown)throw new re("taken_down");if(r&&n.salesStoppedAt!==null)throw new re("sales_stopped");let o=await ao(this.o.nearRpc,this.o.contractId);if(n.terms.network!==this.o.network||o.network!==this.o.network||n.terms.near.token!==o.nearUsdc||n.terms.base&&n.terms.base.usdc!==o.usdc)throw new re("network_mismatch");return n}async startShare(t){let r=await this.hosted.quote(t);await t.onSplit?.(structuredClone(r.terms.near),r.fee??void 0,r.fee?ds(t.price,r.fee,this.o.maxProtocolFee):!1);try{let n=await this.hosted.begin(r.quoteId);if(!t.confirmBackup)throw new S("backup_secret_required");return await t.confirmBackup({fileId:r.fileId,text:await this.hosted.backup(r.fileId)}),await this.hosted.confirmBackup(n.terms.file_id),n}catch(n){throw n instanceof Do?n:new Do(r.fileId,{cause:n})}}async share(t){let r=await this.startShare(t);return this.resumeShare({...t,fileId:r.terms.file_id})}async resumeShare(t){try{for(Bf(t.data);;){let r=await this.hosted.load(t.fileId);if(r.hosting?.result)return r.hosting.result;await this.hosted.next(t.fileId,t)}}catch(r){throw new Do(t.fileId,{cause:r})}}async hostedFile(t,r,n){let o=await this.hosted.load(t.terms.file_id);if(!o.hosting.result||!o.hosting.header||!t.fileKey)throw new S("invalid_record");let i=G(o.hosting.header,(o.hosting.header.length-2)/2),s=await ui(G(t.fileKey,32),r,{fileId:G(o.terms.file_id,32),name:o.name,mime:o.mime,authKind:hr(o.terms.seller)});if(Y(s.cipherHash)!==o.terms.cipher_hash)throw new br;let a=!1,c;if(r instanceof Uint8Array)c=Te(i,new Uint8Array(await new Response(s.body()).arrayBuffer())),a=!0;else{let d=s.body().getReader(),f=!0;c=new ReadableStream({async pull(u){if(f){f=!1,u.enqueue(i);return}try{let l=await d.read();l.done?(a=!0,u.close(),d.releaseLock()):u.enqueue(l.value)}catch(l){u.error(l),d.releaseLock()}},async cancel(u){try{await d.cancel(u)}finally{d.releaseLock()}}},{highWaterMark:0})}try{if(await n({file:c,header:i,terms:o.terms}),!a)throw new S("upload_incomplete")}catch(d){throw c instanceof ReadableStream&&await c.cancel(d).catch(()=>{}),d}return{terms:o.terms,...o.baseSplit?{baseSplit:o.baseSplit}:{},file:c,header:i}}async sell(t){if(t.base&&ne(t.seller.identity).kind!=="evm")throw new S("route_unavailable");if(t.hosting){if(t.fileId||t.moderator||(t.previewLen??0)!==0||t.base&&t.base.price!==t.near.price)throw new S("invalid_arguments");let x={data:t.data,name:t.name,mime:t.mime,seller:t.seller,price:t.near.price,near:{recipients:t.near.recipients,remainder:t.near.remainder},hosting:t.hosting,...t.storageBudget!==void 0?{storageBudget:t.storageBudget}:{},...t.hosting.listingStorage!==void 0?{listingStorage:t.hosting.listingStorage}:{},...t.hosting.confirmBackup?{confirmBackup:t.hosting.confirmBackup}:{},...t.onSplit?{onSplit:t.onSplit}:{}},g=await this.startShare(x);return await this.resumeShare({...x,fileId:g.terms.file_id}),this.hostedFile(g,t.data,t.publish)}if((t.data instanceof Uint8Array?t.data.length:t.data.size)>5e7)throw new $e("too_large");if(t.storageBudget!==void 0&&(t.storageBudget<=0n||t.storageBudget>=2n**128n))throw new S("invalid_arguments","invalid storage budget");if(t.storageBudget!==void 0&&t.seller.identity.kind!=="near")throw new S("near_wallet_required","storage budget requires a NEAR wallet");let r=await ao(this.o.nearRpc,this.o.contractId);if(r.network!==this.o.network)throw new re("network_mismatch");let n={nearUsdc:r.nearUsdc,baseUsdc:r.usdc},o=ne(t.seller.identity),i=t.fileId??`0x${sn(32)}`,s=crypto.getRandomValues(new Uint8Array(32)),a=await ui(s,t.data,{fileId:G(i,32),name:t.name,mime:t.mime,authKind:hr(o),...t.previewLen===void 0?{}:{previewLen:t.previewLen}}),c={token:r.nearUsdc,...t.near,remainder:t.near.recipients.findIndex(x=>Q(x.identity)===Q(t.near.remainder))},d;if(this.o.sponsorship&&o.kind!=="near"){let x=(await this.o.sponsorship()).fee;if(d=x,!t.onSplit&&[c.price,...t.base?[t.base.price]:[]].some(g=>ds(g,x,this.o.maxProtocolFee)))throw new re("protocol_fee_above_max");c=If(c,d,t.base?.price),po({near:c,base:t.base?{price:t.base.price}:null},d)}let f=d!==void 0&&[c.price,...t.base?[t.base.price]:[]].some(x=>ds(x,d,this.o.maxProtocolFee));if(f&&!t.onSplit)throw new re("protocol_fee_above_max");await t.onSplit?.(c,d,f);let u=c.recipients[c.remainder]?.identity,l=c.recipients.map(x=>({...x,identity:ne(x.identity)})).sort((x,g)=>Ur(Tt(x.identity),Tt(g.identity))),p=l.findIndex(x=>Q(x.identity)===Q(u)),m={network:this.o.network,contract:this.o.contractId,file_id:i,seller:o,pay2_version:2,cipher_hash:Y(a.cipherHash),moderator:t.moderator??null,near:{token:r.nearUsdc,price:t.near.price,recipients:l,remainder:p},base:null};tt(m,n);let h=null;if(t.base){if(l.some(v=>v.identity.kind!=="evm"))throw new S("bad_requirements","Base split requires only EVM recipients");let x=t.base.kind??"push",g=`0x${sn(32)}`,w=Af(x,{recipients:l.map(v=>v.identity.id),allocations:l.map(v=>BigInt(v.bps)),totalAllocation:10000n,distributionIncentive:0},g);h={address:w.address,kind:x,salt:g},m.base={usdc:r.usdc,price:t.base.price,pay_to:w.address},tt(m,n),await t.base.sendTransaction(w)}let y=fo(),b={kind:"sell",...t.storageBudget!==void 0?{storageBudget:t.storageBudget.toString()}:{},id:`sell:${i}`,revision:0,terms:m,baseSplit:h,fileKey:Y(s),sellerSecret:Y(y.secret),deadline:this.now()+540,name:t.name,mime:t.mime,previewLen:t.previewLen??0,ckdSecret:null};try{if(!await this.sells.compareAndSet(`annon/sell/${i}`,null,b))throw new re("store_conflict");return await this.finishSell(b,a,t.seller,t.publish,!1)}catch(x){throw new Do(i,{cause:x})}}async resumeSell(t){if((t.data instanceof Uint8Array?t.data.length:t.data.size)>5e7)throw new $e("too_large");let r=await this.sells.load(`annon/sell/${t.fileId}`);if(!r)throw new S("invalid_record","no saved sell job");if(r.hosting&&!r.published){if(!t.hosting)throw new S("transport_required");return await this.resumeShare({fileId:t.fileId,data:t.data,seller:t.seller,hosting:t.hosting}),this.hostedFile(r,t.data,t.publish)}if(r.published)throw await this.o.writeBackup(r.id,await wn(r,this.o.backupSecret)),new S("invalid_record","sell already published; secrets cleared");if(!r.fileKey||!r.sellerSecret)throw new S("invalid_record","sell job has no file key");if(r.terms.contract!==this.o.contractId||Q(r.terms.seller)!==Q(t.seller.identity))throw new S("wrong_identity","sell job identity mismatch");await this.o.writeBackup(r.id,await wn(r,this.o.backupSecret));let n=await ui(G(r.fileKey,32),t.data,{fileId:G(t.fileId,32),name:r.name,mime:r.mime,authKind:hr(r.terms.seller),previewLen:r.previewLen});if(Y(n.cipherHash)!==r.terms.cipher_hash)throw new S("cipher_hash_mismatch","original data cipher hash mismatch");let o=await ai(this.o.nearRpc,this.o.contractId,t.fileId);if(o&&o.termsHash!==tt(r.terms,F5(r.terms)))throw new S("file_mismatch","registered sell job mismatch");try{return await this.finishSell(r,n,t.seller,t.publish,o!==null)}catch(i){throw new Do(t.fileId,{cause:i})}}async reopenSeller(t){let r=await this.file(t.fileId);if(Q(r.seller)!==Q(t.seller.identity))throw new S("wrong_identity","not the registered seller");let n=`annon/seller-key/${t.fileId}`,o=await this.sellerKeys.load(n),i=fo(),s={kind:"seller-key",id:`seller-key:${t.fileId}`,file_id:t.fileId,seller:r.seller,revision:(o?.revision??-1)+1,buyerSecret:Y(i.secret),deadline:this.now()+540};if(!await this.sellerKeys.compareAndSet(n,o,s))throw new re("store_conflict");let a={file_id:t.fileId,key:Y(i.publicKeyBytes),deadline:s.deadline},c=await this.auth(t.seller,Rw(this.o.contractId,a,r.seller)),d=await this.answer(await this.call("reopen_seller",{args:a,...c?{auth:c}:{}},t.seller),i.secret,t.fileId);if(!await this.sellerKeys.compareAndSet(n,s,{...s,revision:s.revision+1,buyerSecret:null}))throw new re("store_conflict");return i.secret.fill(0),d}async finishSell(t,r,n,o,i){let s=t.terms.file_id,a;if(t.ckdSecret)a=G(t.ckdSecret,48);else{if(i)a=await this.reopenSeller({fileId:s,seller:n});else{let x=Gt(G(t.sellerSecret,32)),g={terms:t.terms,seller_key:Y(x.publicKeyBytes),deadline:this.now()+540},w=await this.auth(n,Bw(this.o.contractId,g,F5(t.terms)));a=await this.answer(await this.call("register",{args:g,...w?{auth:w}:{},...w&&t.baseSplit?{baseSplit:{kind:t.baseSplit.kind,salt:t.baseSplit.salt}}:{}},n),x.secret,s)}let y=await this.sells.load(`annon/sell/${s}`);if(!y)throw new S("invalid_record","sell job missing");let b={...y,revision:y.revision+1,ckdSecret:Y(a)};if(!await this.sells.compareAndSet(`annon/sell/${s}`,y,b))throw new re("store_conflict")}let{file:c,header:d,consumed:f,cancel:u}=await r.finish({contractId:this.o.contractId,ckdSecret:a,seller:t.terms.seller,...n.identity.kind==="near"?{}:{sign:async y=>{let b=await this.auth(n,y);if(!b)throw new S("invalid_signature","missing header authorization");let x=G(b.sig,n.identity.kind==="evm"?65:64);return n.identity.kind==="solana"?{signature:x,signedMessage:new TextEncoder().encode(y)}:x}}}),l=d.length;try{if(n.identity.kind==="near"&&await this.call("publish_header",{file_id:s,header_hash:Y(await Oe(d.subarray(0,l-65)))},n),t.storageBudget){let y=`annon/sell/${s}`,b=await this.sells.load(y);if(!b)throw new S("invalid_record","sell job missing");let x=BigInt(t.storageBudget);if(b.storageFunding==="pending"){if((await N0(this.o.nearRpc,this.o.contractId,s)).available<x)throw new re("storage_required","Previous file funding is uncertain; inspect it and explicitly fund before resuming.")}else if(b.storageFunding!=="funded"){let g={...b,revision:b.revision+1,storageFunding:"pending"};if(!await this.sells.compareAndSet(y,b,g))throw new re("store_conflict");b=g;try{await wy(Lo(n),this.o.contractId,s,x)}catch(w){throw w instanceof Hi&&!await this.sells.compareAndSet(y,b,{...b,revision:b.revision+1,storageFunding:"refused"})?new re("store_conflict"):w}}if(b.storageFunding!=="funded"&&!await this.sells.compareAndSet(y,b,{...b,revision:b.revision+1,storageFunding:"funded"}))throw new re("store_conflict")}if(await o({file:c,header:d,terms:t.terms}),!f())throw new S("upload_incomplete","publish did not consume the complete file stream")}catch(y){throw await u(y).catch(()=>{}),y}let p=`annon/seller-key/${s}`,m=await this.sellerKeys.load(p);if(m?.buyerSecret&&!await this.sellerKeys.compareAndSet(p,m,{...m,revision:m.revision+1,buyerSecret:null}))throw new re("store_conflict");let h=await this.sells.load(`annon/sell/${s}`);if(!h||!await this.sells.compareAndSet(`annon/sell/${s}`,h,{...h,revision:h.revision+1,published:!0,fileKey:null,sellerSecret:null,ckdSecret:null}))throw new re("store_conflict");return a.fill(0),{terms:t.terms,...t.baseSplit?{baseSplit:t.baseSplit}:{},file:c,header:d}}async buy(t){if(typeof t.maxPrice!="bigint"||t.maxPrice<=0n||t.maxPrice>=2n**128n)throw new S("max_price_required","maxPrice must be a positive human-approved cap");let r=await this.file(t.fileId,!0);if(r.moderator!==null&&!(t.moderators??[]).includes(r.moderator))throw new re("unknown_moderator");let n=await ni(t.header,wp(t.fileId,r),this.o.contractId);if(!n.usable)throw new re("file_invalid");if(t.route!==void 0&&!["near","base","1click"].includes(t.route))throw new S("invalid_arguments","invalid purchase route");if(t.route==="base"&&!r.terms.base)throw new S("route_unavailable");if(t.route==="near"&&t.payer?.identity.kind!=="near")throw new S("near_wallet_required","direct NEAR requires a NEAR payment wallet");if(t.route==="1click"&&!t.origin)throw new S("origin_required","a 1Click origin is required");if(t.route==="base"&&(t.payer?.identity.kind!=="evm"||!("signTypedData"in t.payer)))throw new S("base_wallet_required","Base requires Base terms and an EVM payment wallet");let o=t.route==="1click"||t.route===void 0&&t.payer?.identity.kind!=="near",i={load:B=>this.store.load(B),compareAndSet:async(B,N,U)=>{U&&await t.beforeSave?.(U);let R=await this.store.compareAndSet(B,N,U);return R&&U&&await t.onSaved?.(U),R}},s=t.route==="base"?"base-usdc":"near-usdc";if(t.route===void 0&&t.payer?.identity.kind==="evm"&&r.terms.base&&"signTypedData"in t.payer){let B=await lo(this.o.baseRpc);!await _f(this.o.baseRpc,t.payer.identity.id,B.number)&&await Ef(this.o.baseRpc,r.terms.base.usdc,t.payer.identity.id,B.number)>=BigInt(r.terms.base.price)&&(s="base-usdc")}let a=s==="base-usdc"?"base":o?"1click":"near";s==="near-usdc"&&o&&t.origin&&Gh(t.origin);let c=s==="base-usdc"&&r.terms.base?r.terms.base.price:r.terms.near.price;if(BigInt(c)>t.maxPrice)throw new re("price_above_max");let d=async()=>{};if(s==="base-usdc"){if(t.baseUnlock!==void 0&&!["relayer","self"].includes(t.baseUnlock))throw new S("invalid_arguments","invalid Base unlock transport");if(t.baseUnlock==="self")Lo(t.recovery),d=async()=>Kh(r,this.o.baseRpc);else{if(!this.o.relayer)throw new S("transport_required");let B=await ao(this.o.nearRpc,this.o.contractId),N={deployment:{network:this.o.network,contractId:this.o.contractId,nearUsdc:B.nearUsdc,baseUsdc:B.usdc},file:r,baseRpc:this.o.baseRpc,relayer:this.o.relayer,...this.o.fetch?{fetch:this.o.fetch}:{},now:()=>this.now()},U=t.baseSponsorship;d=async()=>{Vh(U,N)||(U=await Wh(N))}}}if(await d(),s==="near-usdc"){let B=await N0(this.o.nearRpc,this.o.contractId,t.fileId);if(B.available<B.admissionRequirement)throw new re("file_storage_low")}if(s==="near-usdc"&&t.payer?.identity.kind!=="near"&&!t.origin)throw new S("origin_required","a 1Click origin is required for cross-chain payment");let f=ne(t.recovery.identity),u=fo(),l={version:2,refund:ne(t.refund),network:s==="base-usdc"?"eip155:8453":this.o.network,contract:this.o.contractId,route:s,asset:s==="base-usdc"&&r.terms.base?r.terms.base.usdc:r.terms.near.token,file_id:t.fileId,terms_hash:r.termsHash,price:c,nonce:`0x${sn(32)}`,buyer_key:Y(u.publicKeyBytes),recovery:f,expires_at:String(this.now()+3600)},p={nearUsdc:r.terms.near.token,...r.terms.base?{baseUsdc:r.terms.base.usdc}:{}},m=gn(l,p),h=$r(l,p);es(h,p);let y=`Annon: verify purchase recovery
46
+ header: ${r}`}var Re=class extends S{code;constructor(t,r=t){super(t,r),this.code=t,this.name="Pay2Error"}},Ae=(e,t)=>{throw new Re(e,t)},Ya=[80,65,89,50],Hr=54,ve=16,m0=65536,Wi=1024,Qb=65536,Kd=4096,hn=32,yr=65,yn="near-ckd/v1",qt=globalThis.crypto.subtle,to=new TextEncoder;function Te(...e){return at(e)}function rt(e,t){let r=new Uint8Array(t),n=new DataView(r.buffer);return t===1?n.setUint8(0,e):t===2?n.setUint16(0,e):t===4?n.setUint32(0,e):n.setBigUint64(0,BigInt(e)),r}var pt=(e,t)=>e.length===t.length&&e.every((r,n)=>r===t[n]),We=e=>new Uint8Array(e);function Zi(e){if(!(e.buffer instanceof ArrayBuffer))throw new TypeError("pass bytes over an ArrayBuffer");return e}async function Oe(...e){let t=e.length===1?Zi(e[0]):Te(...e);return new Uint8Array(await qt.digest("SHA-256",t))}async function ei(e,t,r){let n=e instanceof Uint8Array?await qt.importKey("raw",We(e),"HKDF",!1,["deriveBits"]):e,o=await qt.deriveBits({name:"HKDF",hash:"SHA-256",salt:We(t),info:typeof r=="string"?to.encode(r):We(r)},n,256);return new Uint8Array(o)}var ti=(e,t,r)=>ei(e,t,Te(to.encode("annon/pay2/chunk"),rt(r,4))),Xa=e=>Oe(to.encode("annon/pay2/key"),e);function Ov(e){let t=new Uint8Array(12);return t[11]=e?1:0,t}async function Ja(e,t,r,n){let o=await qt.importKey("raw",We(t),"AES-GCM",!1,[e]),i=await qt[e]({name:"AES-GCM",iv:Ov(r)},o,Zi(n));return new Uint8Array(i)}var Qa=async(e,t,r)=>{if(e.length!==48)throw new TypeError("ckdSecret must be the 48-byte G1 point");let n=await ei(e,t,"annon/pay2/near-ckd/v1");return qt.importKey("raw",n,"AES-KW",!1,[r])},ec=e=>Oe(to.encode("annon/pay2/body"),new Uint8Array([e.version??2,e.chunkLog2]),e.fileId,rt(e.metaLen,2),rt(e.previewLen,4),rt(e.n,4),...e.commits,...e.hashes);function p0(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t)}function Za(e,t=32){let r=typeof e=="string"?e.replace(/^0x/,""):"";if(typeof e!="string"?e.length!==t:!new RegExp(`^[0-9a-f]{${2*t}}$`,"i").test(r))throw new TypeError(`expected ${t} bytes`);return typeof e=="string"?Uint8Array.from(r.match(/../g)??[],n=>Number.parseInt(n,16)):e}function eg(e){if(!/^0x[0-9a-f]{40}$/i.test(e))throw new TypeError("seller must be a 0x EVM address");return e.toLowerCase()}function h0(e,t=!1){(e.length<4||!Ya.every((x,g)=>e[g]===x))&&Ae("bad_magic"),e.length<Hr&&Ae("bad_header","shorter than the fixed header");let r=new DataView(e.buffer,e.byteOffset,e.byteLength);e[4]!==2&&Ae("unsupported_version");let n=e[4],o=e[7]??0,i=e[5]??0;(i<16||i>24)&&Ae("bad_chunk_size");let s=r.getUint32(8);s>m0&&Ae("header_too_large");let a=e[6]??0,c=r.getUint16(44),d=r.getUint32(46),f=r.getUint32(50),u=d>0?2:1,l=Hr+32*(u+f);(!(t?a===0&&s===0:a>=1&&a<=8&&s>=l+hn+yr)||o>2||c<256||c>Kd||c%256!==0||d>Qb||f<2||f>Wi||d>0&&f<3||e.length<(t?l:s))&&Ae("bad_header");let m=x=>e.slice(Hr+32*x,Hr+32*(x+1)),h={version:n,authKind:o,chunkLog2:i,fileId:e.slice(12,44),metaLen:c,previewLen:d,n:f,commits:Array.from({length:u},(x,g)=>m(g)),hashes:Array.from({length:f},(x,g)=>m(u+g)),prefixLen:l,headerLen:s,stanzas:[]};if(t)return h;let y=s-hn-yr,b=l;for(let x=0;x<a;x++){let g=e[b]??0;(g<1||g>32||b+3+g>y)&&Ae("bad_stanza");let w=String.fromCharCode(...e.subarray(b+1,b+1+g)),v=r.getUint16(b+1+g),E=b+3+g;(!/^[a-z0-9/.-]+$/.test(w)||v>1024||E+v>y||h.stanzas.some(N=>N.type===w))&&Ae("bad_stanza");let B=e.slice(E,E+v);w===yn&&!ri(B)&&Ae("bad_stanza"),h.stanzas.push({type:w,body:B}),b=E+v}return b!==y&&Ae("bad_header","stanzas do not end at the MAC"),h}function ri(e){let t=e[0]??0;if(t<2||t>64||e.length!==1+t+40)return;let r=String.fromCharCode(...e.subarray(1,1+t));if(/^[a-z0-9._-]+$/.test(r))return{contractId:r,wrapped:e.slice(1+t)}}function tg(e){return Array.from({length:e.n-1},(t,r)=>r===0?e.metaLen+ve:r===1&&e.previewLen>0?e.previewLen+ve:2**e.chunkLog2+ve)}var ro=(e,t,r)=>1+(t>0?1:0)+Math.max(1,Math.ceil((e-t)/2**r));function y0(e,t){let r=p=>Ae("meta_invalid",p),n=new DataView(e.buffer,e.byteOffset,e.byteLength),i=2+n.getUint16(0);i+1>e.length&&r("name runs past the metadata");let s=e[i]??0,a=i+1+s,c=a+8;c>e.length&&r("mime runs past the metadata"),Math.ceil(c/256)*256!==e.length&&r("padding is not minimal"),e.subarray(c).some(p=>p!==0)&&r("padding is not zero");let d="";try{d=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(e.subarray(2,i))}catch{r("name is not UTF-8")}let f=e.subarray(i+1,a);f.some(p=>p<32||p>126)&&r("mime is not printable ASCII");let u=n.getBigUint64(a);u>BigInt(Number.MAX_SAFE_INTEGER)&&r("size too large");let l=Number(u);return t.previewLen>no(l)&&r("preview over the limit"),t.n!==ro(l,t.previewLen,t.chunkLog2)&&r("chunk count does not fit the size"),{name:d,mime:String.fromCharCode(...f),size:l}}async function rg(e,t,r){return ng(await og(Zi(e),t,r),Zi(e),r)}async function ni(e,t,r){let n=Zi(e),o=await Yi(n,t,r);return n.length!==o.headerLen&&Ae("bad_header","expected the header alone"),ng(o,n,r)}var ng=async(e,t,r)=>{let n=We(t.subarray(0,e.headerLen));return{fileId:e.fileId,usable:e.stanzas.some(o=>o.type===yn&&ri(o.body)?.contractId===r),header:n,headerHash:await Oe(n)}};async function Yi(e,t,r){let n=h0(e),o=t.pay2Version??2;n.version!==o&&Ae("unsupported_version");let i=await Cv(n,t),s=typeof t.seller=="string"?ne({kind:"evm",id:eg(t.seller)}):ne(t.seller),a=await Oe(e.subarray(0,i.headerLen-yr)),c=e.subarray(i.headerLen-yr,i.headerLen);if(hr(s)!==i.authKind&&Ae("seller_signature_invalid"),s.kind==="near")(c.some(d=>d!==0)||t.publishedHeaderHash===void 0||!pt(a,Za(t.publishedHeaderHash)))&&Ae("seller_signature_invalid");else{s.kind==="solana"&&c[64]!==0&&Ae("seller_signature_invalid");let d=s.kind==="solana"?c.subarray(0,64):c;lt(s,l0(r,Y(i.fileId),Y(a)),{kind:s.kind,sig:Y(d)})||Ae("seller_signature_invalid")}return i}async function og(e,t,r){let n=await Yi(e,t,r),o=tg(n),i=e.subarray(n.headerLen),s=i.length-o.reduce((c,d)=>c+d,0);(s<ve||s>2**n.chunkLog2+ve)&&Ae("bad_body_length");let a=0;for(let[c,d]of[...o,s].entries())pt(await Oe(i.subarray(a,a+d)),n.hashes[c])||Ae("chunk_hash_mismatch",`chunk ${c}`),a+=d;return n}async function Cv(e,t){return pt(e.fileId,Za(t.fileId))||Ae("file_id_mismatch"),pt(await ec(e),Za(t.cipherHash))||Ae("cipher_hash_mismatch"),e}async function ig(e,t){let r=Zi(e),n=await og(r,t.listing,t.contractId),o=n.stanzas.map(b=>b.type===yn?ri(b.body):void 0).find(b=>b?.contractId===t.contractId);if(!o)return Ae("no_usable_stanza");let i=await Qa(await t.ckdSecret(n.fileId),n.fileId,"unwrapKey"),s;try{s=await qt.unwrapKey("raw",o.wrapped,i,"AES-KW","HKDF",!1,["deriveBits"])}catch{return Ae("key_unwrap_failed")}let a=await qt.importKey("raw",await ei(s,n.fileId,"annon/pay2/header"),{name:"HMAC",hash:"SHA-256"},!1,["verify"]),c=n.headerLen-hn-yr,d=r.subarray(c,c+hn);await qt.verify("HMAC",a,d,r.subarray(0,c))||Ae("header_mac_invalid");let f=tg(n),u=r.subarray(n.headerLen);f.push(u.length-f.reduce((b,x)=>b+x,0));let l=[],p=0;for(let b of f)l.push(u.subarray(p,p+b)),p+=b;let m=async b=>{let x=await ti(s,n.fileId,b),g=n.commits[b];g&&!pt(await Xa(x),g)&&Ae("chunk_invalid",`chunk ${b} key commitment`);try{return await Ja("decrypt",x,b===n.n-1,l[b])}catch{return Ae("chunk_invalid",`chunk ${b}`)}},h=y0(await m(0),n);f.slice(1).reduce((b,x)=>b+x-ve,0)!==h.size&&Ae("meta_invalid","chunk lengths do not add up to the size");let y=[];for(let b=1;b<n.n;b++)y.push(await m(b));return{meta:h,data:Te(...y)}}function b0(e){let t=e.version??2,r=e.authKind??0;if(t!==2||![0,1,2].includes(r))throw new TypeError("invalid PAY2 version/auth kind");return{version:t,authKind:r}}async function g0(e,t,r,n,o){let i=typeof r.seller=="string"?ne({kind:"evm",id:eg(r.seller)}):ne(r.seller);if(hr(i)!==t)throw new TypeError("seller identity does not match auth kind");if(i.kind==="near")return new Uint8Array(yr);if(!r.sign)throw new TypeError("seller signature required");if(e!==2)throw new TypeError("unsupported PAY2 version");let s=l0(r.contractId,Y(n),Y(o)),a=await r.sign(s);if(i.kind==="solana"){if(typeof a=="string"||a instanceof Uint8Array)throw new TypeError("Solana wallet must return signed bytes");let d=f0(i,s,a);return Te(Za(d.sig,64),new Uint8Array([0]))}if(typeof a!="string"&&!(a instanceof Uint8Array))throw new TypeError("expected EVM signature bytes");let c=Za(a,yr);if(!Ka(s,c,i.id))throw new Error("the signature is not from the seller");return c}async function sg(e,t,r){if(r.fileId.length!==32||e.length!==32)throw new TypeError("fileId and K are 32 bytes");let{version:n,authKind:o}=b0(r),i=We(r.fileId),s=r.previewLen??0;if(!Number.isSafeInteger(s)||s<0||s>no(t.length))throw new RangeError(`previewLen must be 0 to ${no(t.length)}`);let a=r.chunkLog2??22;for(;r.chunkLog2===void 0&&a<24&&ro(t.length,s,a)>Wi;)a++;if(!Number.isInteger(a)||a<16||a>24)throw new RangeError("chunkLog2 must be an integer from 16 to 24");if(ro(t.length,s,a)>Wi)throw new RangeError("file too large for PAY2");let c=2**a,d=to.encode(r.name);if(!/^[\x20-\x7e]{0,255}$/.test(r.mime))throw new RangeError("mime must be printable ASCII");let f=Te(rt(d.length,2),d,rt(r.mime.length,1),to.encode(r.mime),rt(t.length,8)),u=Math.ceil(f.length/256)*256;if(u>Kd)throw new RangeError("name too long");let l=[Te(f,new Uint8Array(u-f.length))];s>0&&l.push(t.subarray(0,s));let p=t.subarray(s);for(let v=0;v<p.length||v===0;v+=c)l.push(p.subarray(v,v+c));let m=l.length,h=await Promise.all(l.map((v,E)=>ti(e,i,E))),y=await Promise.all(h.slice(0,s>0?2:1).map(v=>Xa(v))),b=await Promise.all(l.map((v,E)=>Ja("encrypt",h[E],E===m-1,v))),x=await Promise.all(b.map(v=>Oe(v))),g=Te(new Uint8Array(Ya),new Uint8Array([n,a,1,o]),new Uint8Array(4),i,rt(u,2),rt(s,4),rt(m,4),...y,...x),w;return{fileId:i,cipherHash:await ec({version:n,chunkLog2:a,fileId:i,metaLen:u,previewLen:s,n:m,commits:y,hashes:x}),async finish(v){let{contractId:E,ckdSecret:B}=v;be(E);let N=await Qa(B,i,"wrapKey"),U=await qt.importKey("raw",We(e),"AES-GCM",!0,["encrypt"]),R=new Uint8Array(await qt.wrapKey("raw",U,N,"AES-KW")),T=to.encode(yn),O=Te(new Uint8Array([E.length]),to.encode(E),R),H=Te(new Uint8Array([T.length]),T,rt(O.length,2),O),P=Te(g,H);new DataView(P.buffer).setUint32(8,P.length+hn+yr);let _=await qt.importKey("raw",await ei(e,i,"annon/pay2/header"),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),I=new Uint8Array(await qt.sign("HMAC",_,P)),k=await g0(n,o,v,i,await Oe(P,I));return w=P,Te(P,I,k,...b)},async preview(v){if(!w)throw new Error("call finish first: the preview carries the final header");if(v.data&&s===0)throw new RangeError("sealed without a preview");let E=[...v.meta?[0]:[],...v.data?[1]:[]];return{v:1,header:p0(Uv(w.subarray(0,g.length))),chunks:E.map(B=>({index:B,key:p0(h[B]),data:p0(b[B])}))}}}}function Uv(e){let t=We(e);return t[6]=0,t.fill(0,8,12),t}var no=e=>Math.min(Qb,Math.floor(e/10));var Nv=BigInt(0),Wd=BigInt(1),ag=BigInt(2),Xi=BigInt(3);function Fv(e){let t=[];for(;e>Wd;e>>=Wd)(e&Wd)===Nv?t.unshift(0):(e&Xi)===Xi?(t.unshift(-1),e+=Wd):t.unshift(1);return t}function w0(e){if(!Array.isArray(e)||e.length===0)throw new Error("expected non-empty array")}function Mv(e,t,r,n){if(Be(e,{Fp:"object",Fr:"object",Fp2:"object",Fp12:"object"},{Fp6:"object"},"fields"),typeof t!="function")throw new TypeError('"G1_Point" expected point constructor, got type='+typeof t);if(typeof r!="function")throw new TypeError('"G2_Point" expected point constructor, got type='+typeof r);Be(n,{ateLoopSize:"bigint",xNegative:"boolean",twistType:"string"},{randomBytes:"function",postPrecompute:"function"},"params");let{Fp:o,Fr:i,Fp2:s,Fp12:a}=e,{twistType:c,ateLoopSize:d,xNegative:f,postPrecompute:u}=n,l=(k,M)=>({c0:k,c1:M}),p=({c0:k,c1:M})=>Object.freeze({c0:k,c1:M}),m=(k,M)=>l(o.add(k.c0,M.c0),o.add(k.c1,M.c1)),h=(k,M)=>l(o.sub(k.c0,M.c0),o.sub(k.c1,M.c1)),y=(k,M)=>{let $=o.mul(k.c0,M.c0),F=o.mul(k.c1,M.c1);return l(o.sub($,F),o.sub(o.mul(o.add(k.c0,k.c1),o.add(M.c0,M.c1)),o.add($,F)))},b=(k,M)=>l(o.mul(k.c0,M),o.mul(k.c1,M)),x=k=>s.mulByNonresidue(k),g=({c0:k,c1:M},$,F,A,z,D)=>{let q=b(F,z),j=b(A,D),{c0:K,c1:W,c2:Z}=k,{c0:te,c1:J,c2:de}=M,ue=y(K,$),me=y(W,q),Ne=m(x(h(y(m(W,Z),q),me)),ue),fe=h(h(y(m($,q),m(K,W)),ue),me),we=m(h(y(m(K,Z),$),ue),me),an=x(y(de,j)),Ln=y(te,j),dr=y(J,j),cn=m(K,te),dn=m(W,J),qo=m(Z,de),jo=m(q,j),Go=y(cn,$),Vo=y(dn,jo),_p=m(x(h(y(m(dn,qo),jo),Vo)),Go),Ap=h(h(y(m($,jo),m(cn,dn)),Go),Vo),Tp=m(h(y(m(cn,qo),$),Go),Vo);return Object.freeze({c0:Object.freeze({c0:p(m(x(dr),Ne)),c1:p(m(an,fe)),c2:p(m(Ln,we))}),c1:Object.freeze({c0:p(h(h(_p,Ne),an)),c1:p(h(h(Ap,fe),Ln)),c2:p(h(h(Tp,we),dr))})})},w=({c0:k,c1:M},$,F,A,z,D)=>{let q=b($,D),j=b(F,z),{c0:K,c1:W,c2:Z}=k,{c0:te,c1:J,c2:de}=M,ue=y(K,q),me=y(W,q),Ne=y(Z,q),fe=y(te,j),we=y(J,A),an=m(x(h(y(m(J,de),A),we)),fe),Ln=h(h(y(m(j,A),m(te,J)),fe),we),dr=m(h(y(m(te,de),j),fe),we),cn=m(K,te),dn=m(W,J),qo=m(Z,de),jo=m(q,j),Go=y(cn,jo),Vo=y(dn,A),_p=m(x(h(y(m(dn,qo),A),Vo)),Go),Ap=h(h(y(m(jo,A),m(cn,dn)),Go),Vo),Tp=m(h(y(m(cn,qo),jo),Go),Vo);return Object.freeze({c0:Object.freeze({c0:p(m(x(dr),ue)),c1:p(m(an,me)),c2:p(m(Ln,Ne))}),c1:Object.freeze({c0:p(h(h(_p,ue),an)),c1:p(h(h(Ap,me),Ln)),c2:p(h(h(Tp,Ne),dr))})})},v;if(c==="multiplicative")v=(k,M,$,F,A,z)=>g(F,k,M,$,A,z);else if(c==="divisive")v=(k,M,$,F,A,z)=>w(F,$,M,k,A,z);else throw new Error("bls: unknown twist type");let E=s.div(s.ONE,s.mul(s.ONE,ag));function B(k,M,$,F){let A=s.sqr($),z=s.sqr(F),D=s.mulByB(s.mul(z,Xi)),q=s.mul(D,Xi),j=s.sub(s.sub(s.sqr(s.add($,F)),z),A),K=s.sub(D,A),W=s.mul(s.sqr(M),Xi),Z=s.neg(j);return k.push([K,W,Z]),M=s.mul(s.mul(s.mul(s.sub(A,q),M),$),E),$=s.sub(s.sqr(s.mul(s.add(A,q),E)),s.mul(s.sqr(D),Xi)),F=s.mul(A,j),{Rx:M,Ry:$,Rz:F}}function N(k,M,$,F,A,z){let D=s.sub($,s.mul(z,F)),q=s.sub(M,s.mul(A,F)),j=s.sub(s.mul(D,A),s.mul(q,z)),K=s.neg(D),W=q;k.push([j,K,W]);let Z=s.sqr(q),te=s.mul(Z,q),J=s.mul(Z,M),de=s.add(s.sub(te,s.mul(J,ag)),s.mul(s.sqr(D),F));return M=s.mul(q,de),$=s.sub(s.mul(s.sub(J,de),D),s.mul(te,$)),F=s.mul(F,te),{Rx:M,Ry:$,Rz:F}}let U=Fv(d),R=k=>{if(!(k instanceof r))throw new TypeError('"point" expected G2 point, got type='+typeof k);let M=k,{x:$,y:F}=M.toAffine(),A=$,z=F,D=s.neg(F),q=A,j=z,K=s.ONE,W=[];for(let Z of U){let te=[];({Rx:q,Ry:j,Rz:K}=B(te,q,j,K)),Z&&({Rx:q,Ry:j,Rz:K}=N(te,q,j,K,A,Z===-1?D:z)),W.push(te)}if(u){let Z=W[W.length-1];u(q,j,K,A,z,N.bind(null,Z))}return W};function T(k,M=!1){Jt(k,"pairs",(F,A)=>{if(Jt(F,A),F.length!==3)throw new TypeError(`"${A}" expected precompute tuple`);Jt(F[0],A+"[0]")});let $=a.ONE;if(k.length){let F=k[0][0].length;for(let A=0;A<F;A++){A!==0&&($=a.sqr($));for(let[z,D,q]of k)for(let[j,K,W]of z[A])$=v(j,K,W,$,D,q)}}return f&&($=a.conjugate($)),M?a.finalExponentiate($):$}function O(k,M=!0){Jt(k,"pairs");let $=[];for(let F=0;F<k.length;F++){let A=k[F];Be(A,{g1:"object",g2:"object"},{},"pairs["+F+"]");let{g1:z,g2:D}=A;if(!(z instanceof t))throw new TypeError('"pairs['+F+'].g1" expected G1 point, got type='+typeof z);if(!(D instanceof r))throw new TypeError('"pairs['+F+'].g2" expected G2 point, got type='+typeof D);if(z.is0()||D.is0())throw new Error("pairing is not available for ZERO point");z.assertValidity(),D.assertValidity();let q=z.toAffine();$.push([R(D),q.x,q.y])}return T($,M)}function H(k,M,$=!0){if(!(k instanceof t))throw new TypeError('"Q" expected G1 point, got type='+typeof k);if(!(M instanceof r))throw new TypeError('"P" expected G2 point, got type='+typeof M);return O([{g1:k,g2:M}],$)}let P={seed:qi(i.ORDER)},_=n.randomBytes===void 0?lr:n.randomBytes,I=k=>(k=k===void 0?_(P.seed):k,se(k,P.seed,"seed"),ji(k,i.ORDER));return Object.freeze(P),{lengths:P,Fr:i,Fp12:a,millerLoopBatch:T,pairing:H,pairingBatch:O,calcPairingPrecomputes:R,randomSecretKey:I}}function cg(e,t,r,n,o,i){let{Fr:s,Fp12:a,pairingBatch:c,randomSecretKey:d,lengths:f}=e;i||(i={fromBytes:pr,fromHex:pr,toBytes:pr,toHex:pr});let u=Object.freeze({...i});function l(y){return y instanceof t?y:t.fromBytes(y)}function p(y){return y instanceof r?y:u.fromBytes(y)}function m(y){if(!(y instanceof r))throw new Error(`expected valid message hashed to ${n?"G1":"G2"} curve`);return y}let h=n?(y,b)=>({g1:b,g2:y}):(y,b)=>({g1:y,g2:b});return Object.freeze({lengths:Object.freeze({...f,secretKey:s.BYTES}),keygen(y){let b=d(y),x=this.getPublicKey(b);return{secretKey:b,publicKey:x}},getPublicKey(y){let b;try{b=t.Fn.fromBytes(y)}catch(x){throw new Error("invalid private key: "+typeof y,{cause:x})}return t.BASE.multiply(b)},sign(y,b,x){if(x!=null)throw new Error("sign() expects 2 arguments");let g=t.Fn.fromBytes(b);return m(y).assertValidity(),y.multiply(g)},verify(y,b,x,g){if(g!=null)throw new Error("verify() expects 3 arguments");y=p(y),x=l(x);let w=x.negate(),v=t.BASE,E=m(b),B=y;try{let N=c([h(w,E),h(v,B)]);return a.eql(N,a.ONE)}catch{return!1}},verifyBatch(y,b){w0(b);let x=p(y),g=b.map(N=>m(N.message)),w=b.map(N=>l(N.publicKey)),v=new Map;for(let N=0;N<w.length;N++){let U=w[N],R=g[N],T=v.get(R);T===void 0&&(T=[],v.set(R,T)),T.push(U)}let E=[],B=t.BASE;try{for(let[N,U]of v){let R=U.reduce((T,O)=>T.add(O));E.push(h(R,N))}return E.push(h(B.negate(),x)),a.eql(c(E),a.ONE)}catch{return!1}},aggregatePublicKeys(y){w0(y),y=y.map(x=>l(x));let b=y.reduce((x,g)=>x.add(g),t.ZERO);return b.assertValidity(),b},aggregateSignatures(y){w0(y),y=y.map(x=>p(x));let b=y.reduce((x,g)=>x.add(g),r.ZERO);return b.assertValidity(),b},hash(y,b){return se(y),o(y,b===void 0?void 0:{DST:b})},Signature:Object.freeze({...u})})}function Hv(e,t,r,n){let{Fp:o,Fr:i,Fp2:s,Fp6:a,Fp12:c}=e,d={Point:t},f={Point:r},u=Mv(e,t,r,n),{millerLoopBatch:l,pairing:p,pairingBatch:m,calcPairingPrecomputes:h,randomSecretKey:y,lengths:b}=u;return d.Point.BASE.precompute(4),Object.freeze(d),Object.freeze(f),Object.freeze({lengths:Object.freeze(b),millerLoopBatch:l,pairing:p,pairingBatch:m,G1:d,G2:f,fields:Object.freeze({Fr:i,Fp:o,Fp2:s,Fp6:a,Fp12:c}),params:Object.freeze({ateLoopSize:n.ateLoopSize,xNegative:n.xNegative,twistType:n.twistType,postPrecompute:n.postPrecompute}),utils:Object.freeze({randomSecretKey:y,calcPairingPrecomputes:h})})}function zv(e,t,r,n,o){let i=Hv(e,t,r,n);Be(o,{hasherOpts:"object",hasherOptsG1:"object",hasherOptsG2:"object"},{mapToG1:"function",mapToG2:"function"},"hasherParams");let s=Jp(t,o.mapToG1===void 0?pr:o.mapToG1,{...o.hasherOpts,...o.hasherOptsG1}),a=Jp(r,o.mapToG2===void 0?pr:o.mapToG2,{...o.hasherOpts,...o.hasherOptsG2});return Object.freeze({...i,G1:s,G2:a})}function dg(e,t,r,n,o,i){let s=zv(e,t,r,n,o),a={...s,Fr:s.fields.Fr,Fp12:s.fields.Fp12,calcPairingPrecomputes:s.utils.calcPairingPrecomputes,randomSecretKey:s.utils.randomSecretKey},c=cg(a,t,r,!1,s.G2.hashToCurve,i?.LongSignature),d=cg(a,r,t,!0,s.G1.hashToCurve,i?.ShortSignature);return Object.freeze({...s,longSignatures:c,shortSignatures:d})}var x0=BigInt(0),oo=BigInt(1),It=BigInt(2),fg=BigInt(3),$v=BigInt(6),Lv=BigInt(12),oi=e=>!!e&&typeof e=="object";function lg(e,t,r,n,o=1,i){_e(o,"num"),_e(n,"degree");let s=i===void 0?n:i;_e(s,"divisor");let a=e;if(typeof r!="bigint"||r<=oo)throw new Error("calcFrobeniusCoefficients: expected valid modulus, got "+r);if(n<=0)throw new Error("calcFrobeniusCoefficients: expected positive degree, got "+n);if(o<=0)throw new Error("calcFrobeniusCoefficients: expected positive row count, got "+o);if(s<=0)throw new Error("calcFrobeniusCoefficients: expected positive divisor, got "+s);let c=BigInt(s),d=r**BigInt(n),f=[];for(let u=0;u<o;u++){let l=BigInt(u+1),p=[];for(let m=0,h=oo;m<n;m++){let y=l*h-l;if(y%c)throw new Error("calcFrobeniusCoefficients: inexact tower exponent");let b=y/c%d;p.push(a.pow(t,b)),h*=r}f.push(p)}return f}function pg(e,t,r){if(Nt(e),Nt(t),Be(t,{Fp:"object",frobeniusMap:"function",fromBigTuple:"function",mulByB:"function",mulByNonresidue:"function",reim:"function",Fp4Square:"function",NONRESIDUE:"object"},{}),!oi(r)||Array.isArray(r))throw new TypeError('"base" expected Fp2 element, got type='+typeof r);if(!t.isValid(r))throw new RangeError('"base" expected valid Fp2 element');let n=t.pow(r,(e.ORDER-oo)/fg),o=t.pow(r,(e.ORDER-oo)/It);function i(l,p){let m=t.mul(t.frobeniusMap(l,1),n),h=t.mul(t.frobeniusMap(p,1),o);return[m,h]}let s=t.pow(r,(e.ORDER**It-oo)/fg),a=t.pow(r,(e.ORDER**It-oo)/It);if(!t.eql(a,t.neg(t.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function c(l,p){return[t.mul(l,s),t.neg(p)]}let d=l=>(p,m)=>{if(typeof p!="function")throw new TypeError('"c" expected point constructor, got type='+typeof p);if(Fr(p),!(m instanceof p))throw new TypeError('"P" expected Point instance, got type='+typeof m);let h=m.toAffine(),y=l(h.x,h.y);return p.fromAffine({x:y[0],y:y[1]})},f=d(i),u=d(c);return{psi:i,psi2:c,G2psi:f,G2psi2:u,PSI_X:n,PSI_Y:o,PSI2_X:s,PSI2_Y:a}}var v0=class{ORDER;BITS;BYTES;isLE;ZERO;ONE;Fp;NONRESIDUE;mulByB;Fp_NONRESIDUE;Fp_div2;constructor(t,r={}){let{NONRESIDUE:n=BigInt(-1),FP2_NONRESIDUE:o,Fp2mulByB:i}=r,s=t.ORDER,a=s*s;this.Fp=t,this.ORDER=a,this.BITS=tr(a),this.BYTES=Math.ceil(tr(a)/8),this.isLE=t.isLE,this.ZERO=this.create({c0:t.ZERO,c1:t.ZERO}),this.ONE=this.create({c0:t.ONE,c1:t.ZERO}),this.Fp_NONRESIDUE=t.create(n),this.Fp_div2=t.div(t.ONE,It),this.NONRESIDUE=this.create({c0:o[0],c1:o[1]}),this.mulByB=c=>{let{c0:d,c1:f}=i(c);return Object.freeze({c0:d,c1:f})},Object.freeze(this)}fromBigTuple(t){if(!Array.isArray(t)||t.length!==2)throw new Error("invalid Fp2.fromBigTuple");let[r,n]=t;if(typeof r!="bigint"||typeof n!="bigint")throw new Error("invalid Fp2.fromBigTuple");return this.create({c0:r,c1:n})}create(t){let{Fp:r}=this,n=r.create(t.c0),o=r.create(t.c1);return Object.freeze({c0:n,c1:o})}isValid(t){if(!oi(t))throw new TypeError("invalid field element: expected object, got "+typeof t);let{c0:r,c1:n}=t,{Fp:o}=this;return o.isValid(r)&&o.isValid(n)}is0(t){if(!oi(t))return!1;let{c0:r,c1:n}=t,{Fp:o}=this;return o.is0(r)&&o.is0(n)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}eql({c0:t,c1:r},{c0:n,c1:o}){let{Fp:i}=this;return i.eql(t,n)&&i.eql(r,o)}neg({c0:t,c1:r}){let{Fp:n}=this;return Object.freeze({c0:n.neg(t),c1:n.neg(r)})}pow(t,r){return Fd(this,t,r)}invertBatch(t){return mr(this,t,!0)}add(t,r){let{Fp:n}=this,{c0:o,c1:i}=t,{c0:s,c1:a}=r;return Object.freeze({c0:n.add(o,s),c1:n.add(i,a)})}sub({c0:t,c1:r},{c0:n,c1:o}){let{Fp:i}=this;return Object.freeze({c0:i.sub(t,n),c1:i.sub(r,o)})}mul({c0:t,c1:r},n){let{Fp:o}=this;if(typeof n=="bigint")return Object.freeze({c0:o.mul(t,n),c1:o.mul(r,n)});let{c0:i,c1:s}=n,a=o.mul(t,i),c=o.mul(r,s),d=o.sub(a,c),f=o.sub(o.mul(o.add(t,r),o.add(i,s)),o.add(a,c));return Object.freeze({c0:d,c1:f})}sqr({c0:t,c1:r}){let{Fp:n}=this,o=n.add(t,r),i=n.sub(t,r),s=n.add(t,t);return Object.freeze({c0:n.mul(o,i),c1:n.mul(s,r)})}addN(t,r){return this.add(t,r)}subN(t,r){return this.sub(t,r)}mulN(t,r){return this.mul(t,r)}sqrN(t){return this.sqr(t)}div(t,r){let{Fp:n}=this;return this.mul(t,typeof r=="bigint"?n.inv(n.create(r)):this.inv(r))}inv({c0:t,c1:r}){let{Fp:n}=this,o=n.inv(n.create(t*t+r*r));return Object.freeze({c0:n.mul(o,n.create(t)),c1:n.mul(o,n.create(-r))})}sqrt(t){let{Fp:r}=this,n=this,{c0:o,c1:i}=t;if(r.is0(i))return ln(r,o)===1?n.create({c0:r.sqrt(o),c1:r.ZERO}):n.create({c0:r.ZERO,c1:r.sqrt(r.div(o,this.Fp_NONRESIDUE))});let s=r.sqrt(r.sub(r.sqr(o),r.mul(r.sqr(i),this.Fp_NONRESIDUE))),a=r.mul(r.add(s,o),this.Fp_div2);ln(r,a)===-1&&(a=r.sub(a,s));let d=r.sqrt(a),f=n.create({c0:d,c1:r.div(r.mul(i,this.Fp_div2),d)});if(!n.eql(n.sqr(f),t))throw new Error("Cannot find square root");let u=f,l=n.neg(u),{re:p,im:m}=n.reim(u),{re:h,im:y}=n.reim(l);return m>y||m===y&&p>h?u:l}isOdd(t){let{re:r,im:n}=this.reim(t),o=r%It,i=r===x0,s=n%It;return BigInt(o||i&&s)==oo}fromBytes(t){let{Fp:r}=this;if(se(t),t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);return this.create({c0:r.fromBytes(t.subarray(0,r.BYTES)),c1:r.fromBytes(t.subarray(r.BYTES))})}toBytes({c0:t,c1:r}){return ke(this.Fp.toBytes(t),this.Fp.toBytes(r))}cmov({c0:t,c1:r},{c0:n,c1:o},i){let{Fp:s}=this;return this.create({c0:s.cmov(t,n,i),c1:s.cmov(r,o,i)})}reim({c0:t,c1:r}){return{re:t,im:r}}Fp4Square(t,r){let n=this,o=n.sqr(t),i=n.sqr(r);return{first:n.add(n.mulByNonresidue(i),o),second:n.sub(n.sub(n.sqr(n.add(t,r)),o),i)}}mulByNonresidue({c0:t,c1:r}){let{Fp:n,NONRESIDUE:o}=this;return o.c0===n.ONE&&o.c1===n.ONE?Object.freeze({c0:n.sub(t,r),c1:n.add(t,r)}):o.c1===n.ONE?Object.freeze({c0:n.sub(n.mul(t,o.c0),r),c1:n.add(t,n.mul(r,o.c0))}):this.mul({c0:t,c1:r},o)}frobeniusMap(t,r){let{c0:n,c1:o}=t,{Fp:i}=this;return Object.freeze({c0:n,c1:r%2===0?o:i.neg(o)})}},S0=class{ORDER;BITS;BYTES;isLE;ZERO;ONE;Fp2;constructor(t){this.Fp2=t,this.ORDER=t.Fp.ORDER**$v,this.BITS=3*t.BITS,this.BYTES=3*t.BYTES,this.isLE=t.isLE,this.ZERO=this.create({c0:t.ZERO,c1:t.ZERO,c2:t.ZERO}),this.ONE=this.create({c0:t.ONE,c1:t.ZERO,c2:t.ZERO}),Object.freeze(this)}get FROBENIUS_COEFFICIENTS_1(){let t=Zd.get(this);if(t)return t[0];let{Fp2:r}=this,{Fp:n}=r,o=lg(r,r.NONRESIDUE,n.ORDER,6,2,3),i=[Object.freeze(o[0]),Object.freeze(o[1])];return Zd.set(this,i),i[0]}get FROBENIUS_COEFFICIENTS_2(){let t=Zd.get(this);return t?t[1]:(this.FROBENIUS_COEFFICIENTS_1,Zd.get(this)[1])}add({c0:t,c1:r,c2:n},{c0:o,c1:i,c2:s}){let{Fp2:a}=this;return Object.freeze({c0:a.add(t,o),c1:a.add(r,i),c2:a.add(n,s)})}sub({c0:t,c1:r,c2:n},{c0:o,c1:i,c2:s}){let{Fp2:a}=this;return Object.freeze({c0:a.sub(t,o),c1:a.sub(r,i),c2:a.sub(n,s)})}mul({c0:t,c1:r,c2:n},o){let{Fp2:i}=this;if(typeof o=="bigint")return Object.freeze({c0:i.mul(t,o),c1:i.mul(r,o),c2:i.mul(n,o)});let{c0:s,c1:a,c2:c}=o,d=i.mul(t,s),f=i.mul(r,a),u=i.mul(n,c);return Object.freeze({c0:i.add(d,i.mulByNonresidue(i.sub(i.mul(i.add(r,n),i.add(a,c)),i.add(f,u)))),c1:i.add(i.sub(i.mul(i.add(t,r),i.add(s,a)),i.add(d,f)),i.mulByNonresidue(u)),c2:i.sub(i.add(f,i.mul(i.add(t,n),i.add(s,c))),i.add(d,u))})}sqr({c0:t,c1:r,c2:n}){let{Fp2:o}=this,i=o.sqr(t),s=o.mul(o.mul(t,r),It),a=o.mul(o.mul(r,n),It),c=o.sqr(n);return Object.freeze({c0:o.add(o.mulByNonresidue(a),i),c1:o.add(o.mulByNonresidue(c),s),c2:o.sub(o.sub(o.add(o.add(s,o.sqr(o.add(o.sub(t,r),n))),a),i),c)})}addN(t,r){return this.add(t,r)}subN(t,r){return this.sub(t,r)}mulN(t,r){return this.mul(t,r)}sqrN(t){return this.sqr(t)}create(t){let{Fp2:r}=this,n=r.create(t.c0),o=r.create(t.c1),i=r.create(t.c2);return Object.freeze({c0:n,c1:o,c2:i})}isValid(t){if(!oi(t))throw new TypeError("invalid field element: expected object, got "+typeof t);let{c0:r,c1:n,c2:o}=t,{Fp2:i}=this;return i.isValid(r)&&i.isValid(n)&&i.isValid(o)}is0(t){if(!oi(t))return!1;let{c0:r,c1:n,c2:o}=t,{Fp2:i}=this;return i.is0(r)&&i.is0(n)&&i.is0(o)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}neg({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return Object.freeze({c0:o.neg(t),c1:o.neg(r),c2:o.neg(n)})}eql({c0:t,c1:r,c2:n},{c0:o,c1:i,c2:s}){let{Fp2:a}=this;return a.eql(t,o)&&a.eql(r,i)&&a.eql(n,s)}sqrt(t){return pr()}div(t,r){let{Fp2:n}=this,{Fp:o}=n;return this.mul(t,typeof r=="bigint"?o.inv(o.create(r)):this.inv(r))}pow(t,r){return Fd(this,t,r)}invertBatch(t){return mr(this,t,!0)}inv({c0:t,c1:r,c2:n}){let{Fp2:o}=this,i=o.sub(o.sqr(t),o.mulByNonresidue(o.mul(n,r))),s=o.sub(o.mulByNonresidue(o.sqr(n)),o.mul(t,r)),a=o.sub(o.sqr(r),o.mul(t,n)),c=o.inv(o.add(o.mulByNonresidue(o.add(o.mul(n,s),o.mul(r,a))),o.mul(t,i)));return Object.freeze({c0:o.mul(c,i),c1:o.mul(c,s),c2:o.mul(c,a)})}fromBytes(t){let{Fp2:r}=this;if(se(t),t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);let n=r.BYTES;return this.create({c0:r.fromBytes(t.subarray(0,n)),c1:r.fromBytes(t.subarray(n,n*2)),c2:r.fromBytes(t.subarray(2*n))})}toBytes({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return ke(o.toBytes(t),o.toBytes(r),o.toBytes(n))}cmov({c0:t,c1:r,c2:n},{c0:o,c1:i,c2:s},a){let{Fp2:c}=this;return this.create({c0:c.cmov(t,o,a),c1:c.cmov(r,i,a),c2:c.cmov(n,s,a)})}fromBigSix(t){let{Fp2:r}=this;if(!Array.isArray(t)||t.length!==6)throw new Error("invalid Fp6.fromBigSix");for(let o=0;o<6;o++)if(typeof t[o]!="bigint")throw new Error("invalid Fp6.fromBigSix");let n=t;return this.create({c0:r.fromBigTuple(n.slice(0,2)),c1:r.fromBigTuple(n.slice(2,4)),c2:r.fromBigTuple(n.slice(4,6))})}frobeniusMap(t,r){let{c0:n,c1:o,c2:i}=t;if(r%6===0)return Object.freeze({c0:n,c1:o,c2:i});let{Fp2:s}=this;return Object.freeze({c0:s.frobeniusMap(n,r),c1:s.mul(s.frobeniusMap(o,r),this.FROBENIUS_COEFFICIENTS_1[r%6]),c2:s.mul(s.frobeniusMap(i,r),this.FROBENIUS_COEFFICIENTS_2[r%6])})}mulByFp2({c0:t,c1:r,c2:n},o){let{Fp2:i}=this;return Object.freeze({c0:i.mul(t,o),c1:i.mul(r,o),c2:i.mul(n,o)})}mulByNonresidue({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return Object.freeze({c0:o.mulByNonresidue(n),c1:t,c2:r})}mul1({c0:t,c1:r,c2:n},o){let{Fp2:i}=this;return Object.freeze({c0:i.mulByNonresidue(i.mul(n,o)),c1:i.mul(t,o),c2:i.mul(r,o)})}mul01({c0:t,c1:r,c2:n},o,i){let{Fp2:s}=this,a=s.mul(t,o),c=s.mul(r,i);return Object.freeze({c0:s.add(s.mulByNonresidue(s.sub(s.mul(s.add(r,n),i),c)),a),c1:s.sub(s.sub(s.mul(s.add(o,i),s.add(t,r)),a),c),c2:s.add(s.sub(s.mul(s.add(t,n),o),a),c)})}},Zd=new WeakMap,E0=class{ORDER;BITS;BYTES;isLE;ZERO;ONE;Fp6;X_LEN;finalExponentiate;constructor(t,r){let{X_LEN:n,Fp12finalExponentiate:o}=r,{Fp2:i}=t,{Fp:s}=i;this.Fp6=t,this.ORDER=s.ORDER**Lv,this.BITS=2*t.BITS,this.BYTES=2*t.BYTES,this.isLE=t.isLE,this.ZERO=this.create({c0:t.ZERO,c1:t.ZERO}),this.ONE=this.create({c0:t.ONE,c1:t.ZERO}),this.X_LEN=n,this.finalExponentiate=a=>{let c=({c0:u,c1:l})=>Object.freeze({c0:u,c1:l}),d=({c0:u,c1:l,c2:p})=>Object.freeze({c0:c(u),c1:c(l),c2:c(p)}),f=o(a);return Object.freeze({c0:d(f.c0),c1:d(f.c1)})},Object.freeze(this)}get FROBENIUS_COEFFICIENTS(){let t=ug.get(this);if(t)return t;let{Fp2:r}=this.Fp6,{Fp:n}=r,o=Object.freeze(lg(r,r.NONRESIDUE,n.ORDER,12,1,6)[0]);return ug.set(this,o),o}create(t){let{Fp6:r}=this,n=r.create(t.c0),o=r.create(t.c1);return Object.freeze({c0:n,c1:o})}isValid(t){if(!oi(t))throw new TypeError("invalid field element: expected object, got "+typeof t);let{c0:r,c1:n}=t,{Fp6:o}=this;return o.isValid(r)&&o.isValid(n)}is0(t){if(!oi(t))return!1;let{c0:r,c1:n}=t,{Fp6:o}=this;return o.is0(r)&&o.is0(n)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}neg({c0:t,c1:r}){let{Fp6:n}=this;return Object.freeze({c0:n.neg(t),c1:n.neg(r)})}eql({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:i}=this;return i.eql(t,n)&&i.eql(r,o)}sqrt(t){return pr()}inv({c0:t,c1:r}){let{Fp6:n}=this,o=n.inv(n.sub(n.sqr(t),n.mulByNonresidue(n.sqr(r))));return Object.freeze({c0:n.mul(t,o),c1:n.neg(n.mul(r,o))})}div(t,r){let{Fp6:n}=this,{Fp2:o}=n,{Fp:i}=o;return this.mul(t,typeof r=="bigint"?i.inv(i.create(r)):this.inv(r))}pow(t,r){return Fd(this,t,r)}invertBatch(t){return mr(this,t,!0)}add({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:i}=this;return Object.freeze({c0:i.add(t,n),c1:i.add(r,o)})}sub({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:i}=this;return Object.freeze({c0:i.sub(t,n),c1:i.sub(r,o)})}mul({c0:t,c1:r},n){let{Fp6:o}=this;if(typeof n=="bigint")return Object.freeze({c0:o.mul(t,n),c1:o.mul(r,n)});let{c0:i,c1:s}=n,a=o.mul(t,i),c=o.mul(r,s);return Object.freeze({c0:o.add(a,o.mulByNonresidue(c)),c1:o.sub(o.mul(o.add(t,r),o.add(i,s)),o.add(a,c))})}sqr({c0:t,c1:r}){let{Fp6:n}=this,o=n.mul(t,r);return Object.freeze({c0:n.sub(n.sub(n.mul(n.add(n.mulByNonresidue(r),t),n.add(t,r)),o),n.mulByNonresidue(o)),c1:n.add(o,o)})}addN(t,r){return this.add(t,r)}subN(t,r){return this.sub(t,r)}mulN(t,r){return this.mul(t,r)}sqrN(t){return this.sqr(t)}fromBytes(t){let{Fp6:r}=this;if(se(t),t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);return this.create({c0:r.fromBytes(t.subarray(0,r.BYTES)),c1:r.fromBytes(t.subarray(r.BYTES))})}toBytes({c0:t,c1:r}){let{Fp6:n}=this;return ke(n.toBytes(t),n.toBytes(r))}cmov({c0:t,c1:r},{c0:n,c1:o},i){let{Fp6:s}=this;return this.create({c0:s.cmov(t,n,i),c1:s.cmov(r,o,i)})}fromBigTwelve(t){let{Fp6:r}=this;if(!Array.isArray(t)||t.length!==12)throw new Error("invalid Fp12.fromBigTwelve");for(let o=0;o<12;o++)if(typeof t[o]!="bigint")throw new Error("invalid Fp12.fromBigTwelve");let n=t;return this.create({c0:r.fromBigSix(n.slice(0,6)),c1:r.fromBigSix(n.slice(6,12))})}frobeniusMap(t,r){let n=r%12;if(n===0)return Object.freeze({c0:t.c0,c1:t.c1});if(n===6)return this.conjugate(t);let{Fp6:o}=this,{Fp2:i}=o,{c0:s,c1:a,c2:c}=o.frobeniusMap(t.c1,r),d=this.FROBENIUS_COEFFICIENTS[n];return Object.freeze({c0:o.frobeniusMap(t.c0,r),c1:Object.freeze({c0:i.mul(s,d),c1:i.mul(a,d),c2:i.mul(c,d)})})}mulByFp2({c0:t,c1:r},n){let{Fp6:o}=this;return Object.freeze({c0:o.mulByFp2(t,n),c1:o.mulByFp2(r,n)})}conjugate({c0:t,c1:r}){return Object.freeze({c0:t,c1:this.Fp6.neg(r)})}_cyclotomicSquare({c0:t,c1:r}){let{Fp6:n}=this,{Fp2:o}=n,{c0:i,c1:s,c2:a}=t,{c0:c,c1:d,c2:f}=r,{first:u,second:l}=o.Fp4Square(i,d),{first:p,second:m}=o.Fp4Square(c,a),{first:h,second:y}=o.Fp4Square(s,f),b=o.mulByNonresidue(y);return Object.freeze({c0:Object.freeze({c0:o.add(o.mul(o.sub(u,i),It),u),c1:o.add(o.mul(o.sub(p,s),It),p),c2:o.add(o.mul(o.sub(h,a),It),h)}),c1:Object.freeze({c0:o.add(o.mul(o.add(b,c),It),b),c1:o.add(o.mul(o.add(l,d),It),l),c2:o.add(o.mul(o.add(m,f),It),m)})})}_cyclotomicExp(t,r){if(Xn("cyclotomic exponent",r,x0,oo<<BigInt(this.X_LEN)),r===x0)return this.ONE;let n=t;for(let o=tr(r)-2;o>=0;o--)n=this._cyclotomicSquare(n),nb(r,o)&&(n=this.mul(n,t));return n}},ug=new WeakMap;function mg(e){if(Be(e,{ORDER:"bigint",X_LEN:"number",FP2_NONRESIDUE:"object",Fp2mulByB:"function",Fp12finalExponentiate:"function"},{NONRESIDUE:"bigint"}),_e(e.X_LEN,"X_LEN"),e.X_LEN<1)throw new Error("invalid X_LEN");let t=e.FP2_NONRESIDUE;if(!Array.isArray(t)||t.length!==2)throw new Error("invalid FP2_NONRESIDUE");if(typeof t[0]!="bigint"||typeof t[1]!="bigint")throw new Error("invalid FP2_NONRESIDUE");let r=Nr(e.ORDER),n=new v0(r,e),o=new S0(n),i=new E0(o,e);return{Fp:r,Fp2:n,Fp6:o,Fp12:i}}var B0=BigInt(0),hg=BigInt(1),Yd=BigInt(2),Ji=BigInt(3),Qi=BigInt(4),ii=BigInt("0xd201000000010000"),Dv=tr(ii),tc={p:BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),n:BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"),h:BigInt("0x396c8c005555e1568c00aaab0000aaab"),a:B0,b:Qi,Gx:BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),Gy:BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1")},P0=Nr(tc.n,{modFromBytes:!0});function qv(e,t,{g2:r,g3:n,g4:o,g5:i}){return{c0:{c0:e,c1:o,c2:n},c1:{c0:r,c1:t,c2:i}}}function jv({c0:e,c1:t}){return{g2:t.c0,g3:e.c2,g4:e.c1,g5:t.c2}}function Gv({g2:e,g3:t,g4:r,g5:n}){let{first:o,second:i}=ee.Fp4Square(r,n),{first:s,second:a}=ee.Fp4Square(e,t),c=ee.add(e,e),d=ee.add(t,t),f=ee.add(r,r),u=ee.add(n,n);return{g2:ee.add(ee.mul(ee.mulByNonresidue(i),Ji),c),g3:ee.sub(ee.mul(o,Ji),d),g4:ee.sub(ee.mul(s,Ji),f),g5:ee.add(ee.mul(a,Ji),u)}}function Vv({g2:e,g3:t,g4:r,g5:n}){return ee.is0(e)?{num:ee.mul(ee.mul(r,n),Yd),den:t}:{num:ee.add(ee.sub(ee.mul(ee.sqr(r),Ji),ee.mul(t,Yd)),ee.mulByNonresidue(ee.sqr(n))),den:ee.mul(e,Qi)}}function Kv(e,{g2:t,g3:r,g4:n,g5:o}){let i=ee.mul(r,n),s=ee.add(ee.sub(ee.mul(ee.sub(ee.sqr(e),i),Yd),i),ee.mul(t,o));return ee.add(ee.mulByNonresidue(s),ee.ONE)}function Wv(e,t){let r=[],n=jv(e);for(let c of t){for(let d=0;d<c;d++)n=Gv(n);r.push(n)}let o=r.map(({g2:c,g3:d})=>ee.is0(c)&&ee.is0(d)),i=r.map(Vv),s=ee.invertBatch(i.map(({den:c})=>c)),a=r.map((c,d)=>{if(o[d])return ye.ONE;let f=ee.mul(i[d].num,s[d]);return qv(Kv(f,c),f,c)});return{result:ye.mul(ye.mul(a[0],a[1]),a[2]),last:a[2]}}function Zv(e){let{result:t,last:r}=Wv(e,[16,32,9]),n=t,o=r;for(let i=0;i<3;i++)o=ye._cyclotomicSquare(o);n=ye.mul(n,o);for(let i=0;i<2;i++)o=ye._cyclotomicSquare(o);return n=ye.mul(n,o),o=ye._cyclotomicSquare(o),ye.mul(n,o)}var{Fp:Ie,Fp2:ee,Fp6:Yv,Fp12:ye}=mg({ORDER:tc.p,X_LEN:Dv,FP2_NONRESIDUE:[hg,hg],Fp2mulByB:({c0:e,c1:t})=>{let r=Ie.mul(e,Qi),n=Ie.mul(t,Qi);return{c0:Ie.sub(r,n),c1:Ie.add(r,n)}},Fp12finalExponentiate:e=>{let t=m=>ye.conjugate(Zv(m)),r=ye.div(ye.frobeniusMap(e,6),e),n=ye.mul(ye.frobeniusMap(r,2),r),o=t(n),i=ye.mul(ye.conjugate(ye._cyclotomicSquare(n)),o),s=t(i),a=t(s),c=ye.mul(t(a),ye._cyclotomicSquare(o)),d=t(c),f=ye.frobeniusMap(ye.mul(o,a),2),u=ye.frobeniusMap(ye.mul(s,n),3),l=ye.frobeniusMap(ye.mul(c,ye.conjugate(n)),1),p=ye.mul(ye.mul(d,ye.conjugate(i)),n);return ye.mul(ye.mul(ye.mul(f,u),l),p)}}),yg,Tg=()=>yg||(yg=pg(Ie,ee,ee.div(ee.ONE,ee.NONRESIDUE))),I0=(e,t)=>{let r=Tg().G2psi;return I0=r,r(e,t)},Ig=(e,t)=>{let r=Tg().G2psi2;return Ig=r,r(e,t)},_0=Object.freeze({DST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",encodeDST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",p:Ie.ORDER,m:2,k:128,expand:"xmd",hash:ur}),kg={p:ee.ORDER,n:tc.n,h:BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),a:ee.ZERO,b:ee.fromBigTuple([Qi,Qi]),Gx:ee.fromBigTuple([BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")]),Gy:ee.fromBigTuple([BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")])},bg=(e,t)=>{for(let r of e)if(r!==B0)return!!(r*Yd/t);return!1},gg={encode({c0:e,c1:t}){let{BYTES:r}=Ie;return ke(Yn(t,r),Yn(e,r))},decode(e){let{BYTES:t}=Ie;return ee.create({c0:k0(e.subarray(t)),c1:k0(e.subarray(0,t))})}},wg=Ie;function k0(e){return Ie.fromBytes(e)}var Bg=(e,t,r,n,o,i)=>{let s=t,a=n,c=o,d=s.BYTES;return f=>({encode(u,l=!0){if(!l&&!f)throw new Error("invalid signature: expected compressed encoding");let p=u.is0(),{x:m,y:h}=u.toAffine(),y=l?a(m):ke(a(m),a(h)),b;return l&&!p&&(b=bg(i(h),wg.ORDER)),Jv(y,{compressed:l,infinity:p,sort:b})},decode(u){let l=f?se(u,void 0,"point"):se(u,d,"signature"),{compressed:p,infinity:m,sort:h,value:y}=Xv(l);if(!f&&!p)throw new Error("invalid signature: expected compressed encoding");let b=p?d:2*d;if(y.length!==b)throw new Error(`invalid ${e} point: expected ${b} bytes`);if(m){for(let w of y)if(w)throw new Error(`invalid ${e} point: non-canonical zero`);return{x:s.ZERO,y:s.ZERO}}let x=c(p?y:y.subarray(0,d)),g;if(p){if(g=s.sqrt(s.add(s.pow(x,Ji),r)),!g)throw new Error(`invalid ${e} point: compressed`);bg(i(g),wg.ORDER)!==h&&(g=s.neg(g))}else g=c(y.subarray(d));if(!p&&s.is0(x)&&s.is0(g))throw new Error(`invalid ${e} point: uncompressed`);return{x,y:g}}})};function Pg({compressed:e,infinity:t,sort:r}){if(!e&&!t&&r||!e&&t&&r||e&&t&&r)throw new Error("invalid encoding flag")}function Xv(e){e=Ur(e);let t=e[0]&224,r=!!(t>>7&1),n=!!(t>>6&1),o=!!(t>>5&1);return Pg({compressed:r,infinity:n,sort:o}),e[0]&=31,{compressed:r,infinity:n,sort:o,value:e}}function Jv(e,t){if(e[0]&224)throw new Error("setMask: non-empty mask");return Pg({compressed:!!t.compressed,infinity:!!t.infinity,sort:!!t.sort}),t.compressed&&(e[0]|=128),t.infinity&&(e[0]|=64),t.sort&&(e[0]|=32),e}var xg=Bg("G1",Ie,Ie.create(tc.b),e=>Yn(e,Ie.BYTES),k0,e=>[e]),Xd={point:xg(!0),sig:xg(!1)},A0=e=>(e.assertValidity(),Xd.sig.encode(e));function vg(e){let r=kt.G1.Point.fromAffine(Xd.sig.decode(e));return r.assertValidity(),r}var Sg=Bg("G2",ee,kg.b,gg.encode,gg.decode,e=>[e.c1,e.c0]),Jd={point:Sg(!0),sig:Sg(!1)},T0=e=>(e.assertValidity(),Jd.sig.encode(e));function Eg(e){let r=kt.G2.Point.fromAffine(Jd.sig.decode(e));return r.assertValidity(),r}var Qv={ShortSignature:{fromBytes(e){return vg(se(e))},fromHex(e){return vg(un(e))},toBytes(e){return A0(e)},toRawBytes(e){return A0(e)},toHex(e){return Zn(A0(e))}},LongSignature:{fromBytes(e){return Eg(se(e))},fromHex(e){return Eg(un(e))},toBytes(e){return T0(e)},toRawBytes(e){return T0(e)},toHex(e){return Zn(T0(e))}}},eS={Fp:Ie,Fp2:ee,Fp6:Yv,Fp12:ye,Fr:P0},tS=Ga(tc,{allowInfinityPoint:!0,Fn:P0,fromBytes:Xd.point.decode,toBytes:(e,t,r)=>Xd.point.encode(t,r),isTorsionFree:(e,t)=>{let r=BigInt("0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe"),n=new e(Ie.mul(t.X,r),t.Y,t.Z);return t.multiplyUnsafe(ii).negate().multiplyUnsafe(ii).equals(n)},clearCofactor:(e,t)=>t.multiplyUnsafe(ii).add(t)}),rS=Ga(kg,{Fp:ee,allowInfinityPoint:!0,Fn:P0,fromBytes:Jd.point.decode,toBytes:(e,t,r)=>Jd.point.encode(t,r),isTorsionFree:(e,t)=>t.multiplyUnsafe(ii).negate().equals(I0(e,t)),clearCofactor:(e,t)=>{let r=ii,n=t.multiplyUnsafe(r).negate(),o=I0(e,t),i=t.double();return i=Ig(e,i),i=i.subtract(o),o=n.add(o),o=o.multiplyUnsafe(r).negate(),i=i.add(o),i=i.subtract(n),i.subtract(t)}}),nS={mapToG1:dS,mapToG2:fS,hasherOpts:_0,hasherOptsG1:{..._0,m:1,DST:"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_",encodeDST:"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_"},hasherOptsG2:{..._0}},oS={ateLoopSize:ii,xNegative:!0,twistType:"multiplicative",randomBytes:lr},kt=dg(eS,tS,rS,oS,nS,Qv),iS=Xp(ee,[[["0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6"],["0x0","0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d"],["0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1","0x0"]],[["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63"],["0xc","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f"],["0x1","0x0"]],[["0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706","0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706"],["0x0","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f"],["0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10","0x0"]],[["0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb"],["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3"],["0x12","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99"],["0x1","0x0"]]].map(e=>e.map(t=>ee.fromBigTuple(t.map(BigInt))))),sS=Xp(Ie,[["0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7","0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb","0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0","0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861","0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9","0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983","0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84","0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e","0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317","0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e","0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b","0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229"],["0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c","0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff","0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19","0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8","0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e","0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5","0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a","0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e","0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641","0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"],["0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33","0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696","0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6","0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb","0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb","0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0","0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2","0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29","0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587","0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30","0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132","0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e","0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8","0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133","0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b","0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604"],["0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1","0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d","0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2","0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416","0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d","0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac","0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c","0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9","0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a","0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55","0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8","0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092","0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc","0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7","0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),_g,Ag,aS=()=>_g||(_g=Qp(Ie,{A:Ie.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),B:Ie.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),Z:Ie.create(BigInt(11))})),cS=()=>Ag||(Ag=Qp(ee,{A:ee.create({c0:Ie.create(B0),c1:Ie.create(BigInt(240))}),B:ee.create({c0:Ie.create(BigInt(1012)),c1:Ie.create(BigInt(1012))}),Z:ee.create({c0:Ie.create(BigInt(-2)),c1:Ie.create(BigInt(-1))})}));function dS(e){let{x:t,y:r}=aS()(Ie.create(e[0]));return sS(t,r)}function fS(e){let{x:t,y:r}=cS()(ee.fromBigTuple(e));return iS(t,r)}function io(e){let t=G(e,48),r=kt.G1.Point.fromBytes(t);if(r.is0()||!r.isTorsionFree()||Y(r.toBytes(!0))!==e)throw new TypeError("invalid buyer key");return t}function uS(e,t={}){if(ae(e,["version","refund","network","contract","route","asset","file_id","terms_hash","price","nonce","buyer_key","recovery","expires_at"]),e.version!==2||e.route!=="near-usdc"&&e.route!=="base-usdc")throw new TypeError("invalid purchase version/route");if(e.route==="near-usdc"){if(Gn(e.network),be(e.asset),(t.nearUsdc!==void 0||e.network==="near:mainnet")&&e.asset!==(t.nearUsdc??Ki))throw new TypeError("invalid NEAR asset")}else{if(e.network!=="eip155:8453"||e.asset!==(t.baseUsdc??u0))throw new TypeError("invalid Base network/asset");G(e.asset,20)}be(e.contract);let r=_t(e.price,128);if(r===0n)throw new RangeError("price must be positive");return Et(je(2,1),Tt(e.refund),At(e.network),At(e.contract),je(e.route==="near-usdc"?0:1,1),At(e.asset),G(e.file_id,32),G(e.terms_hash,32),je(r,16),G(e.nonce,32),io(e.buyer_key),Tt(e.recovery),je(_t(e.expires_at,64),8))}var bn=(e,t)=>Pd("annon/purchase/v2",uS(e,t)),Qd=e=>Y(Pe(Et(et.encode("annon/base-payment/v2"),je(0,1),G(e,32))));function zr(e,t){let r=bn(e,t),n=JSON.stringify({annon:2,refund:ne(e.refund),purchase:{network:e.network,contract:e.contract,route:e.route,asset:e.asset,file_id:e.file_id,terms_hash:e.terms_hash,price:e.price,nonce:e.nonce,buyer_key:e.buyer_key,recovery:ne(e.recovery),expires_at:e.expires_at,purchase_id:r}});if(et.encode(n).length>1024)throw new RangeError("purchase message exceeds 1024 UTF-8 bytes");return n}function lS(e){if(typeof e!="string")throw new TypeError("expected message string");let t=e.slice(0,160),r=/^\{"annon":2,"refund":(\{"kind":"(?:evm|solana|near)","id":"[a-zA-Z0-9._-]+"\}),/.exec(t);if(!r)throw new TypeError("invalid refund prefix");let n=r[1],o=ne(JSON.parse(n));if(Q(o)!==n||et.encode(r[0]).length>160)throw new TypeError("noncanonical refund prefix");return o}function es(e,t){if(typeof e!="string"||e.length>1024||et.encode(e).length>1024)throw new RangeError("purchase message exceeds 1024 UTF-8 bytes");let r=lS(e),n=JSON.parse(e);if(ae(n,["annon","refund","purchase"]),n.annon!==2)throw new TypeError("invalid annon version");let o=n.purchase;ae(o,["network","contract","route","asset","file_id","terms_hash","price","nonce","buyer_key","recovery","expires_at","purchase_id"]);let i={version:2,refund:r,network:o.network,contract:o.contract,route:o.route,asset:o.asset,file_id:o.file_id,terms_hash:o.terms_hash,price:o.price,nonce:o.nonce,buyer_key:o.buyer_key,recovery:ne(o.recovery),expires_at:o.expires_at};if(zr(i,t)!==e)throw new TypeError("noncanonical purchase message or incorrect purchase_id");return i}function Rg(e){return be(e.contract),G(e.purchase_id,32),G(e.file_id,32),io(e.fresh_key),G(e.nonce,32),["Annon: open a purchased file again",`contract: ${e.contract}`,`purchase: ${e.purchase_id}`,`file: ${e.file_id}`,`recovery: ${Ke(e.recovery)}`,`new key: ${e.fresh_key}`,`nonce: ${e.nonce}`,`valid until: ${Vn(e.deadline)}`].join(`
47
+ `)}var ts=class extends S{code;constructor(t,r=t){super(t,r),this.code=t,this.name="NearError"}},rc=class extends ts{constructor(t="NEAR RPC rate limited (429)"){super("near_rpc_rate_limited",t),this.name="NearRpcRateLimited"}},si=(e,t)=>{throw new ts(e,t)},ze=e=>si("transport",`malformed RPC answer: ${e}`),pS=e=>btoa(String.fromCharCode(...new TextEncoder().encode(e))),Og=e=>new TextDecoder().decode(Uint8Array.from(atob(e),t=>t.charCodeAt(0))),O0=2e4,mS=0;async function hS(e,t,r){let n=`annon-${++mS}`,o,i,s=new AbortController,a=setTimeout(()=>s.abort(new Error("timed out")),O0);try{i=await fetch(e,{credentials:"omit",method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:n,method:t,params:r}),signal:s.signal});let c=()=>{if(i.status===429)throw new rc("NEAR RPC HTTP 429: rate limited (429)");return si("transport",`NEAR RPC HTTP ${i.status}`)};try{o=await i.json()}catch(d){if(!i.ok)return c();throw d}if(i.status===429||!i.ok&&(!o||typeof o!="object"||Array.isArray(o)||o.jsonrpc!=="2.0"&&o.id!==n||!("result"in o)&&!("error"in o)))return c()}catch(c){if(c instanceof ts)throw c;return si("transport",`NEAR RPC unreachable: ${c.message}`)}finally{clearTimeout(a)}if(o?.error?.code===-429)throw new rc;return o?.id!==n?ze("a reply to another request"):o}async function ef(e,t,r){let n=await hS(e,t,r);if(n.error){let o=JSON.stringify(n.error.cause?.info??n.error.data??n.error.message);["CONTRACT_EXECUTION_ERROR","UNKNOWN_ACCESS_KEY","UNKNOWN_ACCOUNT"].includes(n.error.cause?.name??"")&&si("refused",o),si("transport",`NEAR RPC error: ${o}`)}return typeof n?.result!="object"||n.result===null?ze("no result"):n.result}async function $r(e,t,r,n,o){let i=await ef(e,"query",{request_type:"call_function",...o===void 0?{finality:"final"}:{block_id:o},account_id:t,method_name:r,args_base64:pS(JSON.stringify(n))});typeof i.error=="string"&&si("refused",i.error);let s=i.result;if(!Array.isArray(s)||!s.every(a=>Number.isInteger(a)&&a>=0&&a<=255))return ze("view bytes");try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(s)))}catch{return ze("view bytes are not JSON")}}var nc=(e,t)=>typeof e=="string"&&new RegExp(`^0x[0-9a-f]{${2*t}}$`).test(e),R0=e=>typeof e=="string"&&/^(?=.{2,64}$)(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a-z\d]+$/.test(e),yS=["illegal_content","court_order","rights_holder_notice"];async function ai(e,t,r,n){let o=await $r(e,t,"get_file",{file_id:r},n);if(o===null)return null;try{let s=tt(o.terms,{nearUsdc:o.terms.near.token,...o.terms.base?{baseUsdc:o.terms.base.usdc}:{}});if(o.terms_hash!==s)throw new Error;if(o.purchase_storage_balance!==void 0&&(typeof o.purchase_storage_balance!="string"||!/^(0|[1-9][0-9]*)$/.test(o.purchase_storage_balance)||BigInt(o.purchase_storage_balance)>=2n**128n)||o.terms.contract!==t||o.terms.file_id!==r||!(o.header_hash===null||nc(o.header_hash,32))||!(o.sales_stopped_at===null||Number.isSafeInteger(o.sales_stopped_at)&&o.sales_stopped_at>0)||!(o.taken_down===null||typeof o.taken_down=="string"&&yS.includes(o.taken_down)))throw new Error}catch{return ze("get_file")}let i=o.terms;return{purchaseStorageBalance:BigInt(o.purchase_storage_balance??"0"),terms:i,termsHash:o.terms_hash,seller:ne(i.seller),price:BigInt(i.base?.price??i.near.price),payTo:i.base?.pay_to??"",cipherHash:i.cipher_hash,moderator:i.moderator,headerHash:o.header_hash,salesStoppedAt:o.sales_stopped_at,takenDown:o.taken_down}}async function so(e,t,r){let n=await $r(e,t,"get_purchase",{purchase_id:r});if(n===null)return null;try{if(n.purchase_id!==r||!nc(n.file_id,32)||!nc(n.terms_hash,32)||!Number.isSafeInteger(n.grants)||n.grants<1||n.grants>4294967295||!Number.isSafeInteger(n.accepted_at)||n.accepted_at<0||!["near-usdc","base-usdc"].includes(n.route)||(n.route==="base-usdc"?n.delivery!==null:!Number.isSafeInteger(n.delivery)||n.delivery<0))throw new Error;io(n.buyer_key),ne(n.recovery)}catch{return ze("get_purchase")}return n}async function C0(e,t,r,n=0){if(!Number.isInteger(n)||n<0||n>4294967295)throw new TypeError("invalid grant");let o=await $r(e,t,"get_grant",{purchase_id:r,grant:n});if(o===null)return null;try{if(o.purchase_id!==r||o.grant!==n)throw new Error;io(o.buyer_key)}catch{return ze("get_grant")}return o}async function Cg(e,t,r,n=0,o=50){if(!Number.isSafeInteger(n)||n<0||n>4294967295||!Number.isSafeInteger(o)||o<1||o>100)throw new TypeError("invalid page");let i=await $r(e,t,"purchases_of",{recovery:ne(r),from:n,limit:o});return!Array.isArray(i)||i.length>o||!i.every(s=>nc(s,32))?ze("purchases_of"):i}async function ao(e,t){let r=await $r(e,t,"get_config",{});return!R0(r?.mpc)||!Number.isSafeInteger(r?.ckd_domain)||!Number.isSafeInteger(r?.foreign_tx_domain)||!nc(r?.usdc,20)||!["near:mainnet","near:testnet","near:sandbox"].includes(r?.network)||!R0(r?.near_usdc)||!R0(r?.intents)||r?.ckd_domain<0||r?.foreign_tx_domain<0?ze("get_config"):{mpc:r?.mpc,ckdDomain:r?.ckd_domain,foreignTxDomain:r?.foreign_tx_domain,usdc:r?.usdc,network:r?.network,nearUsdc:r?.near_usdc,intents:r?.intents}}var bS=new Set(["register","unlock","reopen","reopen_seller","claim_key"]),gS=e=>typeof e=="object"&&e!==null&&("SuccessValue"in e||"SuccessReceiptId"in e),tf=e=>e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(tf).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${tf(e[t])}`).join(",")}}`;function ci(e,t,r){let n=e,o=n?.transaction;if(r&&(o?.hash!==r.txHash||o?.signer_id!==r.signer))return ze("an outcome for another transaction");o?.receiver_id!==t&&si("transport","the transaction was not sent to the Annon contract");let i=Array.isArray(o?.actions)?o.actions:[],s=i[0]?.FunctionCall?.method_name;if(i.length!==1||typeof s!="string")return ze("not a single function call");if(r?.method!==void 0&&s!==r.method)return ze("an outcome of another method");if(r?.deposit!==void 0&&i[0]?.FunctionCall?.deposit!==r.deposit)return ze("an outcome with another deposit");if(r?.args!==void 0){let p;try{p=JSON.parse(Og(String(i[0]?.FunctionCall?.args)))}catch{return ze("call arguments are not JSON")}let m=JSON.parse(JSON.stringify(r.args)??"null");if(s==="register"&&p&&typeof p=="object"&&"args"in p&&!Object.hasOwn(m.args??{},"file_budget")){let h=p.args;if(Object.hasOwn(h,"file_budget")){if(typeof h.file_budget!="string"||!/^[1-9][0-9]*$/.test(h.file_budget)||BigInt(h.file_budget)>=2n**128n)return ze("invalid registration budget");delete h.file_budget}}if(tf(p)!==tf(m))return ze("an outcome of another call")}let a=[];for(let p of Array.isArray(n.receipts_outcome)?n.receipts_outcome:[])if(!(p?.outcome?.executor_id!==t||!gS(p.outcome.status))){for(let m of Array.isArray(p.outcome.logs)?p.outcome.logs:[])if(!(typeof m!="string"||!m.startsWith("EVENT_JSON:")))try{let h=JSON.parse(m.slice(11));h.standard==="annon"&&h.version==="2.0.0"&&typeof h.event=="string"&&a.push({event:h.event,data:h.data?.[0]??{}})}catch{}}let c=n.status;if(c==="NotStarted"||c==="Started")return{state:"pending",method:s,events:a};if(typeof c!="object"||c===null)return ze("status");let d=bS.has(s);if("Failure"in c){let p=wS(c.Failure);return d?{state:"not_released",method:s,reason:p,events:a}:{state:"refused",method:s,reason:p,events:a}}if(typeof c.SuccessValue!="string")return ze("status");let f=null;if(c.SuccessValue!=="")try{f=JSON.parse(Og(c.SuccessValue))}catch{return ze("return value is not JSON")}if(!d)return{state:"done",method:s,value:f,events:a};let u=f;if(u&&typeof u.big_y=="string"&&typeof u.big_c=="string")return{state:"released",method:s,answer:f,events:a};let l=u&&typeof u.error=="string"?u.error:"no key in the result";return{state:"not_released",method:s,reason:l,events:a}}function wS(e){let t=e?.ActionError?.kind?.FunctionCallError?.ExecutionError;return typeof t=="string"?t.replace(/^Smart contract panicked: /,""):JSON.stringify(e)}async function Ug(e,t,r,n,o="FINAL",i){let s=await ef(e,"EXPERIMENTAL_tx_status",{tx_hash:t,sender_account_id:r,wait_until:o}),a=ci(s,n,{txHash:t,signer:r,...i});if(i?.notBefore!==void 0){let c=s.transaction_outcome?.block_hash;if(!Number.isSafeInteger(i.notBefore)||i.notBefore<0||typeof c!="string"||!c)return ze("missing transaction inclusion checkpoint");let f=(await ef(e,"block",{block_id:c})).header?.timestamp_nanosec;if(typeof f!="string"||!/^(0|[1-9][0-9]*)$/.test(f))return ze("transaction inclusion time");if(BigInt(f)<BigInt(i.notBefore)*1000000000n)return ze("a transaction before the current attempt")}return a}async function Ng(e,t,r){return(await ef(e,"query",{request_type:"view_access_key",finality:"final",account_id:t,public_key:r})).permission==="FullAccess"}async function U0(e,t,r){let n=await $r(e,t,"file_storage_balance",{file_id:r}),o=i=>typeof i=="string"&&/^(0|[1-9][0-9]*)$/.test(i)&&BigInt(i)<2n**128n;return!n||!o(n.available)||!o(n.admission_requirement)||BigInt(n.admission_requirement)===0n?ze("file_storage_balance"):{available:BigInt(n.available),admissionRequirement:BigInt(n.admission_requirement)}}function Fg(e){return typeof e=="string"&&/prepaid|storage balance|storage[_ ]deposit/i.test(e)}function xS(e){if(e.nonce.length!==32)throw new TypeError("NEP-413 nonce must be 32 bytes");return ur(Et(je(2147484061,4),At(e.message),e.nonce,At(e.recipient),e.callbackUrl===void 0?je(0,1):Et(je(1,1),At(e.callbackUrl))))}async function rf(e,t,r,n){be(e),be(r.contractId);let o={...r.callbackUrl===void 0?{}:{callbackUrl:r.callbackUrl},message:t,recipient:r.contractId,nonce:crypto.getRandomValues(new Uint8Array(32))},i=await n({...o,nonce:o.nonce.slice()});await oc(e,o,i,r.nearRpc)}async function oc(e,t,r,n){let o=xS(t);if(!r||r.accountId!==e||!r.publicKey.startsWith("ed25519:"))throw new S("invalid_signature","NEP-413 proof belongs to another account or key type");let i=Ct.decode(r.publicKey.slice(8)),s=wd.decode(r.signature);if(i.length!==32||s.length!==64||!jd.verify(s,o,i,{zip215:!1}))throw new S("invalid_signature","invalid NEP-413 recovery signature");if(!await Ng(n,e,r.publicKey))throw new S("invalid_signature","NEP-413 recovery requires a full-access key")}function nf(e){ae(e,["v","uploadId","network","contract","fileId","termsHash","seller","cipherHash","byteSize","plaintextSize","headerSize","metadataHash","hostOrigin","issuedAt","expiresAt","signature"]);let t=e;if(t.v!==1||!/^[0-9a-f]{64}$/.test(t.uploadId)||typeof t.signature!="string"||!/^[A-Za-z0-9_-]{86}$/.test(t.signature))throw new TypeError("Invalid hosting reservation.");for(let n of["fileId","termsHash","cipherHash","metadataHash"])G(t[n],32);for(let n of["byteSize","plaintextSize","headerSize","issuedAt","expiresAt"])if(!Number.isSafeInteger(t[n])||t[n]<0)throw new TypeError("Invalid hosting reservation.");let r=new URL(t.hostOrigin);if(r.protocol!=="https:"||r.origin!==t.hostOrigin||t.byteSize<1||t.byteSize>50086016||t.plaintextSize>5e7||t.headerSize<1||t.headerSize>65536||t.byteSize<=t.headerSize||t.expiresAt!==t.issuedAt+600)throw new TypeError("Invalid hosting reservation.");return Ke(t.seller),t}var co=e=>["Annon: reserve encrypted file hosting",`network: ${e.network}`,`contract: ${e.contract}`,`seller: ${Ke(e.seller)}`,`file: ${e.fileId}`,`cipher: ${e.cipherHash}`,`terms: ${e.termsHash}`,`bytes: ${e.byteSize}`,`plaintext bytes: ${e.plaintextSize}`,`header bytes: ${e.headerSize}`,`host: ${e.hostOrigin}`,`metadata: ${e.metadataHash}`,`nonce: ${e.nonce}`,`expires: ${e.expiresAt}`].join(`
48
+ `),of=new TextEncoder;function di(e){let t=new URL(e);if(t.protocol!=="https:"||t.origin!==e||t.username||t.password)throw new S("bad_request","Invalid upload origin.");return e}function sf(e){ae(e,["filename","title","description"]);let t={};for(let[r,n]of[["filename",255],["title",120],["description",500]]){let o=e[r];if(typeof o!="string")throw new S("bad_request","Invalid upload metadata.");let i=o.normalize("NFC");if(/[\p{Cc}\p{Cs}\p{Cf}\p{Zl}\p{Zp}]/u.test(i)||of.encode(i).length>n||r!=="description"&&!i)throw new S("bad_request","Invalid upload metadata.");t[r]=i}if(/[\\/]/.test(t.filename)||t.filename==="."||t.filename==="..")throw new S("bad_request","Invalid upload filename.");return t}async function N0(e){let t=sf(e);return Y(await Oe(of.encode(JSON.stringify([t.filename,t.title,t.description]))))}function sc(e){ae(e,["network","contract","seller","fileId","cipherHash","termsHash","byteSize","plaintextSize","headerSize","hostOrigin","metadataHash","nonce","expiresAt"]);let t=e;Gn(t.network),be(t.contract),di(t.hostOrigin);let r=ne(t.seller);if(r.kind!==t.seller.kind||r.id!==t.seller.id)throw new S("bad_request","Noncanonical seller.");for(let n of["fileId","cipherHash","termsHash","metadataHash","nonce"])G(t[n],32);for(let n of["byteSize","plaintextSize","headerSize","expiresAt"])if(!Number.isSafeInteger(t[n])||t[n]<0)throw new S("bad_request","Invalid upload size or time.");if(t.byteSize<=t.headerSize||t.headerSize<1||t.headerSize>65536||t.plaintextSize>5e7||t.byteSize>50086016)throw new S("bad_request","Invalid upload size.");return{...structuredClone(t),seller:r}}function F0(e){if(!e||typeof e!="object")throw new S("bad_request","Invalid upload authorization.");if("kind"in e&&e.kind==="near"){ae(e,["kind","accountId","publicKey","signature"]);let t=e;if(typeof t.accountId!="string"||typeof t.publicKey!="string"||typeof t.signature!="string")throw new S("bad_request","Invalid upload authorization.")}else{if(ae(e,["kind","sig"]),e.kind!=="evm"&&e.kind!=="solana")throw new S("bad_request","Invalid upload authorization.");G(e.sig,e.kind==="evm"?65:64)}return structuredClone(e)}function M0(e){ae(e,["intent","terms","manifest","metadata","auth"]);let t=sc(e.intent);ae(e.manifest,["version","chunkLog2","metaLen","previewLen","n","keyCommitments","chunkHashes"]);let r=e.manifest;if(![r.chunkLog2,r.metaLen,r.previewLen,r.n].every(Number.isSafeInteger)||r.version!==2||r.chunkLog2<16||r.chunkLog2>24||r.metaLen<256||r.metaLen>4096||r.metaLen%256!==0||r.previewLen<0||r.previewLen>no(t.plaintextSize)||r.n<2||r.n>1024||r.n!==ro(t.plaintextSize,r.previewLen,r.chunkLog2)||!Array.isArray(r.keyCommitments)||r.keyCommitments.length!==(r.previewLen>0?2:1)||!Array.isArray(r.chunkHashes)||r.chunkHashes.length!==r.n)throw new S("bad_request","Invalid upload manifest.");for(let n of[...r.keyCommitments,...r.chunkHashes])G(n,32);if(t.headerSize!==206+of.encode(t.contract).length+32*(r.keyCommitments.length+r.n)||t.byteSize-t.headerSize!==t.plaintextSize+r.metaLen+16*r.n)throw new S("bad_request","Invalid upload framing.");return{intent:t,terms:structuredClone(e.terms),manifest:structuredClone(r),metadata:sf(e.metadata),auth:F0(e.auth)}}async function Hg(e,t){let r=sc(e.intent),n=F0(e.auth);if(r.network!==t.network||r.contract!==t.contract||r.hostOrigin!==t.hostOrigin||r.expiresAt<=t.now||r.expiresAt>t.now+(t.authSeconds??600)||n.kind!==r.seller.kind)throw new S("bad_request","Invalid upload authorization.");if(n.kind==="near")await oc(r.seller.id,{message:co(r),recipient:r.hostOrigin,nonce:G(r.nonce,32)},n,t.nearRpc);else if(!lt(r.seller,co(r),n))throw new S("bad_request","Invalid upload signature.")}function vS(e){let t=Ny.encode(of.encode(JSON.stringify({intent:sc(e.intent),auth:F0(e.auth)})));if(t.length>8192)throw new S("bad_request","Upload authorization is too large.");return t}var rs=(e,t)=>{let r=Ko({code:e,retryAfterSeconds:t});return{ok:!1,error:Object.assign(new S(e),r.retryAfterSeconds===void 0?{}:{retryAfterSeconds:r.retryAfterSeconds})}};function zg(e,t,r){ae(e,["uploadId","state","expiresAt","bodyUrl","headerUrl"]);let n=e;if(!/^[a-f0-9]{64}$/.test(n.uploadId)||r!==void 0&&n.uploadId!==r||n.state!=="receiving"||!Number.isSafeInteger(n.expiresAt)||n.expiresAt<0||n.bodyUrl!==`${t}/v1/uploads/${n.uploadId}/body`||n.headerUrl!==`${t}/v1/uploads/${n.uploadId}/header`)throw new S("bad_request","Invalid upload response.");return n}function $g(e,t,r){ae(e,["uploadId","state","reservation"]);let n=e,o=nf(n.reservation);if(n.uploadId!==t||n.state!=="reserved"||o.uploadId!==t||Q(o.seller)!==Q(r.seller))throw new S("bad_request","Invalid upload response.");for(let i of["network","contract","fileId","termsHash","cipherHash","byteSize","plaintextSize","headerSize","metadataHash","hostOrigin"])if(o[i]!==r[i])throw new S("bad_request","Invalid upload response.");return{...n,reservation:o}}function Lg(e,t){ae(e,["fileId","url","header","expiresAt"]);let r=e,n=`${t.hostOrigin}/f/${t.fileId.slice(2)}`;if(r.fileId!==t.fileId||r.url!==n||r.header!==`${n}/header`||r.expiresAt!==null&&(!Number.isSafeInteger(r.expiresAt)||r.expiresAt<0))throw new S("bad_request","Invalid upload response.");return r}function Dg(e){if(e===null)return null;if(ae(e,["state","address","kind","salt","txHash"]),e.state!=="pending"&&e.state!=="ready"||typeof e.address!="string"||!/^0x[0-9a-fA-F]{40}$/.test(e.address)||e.kind!=="push"||e.salt!==`0x${"00".repeat(32)}`||e.txHash!==null&&(typeof e.txHash!="string"||!/^0x[0-9a-f]{64}$/.test(e.txHash)))throw new S("bad_request");return e}function Mg(e,t,r){if(!e||typeof e!="object"||!("baseSplit"in e))throw new S("bad_request");let{baseSplit:n,...o}=e,i=Dg(n);if("state"in o&&o.state==="receiving")return{...zg(o,r.hostOrigin,t),baseSplit:i};if("state"in o&&o.state==="reserved")return{...$g(o,t,r),baseSplit:i};if(ae(o,["uploadId","state","result"]),o.uploadId!==t||o.state!=="published")throw new S("bad_request");return{uploadId:t,state:"published",result:Lg(o.result,r),baseSplit:i}}var ic=class{origin;fetcher;constructor(t,r={}){this.origin=di(t),this.fetcher=r.fetch??fetch}async request(t,r,n,o,i){try{return await this.requestJson(t,r,n,o,i)}catch{return rs("operation_failed")}}async requestJson(t,r,n,o,i){let s=await this.fetcher(`${this.origin}${t}`,{method:r,credentials:"omit",redirect:"error",signal:AbortSignal.timeout(r==="PUT"?18e5:5e3),headers:{...n===void 0?{}:{"Content-Type":r==="PUT"?"application/octet-stream":"application/json"},...o?{"Annon-Upload-Authorization":vS(o)}:{}},...n===void 0?{}:{body:n},...n instanceof ReadableStream?{duplex:"half"}:{}});if(s.redirected||s.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()!=="application/json")return await s.body?.cancel(),rs("operation_failed");let a=s.body?.getReader();if(!a)return rs("operation_failed");let c=[],d=0;try{for(;;){let{value:m,done:h}=await a.read();if(h)break;if(d+=m.length,d>131072)throw new S("bad_request","Upload response is too large.");c.push(m)}}finally{await a.cancel(),a.releaseLock()}let f=new Uint8Array(d),u=0;for(let m of c)f.set(m,u),u+=m.length;let l=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(f));if(bd(l?.error))return rs(l.error,l.retryAfterSeconds);if(s.ok)try{if(!i)throw new S("bad_request");return{ok:!0,value:i(l,s.status)}}catch{return rs("operation_failed")}let p=bd(l?.error)?l.error:"operation_failed";return rs(p,p==="operation_failed"?void 0:l.retryAfterSeconds)}path(t){if(!/^[a-f0-9]{64}$/.test(t))throw new S("bad_request","Invalid upload ID.");return`/v1/uploads/${t}`}create(t){return this.request("/v1/uploads","POST",JSON.stringify(M0(t)),void 0,r=>r&&typeof r=="object"&&"baseSplit"in r?Mg(r,r.uploadId,t.intent):zg(r,this.origin))}async body(t,r,n){return this.request(`${this.path(t)}/body`,"PUT",n,r,o=>$g(o,t,r.intent))}async header(t,r,n){return this.request(`${this.path(t)}/header`,"PUT",n,r,o=>Lg(o,r.intent))}async status(t,r){return this.request(this.path(t),"GET",void 0,r,n=>Mg(n,t,r.intent))}async baseSplit(t,r,n){if(ae(n,["kind","salt"]),n.kind!=="push"||n.salt!==`0x${"00".repeat(32)}`)throw new S("bad_request");return this.request(`${this.path(t)}/base-split`,"POST",JSON.stringify(n),r,(o,i)=>{ae(o,["baseSplit"]);let s=Dg(o.baseSplit);if(!s||i!==(s.state==="pending"?202:200))throw new S("bad_request");return{baseSplit:s}})}};var fi=globalThis.crypto.subtle,ac=new TextEncoder,br=class extends S{constructor(){super("source_changed","source changed between passes"),this.name="SourceChangedError"}},ns=class{reader;pending=new Uint8Array;at=0;ended=!1;released=!1;cancellation;constructor(t){this.reader=t.getReader()}async read(t){let r=new Uint8Array(t),n=0;for(;n<t;){if(this.at===this.pending.length){if(this.pending=new Uint8Array,this.at=0,this.ended)break;let i=await this.reader.read();if(i.done){this.ended=!0;break}if(!(i.value instanceof Uint8Array))throw new TypeError("expected Uint8Array");this.pending=i.value}let o=Math.min(t-n,this.pending.length-this.at);r.set(this.pending.subarray(this.at,this.at+o),n),this.at+=o,n+=o,this.at===this.pending.length&&(this.pending=new Uint8Array,this.at=0)}return r.subarray(0,n)}cancel(t){return this.cancellation??=this.reader.cancel(t).catch(()=>{}),this.cancellation}release(){this.released||(this.released=!0,this.pending=new Uint8Array,this.reader.releaseLock())}};function H0(e,t){let r=new ns(e);async function*n(){try{yield*t(r)}finally{await r.cancel(),r.release()}}let o=n();return new ReadableStream({async pull(i){try{let s=await o.next();s.done?i.close():i.enqueue(s.value)}catch(s){i.error(s)}},async cancel(i){await r.cancel(i),await o.return(),r.release()}},{highWaterMark:0})}async function z0(e,t,r,n){if(n.fileId.length!==32||e.length!==32)throw new TypeError("fileId and K are 32 bytes");if(!Number.isSafeInteger(r)||r<0)throw new RangeError("size must be a safe unsigned integer");let{version:o,authKind:i}=b0(n),s=We(n.fileId),a=We(e),c=n.previewLen??0;if(!Number.isSafeInteger(c)||c<0||c>no(r))throw new RangeError(`previewLen must be 0 to ${no(r)}`);let d=n.chunkLog2??22;for(;n.chunkLog2===void 0&&d<24&&ro(r,c,d)>Wi;)d++;if(!Number.isInteger(d)||d<16||d>24)throw new RangeError("chunkLog2 must be an integer from 16 to 24");let f=ro(r,c,d);if(f>Wi)throw new RangeError("file too large for PAY2");let u=2**d,l=ac.encode(n.name);if(!/^[\x20-\x7e]{0,255}$/.test(n.mime))throw new RangeError("mime must be printable ASCII");let p=Te(rt(l.length,2),l,rt(n.mime.length,1),ac.encode(n.mime),rt(r,8)),m=Math.ceil(p.length/256)*256;if(m>Kd)throw new RangeError("name too long");let h=Te(p,new Uint8Array(m-p.length)),y=c>0?2:1,b=[];for(let U=0;U<y;U++)b.push(await Xa(await ti(a,s,U)));let x=Te(new Uint8Array(Ya),new Uint8Array([o,d,1,i]),new Uint8Array(4),s,rt(m,2),rt(c,4),rt(f,4),...b,new Uint8Array(32*f)),g=Array.from({length:f},(U,R)=>x.subarray(Hr+32*(y+R),Hr+32*(y+R+1)));async function*w(U,R=!1){let T=r;for(let O=0;O<f;O++){let H=O===0?m:O===1&&c>0?c:Math.min(u,T),P=O===0?h:await U.read(H);if(P.length!==H)throw R?new br:new RangeError("plaintext shorter than size");O>0&&(T-=H);let _=O===f-1;if(_&&(await U.read(1)).length!==0)throw R?new br:new RangeError("plaintext longer than size");yield await Ja("encrypt",await ti(a,s,O),_,P)}}let v=new ns(t),E=[];try{let U=0;for await(let R of w(v))U<y&&E.push(R),g[U++].set(await Oe(R))}finally{await v.cancel(),v.release()}let B=await ec({version:o,chunkLog2:d,fileId:s,metaLen:m,previewLen:c,n:f,commits:b,hashes:g}),N;return{manifest:{version:o,chunkLog2:d,metaLen:m,previewLen:c,n:f,keyCommitments:b.map(Y),chunkHashes:g.map(Y)},headerSize(U){return be(U),206+ac.encode(U).length+32*(y+f)},body(U){return H0(U,async function*(R){let T=0;for await(let O of w(R,!0)){if(!pt(await Oe(O),g[T++]))throw new br;yield O}})},fileId:We(s),cipherHash:B,async finish(U,R){let{contractId:T,ckdSecret:O}=R;be(T);let H=await Qa(O,s,"wrapKey"),P=await fi.importKey("raw",a,"AES-GCM",!0,["encrypt"]),_=new Uint8Array(await fi.wrapKey("raw",P,H,"AES-KW")),I=ac.encode(yn),k=Te(new Uint8Array([T.length]),ac.encode(T),_),M=Te(new Uint8Array([I.length]),I,rt(k.length,2),k),$=Te(x,M);new DataView($.buffer).setUint32(8,$.length+hn+yr);let F=await fi.importKey("raw",await ei(a,s,"annon/pay2/header"),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),A=new Uint8Array(await fi.sign("HMAC",F,$)),z=await g0(o,i,R,s,await Oe($,A)),D=Te($,A,z);return N=D,H0(U,async function*(q){yield D;let j=0;for await(let K of w(q,!0)){if(!pt(await Oe(K),g[j++]))throw new br;yield K}})},async preview(U){if(!N)throw new Error("call finish first: the preview carries the final header");if(U.data&&c===0)throw new RangeError("sealed without a preview");let R=N.slice(0,x.length);R[6]=0,new DataView(R.buffer).setUint32(8,0);let T=H=>{let P="";for(let _ of H)P+=String.fromCharCode(_);return btoa(P)},O=[];for(let H of[0,1])(H===0?U.meta:U.data)&&O.push({index:H,key:T(await ti(a,s,H)),data:T(E[H])});return{v:1,header:T(R),chunks:O}}}}async function $0(e){let t=await e.read(Hr);if(t.length<4||!Ya.every((i,s)=>t[s]===i))throw new Re("bad_magic");if(t.length<Hr)throw new Re("bad_header");if(t[4]!==2)throw new Re("unsupported_version");let r=t[5]??0;if(r<16||r>24)throw new Re("bad_chunk_size");let o=new DataView(t.buffer).getUint32(8);if(o>m0)throw new Re("header_too_large");return Te(t,await e.read(Math.max(0,o-Hr)))}function qg(e,t,r){return H0(e,async function*(n){let o=await $0(n);if(t.expectedHeader&&!pt(o,t.expectedHeader))throw new br;let i=await Yi(o,t.listing,t.contractId),s=i.stanzas.map(m=>m.type===yn?ri(m.body):void 0).find(m=>m?.contractId===t.contractId);if(!s)throw new Re("no_usable_stanza");let a=await Qa(await t.ckdSecret(We(i.fileId)),i.fileId,"unwrapKey"),c;try{c=await fi.unwrapKey("raw",s.wrapped,a,"AES-KW","HKDF",!1,["deriveBits"])}catch{throw new Re("key_unwrap_failed")}let d=await fi.importKey("raw",await ei(c,i.fileId,"annon/pay2/header"),{name:"HMAC",hash:"SHA-256"},!1,["verify"]),f=i.headerLen-hn-yr;if(!await fi.verify("HMAC",d,o.subarray(f,f+hn),o.subarray(0,f)))throw new Re("header_mac_invalid");let u=2**i.chunkLog2,l,p=0;for(let m=0;m<i.n;m++){let h=m===i.n-1,y=m===0?i.metaLen+ve:m===1&&i.previewLen>0?i.previewLen+ve:u+ve,b=await n.read(h?u+ve+1:y);if(h?b.length<ve||b.length>u+ve:b.length!==y)throw new Re("bad_body_length");if(!pt(await Oe(b),i.hashes[m]))throw new Re("chunk_hash_mismatch",`chunk ${m}`);let x=await ti(c,i.fileId,m),g=i.commits[m];if(g&&!pt(await Xa(x),g))throw new Re("chunk_invalid",`chunk ${m} key commitment`);let w;try{w=await Ja("decrypt",x,h,b)}catch{throw new Re("chunk_invalid",`chunk ${m}`)}if(m===0){if(l=y0(w,i),r!==void 0&&l.size!==r)throw new Re("meta_invalid","chunk lengths do not add up to the size");t.onMeta?.({...l})}else{if(p+=w.length,h&&p!==l?.size)throw new Re("meta_invalid","chunk lengths do not add up to the size");yield w}}})}function jg(e,t,r){return e instanceof ReadableStream?r?r(e,t):Promise.reject(new TypeError("a ciphertext spool is required for a single-use stream")):t(e)}function cc(e){return{size:e.size,read:()=>e.stream()}}async function ui(e,t,r){if(t instanceof Uint8Array){let i=t.slice(),s=await sg(e,i,r),a=await z0(e,new Blob([i]).stream(),i.length,r),c=()=>a.body(new Blob([i]).stream());return{...s,manifest:a.manifest,headerSize:a.headerSize,body:c,stage:(d,f)=>d(c(),f),async finish(d){let f=await s.finish(d);return{consumed:()=>!0,cancel:async()=>{},file:f,header:f.subarray(0,new DataView(f.buffer).getUint32(8))}}}}let n=t.read(),o;try{o=await z0(e,n,t.size,r)}catch(i){throw await n.cancel(i).catch(()=>{}),i}return{...o,body:()=>o.body(t.read()),stage:(i,s)=>i(o.body(t.read()),s),async finish(i){let s=t.read(),a;try{a=await o.finish(s,i)}catch(h){throw await s.cancel(h).catch(()=>{}),h}let c=a.getReader(),d;try{d=(await c.read()).value}catch(h){throw await c.cancel(h),c.releaseLock(),h}let f=!1,u=()=>{f||(f=!0,c.releaseLock())},l=!0,p=!1,m=new ReadableStream({async pull(h){if(l){l=!1,h.enqueue(d);return}try{let y=await c.read();y.done?(p=!0,h.close(),u()):h.enqueue(y.value)}catch(y){h.error(y),u()}},async cancel(h){await c.cancel(h),u()}},{highWaterMark:0});return{file:m,header:d,consumed:()=>p,async cancel(h){if(!f)try{await c.cancel(h)}finally{u()}await m.cancel(h).catch(()=>{})}}}}}async function Gg(e,t){let r=new ns(e.read()),n,o=0;try{n=await $0(r);let i=await Yi(n,t.listing,t.contractId),s=2**i.chunkLog2,a=-1;for(let c=0;c<i.n;c++){let d=c===i.n-1,f=c===0?i.metaLen+ve:c===1&&i.previewLen>0?i.previewLen+ve:s+ve,u=await r.read(d?s+ve+1:f);if(d?u.length<ve||u.length>s+ve:u.length!==f)throw new Re("bad_body_length");c>0&&(o+=u.length-ve),!pt(await Oe(u),i.hashes[c])&&a<0&&(a=c)}if(a>=0)throw new Re("chunk_hash_mismatch",`chunk ${a}`);if(!i.stanzas.some(c=>c.type===yn&&ri(c.body)?.contractId===t.contractId))throw new Re("no_usable_stanza")}finally{await r.cancel(),r.release()}return{header:n.slice(),async writeTo(i,s){let a;if(await qg(e.read(),{...t,expectedHeader:n,ckdSecret:s,onMeta:c=>{a=c}},o).pipeTo(i),!a)throw new Re("meta_invalid");return a}}}var D0=kt.G1.Point,Vg=kt.G2.Point,Kg=kt.fields.Fr,SS="NEAR BLS12381G1_XMD:SHA-256_SSWU_RO_",af=class extends S{code;constructor(t,r=t){super(t,r),this.code=t,this.name="CkdError"}},cf=(e,t)=>{throw new af(e,t)};function fo(){let e=Yg(kt.utils.randomSecretKey())%Kg.ORDER;return jt(TS(e===0n?1n:e))}function jt(e){let t=D0.BASE.multiply(Xg(e)).toBytes(!0);return{secret:e,publicKey:`bls12381g1:${Ct.encode(t)}`,publicKeyBytes:t}}var ES=(e,t)=>Zb(new TextEncoder().encode(`near-mpc v0.1.0 app_id derivation:${e},${t}`)),Wg=(e,t)=>ES(e,`file/${Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}`);function Zg(e,t){let r=e;r&&typeof r.error=="string"&&cf("ckd_failed",r.error);let n=L0(D0,r?.big_y,"bls12381g1:",48),o=L0(D0,r?.big_c,"bls12381g1:",48),i=L0(Vg,t.mpcKey,"bls12381g2:",96);return _S(Xg(t.secret),n,o,i,t.appId).toBytes(!0)}function _S(e,t,r,n,o){let i=r.subtract(t.multiply(e)),s=AS(n,o),a=!1;try{a=!i.is0()&&kt.fields.Fp12.eql(kt.pairing(s,n),kt.pairing(i,Vg.BASE))}catch{}return a||cf("ckd_invalid","the answer is not the key for this file and this one-time key"),i}var AS=(e,t)=>kt.shortSignatures.hash(new Uint8Array([...e.toBytes(!0),...t]),SS),Yg=e=>BigInt(`0x${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")||"0"}`),TS=e=>Uint8Array.from(e.toString(16).padStart(64,"0").match(/../g)??[],t=>Number.parseInt(t,16));function Xg(e){if(e.length!==32)throw new TypeError("the one-time secret is 32 bytes");let t=Yg(e);if(t===0n||t>=Kg.ORDER)throw new TypeError("the one-time secret is not a valid scalar");return t}function L0(e,t,r,n){if(typeof t!="string"||!t.startsWith(r))return cf("ckd_invalid","bad point");try{let o=Ct.decode(t.slice(r.length));if(o.length!==n)throw new Error("length");return e.fromBytes(o)}catch{return cf("ckd_invalid","bad point")}}var Lr=5e7,Dr=50086016,df=60;var q0=["terms_review","preparing","payment_uncertain","awaiting_deposit","incomplete_deposit","processing","accepting","accepted","recovering","file_ready","refunded","failed","expired","abandoned"];function dc(e,t){if(t===null){if(e===null)throw new TypeError("nothing to remove");return}if(t.revision!==(e===null?0:e.revision+1))throw new TypeError("next must be the expected record's next revision");if(e!==null&&t.id!==e.id)throw new TypeError("next must keep the id of the record it replaces")}var IS=(e,t)=>t===null?e===null:e!==null&&e.id===t.id&&e.revision===t.revision,Jg=e=>e==null?null:JSON.parse(e);function fc(e={}){let t=e.factory??globalThis.indexedDB;if(!t)throw new TypeError("no IndexedDB here: pass a factory or use another store");let r=e.name??"annon",n,o=()=>(n??=new Promise((a,c)=>{let d=t.open(r,1);d.onupgradeneeded=()=>d.result.createObjectStore("records"),d.onsuccess=()=>a(d.result),d.onerror=()=>c(d.error)}),n),i=async a=>(await o()).transaction("records",a,{durability:"strict"}).objectStore("records"),s=async a=>{if(!a.length||new Set(a.map(d=>d.key)).size!==a.length)throw new TypeError("empty or duplicate CAS keys");for(let d of a)dc(d.expected,d.next);let c=await i("readwrite");return new Promise((d,f)=>{let u=a.length,l=!0,p=!1;for(let h of a){let y=c.get(h.key);y.onsuccess=()=>{try{if(IS(Jg(y.result),h.expected)||(l=!1),--u!==0||!l)return;for(let b of a)b.next===null?c.delete(b.key):c.put(JSON.stringify(b.next),b.key);p=!0}catch(b){f(b),c.transaction.abort()}}}c.transaction.oncomplete=()=>d(p);let m=()=>f(c.transaction.error??new Error("the IndexedDB transaction was aborted"));c.transaction.onerror=m,c.transaction.onabort=m})};return{load:async a=>{let c=await i("readonly");return new Promise((d,f)=>{let u=c.get(a);u.onsuccess=()=>d(Jg(u.result)),u.onerror=()=>f(u.error)})},compareAndSet:(a,c,d)=>s([{key:a,expected:c,next:d}]),compareAndSetMany:s}}var uf=globalThis.crypto.subtle,j0=2*1024*1024,G0="annon/purchase-backup/v1";function kS(e){if("kind"in e&&e.kind==="browser-recovery-archives"){if(G(e.purchaseId,32),e.id!==`recovery-archives:${e.purchaseId}`||!Number.isSafeInteger(e.revision)||e.revision<0||!Array.isArray(e.names)||new Set(e.names).size!==e.names.length||e.names.some(t=>typeof t!="string"||!t.startsWith(`recovery:${e.purchaseId}:revision:`)||!/^[0-9]+$/.test(t.slice(t.lastIndexOf(":")+1))))throw new TypeError("invalid recovery archive index");return}if("kind"in e&&e.kind==="browser-purchase"){Qg(e);return}if("kind"in e&&e.kind==="browser-purchase-index"){if(e.id!=="browser-index"||!Number.isSafeInteger(e.revision)||e.revision<0||!Array.isArray(e.entries)||new Set(e.entries.map(t=>t.id)).size!==e.entries.length)throw new TypeError("invalid browser purchase index");for(let t of e.entries){if(!/^[a-zA-Z0-9_-]{1,128}$/.test(t.id)||!Number.isSafeInteger(t.revision)||t.revision<0||!q0.includes(t.state)||!["near","base","1click"].includes(t.route)||!Number.isSafeInteger(t.createdAt)||!Number.isSafeInteger(t.updatedAt)||t.createdAt<0||t.updatedAt<t.createdAt)throw new TypeError("invalid browser index entry");G(t.fileId,32),t.purchaseId!==void 0&&G(t.purchaseId,32);let r=new URL(t.resourceUrl);if(!["https:","http:"].includes(r.protocol)||r.username||r.password)throw new TypeError("invalid resource URL");if(Object.keys(t).some(n=>!["id","revision","fileId","route","state","resourceUrl","purchaseId","createdAt","updatedAt"].includes(n)))throw new TypeError("index must contain metadata only")}if(et.encode(JSON.stringify(e)).length>j0)throw new TypeError("browser index too large");return}if("kind"in e&&e.kind==="browser-receipt"){ae(e,["kind","entry"]),Qg(e.entry);return}if("kind"in e&&e.kind==="seller-key"){if(ae(e,["kind","id","revision","file_id","seller","buyerSecret","deadline"]),e.id!==`seller-key:${e.file_id}`||!Number.isSafeInteger(e.revision)||e.revision<0||!Number.isSafeInteger(e.deadline)||e.deadline<0)throw new TypeError("invalid seller key record");G(e.file_id,32),e.buyerSecret!==null&&jt(G(e.buyerSecret,32)),Q(e.seller);return}if("kind"in e&&e.kind==="sell"){if(ss(e),!Object.hasOwn(e,"baseSplit")||!(e.baseSplit===null||e.baseSplit&&/^0x[0-9a-f]{40}$/.test(e.baseSplit.address)&&["push","pull"].includes(e.baseSplit.kind)&&/^0x[0-9a-f]{64}$/.test(e.baseSplit.salt)))throw new TypeError("invalid Base split provenance");if(e.id!==`sell:${e.terms.file_id}`||!Number.isSafeInteger(e.revision)||e.revision<0||!Number.isSafeInteger(e.deadline)||e.deadline<0)throw new TypeError("invalid sell record");if(e.storageBudget!==void 0&&(!/^[1-9][0-9]*$/.test(e.storageBudget)||BigInt(e.storageBudget)>=2n**128n))throw new TypeError("invalid sell storage budget");if(e.storageFunding!==void 0&&(!e.storageBudget||!["pending","funded","refused"].includes(e.storageFunding)))throw new TypeError("invalid sell funding state");if(e.published===!0){if(e.fileKey!==null||e.sellerSecret!==null||e.ckdSecret!==null)throw new TypeError("published sell retains secrets")}else G(e.fileKey,32),G(e.sellerSecret,32);e.ckdSecret!==null&&G(e.ckdSecret,48);return}if("kind"in e&&e.kind==="recovery"){if(G(e.purchase_id,32),G(e.file_id,32),G(e.nonce,32),e.id!==`recovery:${e.purchase_id}`||Y(jt(G(e.buyerSecret,32)).publicKeyBytes)!==e.fresh_key||!Number.isSafeInteger(e.deadline)||e.deadline<0||!Number.isSafeInteger(e.revision)||e.revision<0||!(e.grant===null||Number.isInteger(e.grant)&&e.grant>=0&&e.grant<=4294967295))throw new TypeError("invalid recovery record");Q(e.recovery)}else lf(e)}function Qg(e){if(!/^[a-zA-Z0-9_-]{1,128}$/.test(e.id)||!Number.isSafeInteger(e.revision)||e.revision<0||!q0.includes(e.state)||!["near","base","1click"].includes(e.route)||typeof e.header!="string"||!/^0x(?:[0-9a-f]{2}){1,65536}$/.test(e.header)||e.needsProof!==void 0&&typeof e.needsProof!="boolean"||!["not_submitted","uncertain","submitted"].includes(e.submission))throw new TypeError("invalid browser purchase");if(e.paymentStarted!==void 0&&typeof e.paymentStarted!="boolean")throw new TypeError("invalid payment boundary");if(e.lease&&(!/^[a-zA-Z0-9_-]{1,128}$/.test(e.lease.owner)||!Number.isSafeInteger(e.lease.expiresAt)||e.lease.expiresAt<0))throw new TypeError("invalid purchase lease");if(e.recoveryArchives!==void 0){if(!Array.isArray(e.recoveryArchives)||new Set(e.recoveryArchives.map(r=>r.revision)).size!==e.recoveryArchives.length)throw new TypeError("invalid recovery archives");for(let r of e.recoveryArchives){if(r.kind!=="recovery")throw new TypeError("invalid recovery archive");if(ff(r),!e.purchase||r.purchase_id!==e.purchase.id||r.file_id!==e.fileId)throw new TypeError("recovery archive mismatch")}}if(G(e.fileId,32),_t(e.maxPrice,128)===0n)throw new TypeError("invalid browser price");let t=new URL(e.resourceUrl);if(!["https:","http:"].includes(t.protocol)||t.username||t.password)throw new TypeError("invalid resource URL");if(e.purchase&&(lf(e.purchase),e.purchase.purchase.file_id!==e.fileId||e.purchase.purchase.route!==(e.route==="base"?"base-usdc":"near-usdc")||e.purchase.payment.route!==e.route))throw new TypeError("browser purchase mismatch");if(e.recovery&&(ff(e.recovery),!e.purchase||e.recovery.purchase_id!==e.purchase.id||e.recovery.file_id!==e.fileId))throw new TypeError("browser recovery mismatch");if(e.checkpoint&&(!e.purchase||!Number.isSafeInteger(e.checkpoint.attempts)||e.checkpoint.attempts<0||!Number.isSafeInteger(e.checkpoint.errors)||e.checkpoint.errors<0))throw new TypeError("invalid browser checkpoint")}function ff(e){try{kS(e)}catch(t){throw new S("invalid_record","Invalid encrypted record.",{cause:t})}}var uc=()=>crypto.getRandomValues(new Uint8Array(32));function BS(e){if(!(e instanceof Uint8Array)||e.length!==32)throw new TypeError("backup secret must be 32 random bytes held by the user");return uf.importKey("raw",We(e),"HKDF",!1,["deriveKey"])}async function ew(e,t){return uf.deriveKey({name:"HKDF",hash:"SHA-256",salt:We(t),info:et.encode(G0)},await BS(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function lf(e){try{PS(e)}catch(t){throw new S("invalid_record","Invalid purchase record.",{cause:t})}}function PS(e){if(typeof e.recoveryProved!="boolean")throw new TypeError("invalid recovery proof checkpoint");if(e?.schemaVersion!==2||!Object.hasOwn(e,"quote")||!(e.quote===null||e.quote&&typeof e.quote=="object"&&e.quote.request&&e.quote.response&&e.quote.deposit)||!e.payment||!["near","base","1click"].includes(e.payment.route)||e.payment.route==="base"!=(e.purchase.route==="base-usdc")||e.payment.amountBaseUnits!==e.purchase.price||e.payment.amountUsdc!==ct(BigInt(e.purchase.price))||e.payment.network!==e.purchase.network||e.payment.asset?.symbol!=="USDC"||e.payment.asset.id!==e.purchase.asset||!Number.isSafeInteger(e.revision)||e.revision<0||e.id!==bn(e.purchase,e.purchase.route==="base-usdc"?{baseUsdc:e.purchase.asset}:{nearUsdc:e.purchase.asset})||e.message!==zr(e.purchase,e.purchase.route==="base-usdc"?{baseUsdc:e.purchase.asset}:{nearUsdc:e.purchase.asset})||Y(jt(G(e.buyerSecret,32)).publicKeyBytes)!==e.purchase.buyer_key||Q(e.recovery)!==Q(e.purchase.recovery)||e.paymentState!==void 0&&!["expired","canceled"].includes(e.paymentState)||!Array.isArray(e.attempts)||!e.terms||e.terms.network!==e.purchase.network||e.terms.usdc!==e.purchase.asset||e.terms.price!==e.purchase.price||e.terms.nonce!==(e.purchase.route==="base-usdc"?Qd(e.id):e.purchase.nonce)||e.terms.contractId!==e.purchase.contract||e.terms.fileId!==e.purchase.file_id||e.terms.buyerKey!==e.purchase.buyer_key||e.terms.headerHash!==e.checkedHeaderHash)throw new TypeError("invalid purchase record");if(G(e.checkedHeaderHash,32),et.encode(JSON.stringify(e)).length>j0)throw new TypeError("purchase record too large")}async function li(e,t,r=""){ff(e);let n=crypto.getRandomValues(new Uint8Array(32)),o=crypto.getRandomValues(new Uint8Array(12)),i=await uf.encrypt({name:"AES-GCM",iv:o,additionalData:Te(et.encode(G0),et.encode(r)),tagLength:128},await ew(t,n),et.encode(JSON.stringify(e))),s={format:"annon-purchase-backup",v:1,kdf:"HKDF-SHA256",salt:Y(n),iv:Y(o),ciphertext:Y(new Uint8Array(i))};return JSON.stringify(s)}async function os(e,t,r=""){if(typeof e!="string"||e.length>j0*2+1024)throw new TypeError("backup too large");let n=JSON.parse(e);if(ae(n,["format","v","kdf","salt","iv","ciphertext"]),n.format!=="annon-purchase-backup"||n.v!==1||n.kdf!=="HKDF-SHA256"||typeof n.ciphertext!="string"||!/^0x(?:[0-9a-f]{2}){16,}$/.test(n.ciphertext))throw new TypeError("unsupported backup format");let o=G(n.ciphertext,(n.ciphertext.length-2)/2),i=await uf.decrypt({name:"AES-GCM",iv:G(n.iv,12),additionalData:Te(et.encode(G0),et.encode(r)),tagLength:128},await ew(t,G(n.salt,32)),o),s=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i));return ff(s),s}var pf=(e,t)=>li(e,t),V0=async(e,t)=>{let r=await os(e,t);if("kind"in r)throw new TypeError("not a purchase");return r},is=(e,t)=>li(e,t),mf=async(e,t)=>{let r=await os(e,t);if(!("kind"in r)||r.kind!=="recovery")throw new TypeError("not a recovery");return r};function pi(e,t){if(t.length!==32)throw new TypeError("backup secret must be 32 bytes");let r=We(t),n=(o,i)=>JSON.stringify([o,i.id,i.revision]);return{async load(o){let i=await e.load(o);if(!i)return null;let s=await os(i.backup,r,n(o,i));if(!("id"in s)||s.id!==i.id||s.revision!==i.revision)throw new Error("encrypted record metadata mismatch");return s},async compareAndSet(o,i,s){dc(i,s);let a=s?{id:s.id,revision:s.revision,backup:await li(s,r,n(o,s))}:null;return e.compareAndSet(o,i,a)}}}var mi=(e,t)=>pi(e,t),lc=(e,t)=>pi(e,t),gn=(e,t)=>li(e,t),K0=async(e,t)=>{let r=await os(e,t);if(!("kind"in r)||r.kind!=="sell")throw new TypeError("not a sell record");return r},hf=(e,t)=>pi(e,t),W0=(e,t)=>li(e,t);async function RS(e,t){try{let r=await os(e,t);if(!("kind"in r)||r.kind!=="seller-key")throw new S("invalid_record");return r}catch(r){throw r instanceof S&&r.code==="invalid_record"?r:new S("invalid_record",void 0,{cause:r})}}var tw=(e,t)=>pi(e,t),rw=(e,t)=>li(e,t);async function nw(e,t){let r=await os(e,t);if(!("kind"in r)||r.kind!=="browser-receipt")throw new S("invalid_record");return r}var ow=(e,t)=>pi(e,t),iw=(e,t)=>pi(e,t);async function yf(e,t,r){return{id:t.id,revision:t.revision,backup:await li(t,r,JSON.stringify([e,t.id,t.revision]))}}var sw=(e,t)=>pi(e,t);var mc=8453,Z0="TransferWithAuthorization",aw=[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}],cw=(e,t)=>({domain:{name:"USD Coin",version:"2",chainId:mc,verifyingContract:e},types:{[Z0]:aw},primaryType:Z0,message:t}),bf=new TextEncoder,pc=(...e)=>at(e),Ze=e=>vd(e);function Ft(e,t,r){if(!new RegExp(`^0x[0-9a-fA-F]{${2*t}}$`).test(e))throw new TypeError(`${r} must be 0x and ${t} bytes of hex`);return Uint8Array.from(e.slice(2).match(/../g)??[],n=>Number.parseInt(n,16))}function Ge(e){if(e<0n||e>=2n**256n)throw new RangeError("not a uint256");return Ft(`0x${e.toString(16).padStart(64,"0")}`,32,"word")}var mt=e=>pc(new Uint8Array(12),Ft(e,20,"address"));function gf(e,t){let r=Pe(bf.encode("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")),n=Pe(pc(r,Pe(bf.encode("USD Coin")),Pe(bf.encode("2")),Ge(BigInt(mc)),mt(e))),o=Pe(bf.encode(`${Z0}(${aw.map(s=>`${s.type} ${s.name}`)})`)),i=Pe(pc(o,mt(t.from),mt(t.to),Ge(t.value),Ge(t.validAfter),Ge(t.validBefore),Ft(t.nonce,32,"nonce")));return Pe(pc(new Uint8Array([25,1]),n,i))}function wf(e,t){if(!/^0x[0-9a-fA-F]{130}$/.test(t))return null;let r=Ft(t,65,"signature"),n=r[64]??0,o=BigInt(Ze(r.subarray(32,64)));if(n!==27&&n!==28||o>eo.Point.Fn.ORDER/2n)return null;try{let i=eo.Point.fromBytes(eo.recoverPublicKey(pc(new Uint8Array([n-27]),r.subarray(0,64)),e,{prehash:!1}));return Ze(Pe(i.toBytes(!1).subarray(1)).subarray(12))}catch{return null}}var re=class extends S{code;purchase;retryAfterSeconds;constructor(t,r=t){super(t,r),this.code=t,this.name="PayError"}},vf=class extends re{constructor(){super("base_rpc_rate_limited","Base RPC rate limited (429)"),this.name="BaseRpcRateLimited"}},ie=(e,t)=>{throw new re(e,t)},Gt=e=>ie("transport",`malformed Base RPC answer: ${e}`),OS=0;async function fw(e,t,r){let n=`annon-base-${++OS}`,o;try{let i=await fetch(e,{credentials:"omit",method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:n,method:t,params:r}),signal:AbortSignal.timeout(O0)}),s=()=>{if(i.status===429)throw new vf;return ie("transport",`Base RPC HTTP ${i.status}`)};try{o=await i.json()}catch(a){if(!i.ok)return s();throw a}if(i.status===429||!i.ok&&(!o||typeof o!="object"||Array.isArray(o)||o.jsonrpc!=="2.0"&&o.id!==n||!("result"in o)&&!("error"in o)))return s()}catch(i){if(i instanceof re)throw i;return ie("transport",`Base RPC unreachable: ${i.message}`)}return o?.id!==n?Gt("a reply to another request"):o}async function yi(e,t,r){let n=await fw(e,t,r);return n.error&&ie(t==="eth_call"&&n.error.code===3?"refused":"transport",`Base RPC error: ${JSON.stringify(n.error)}`),n.result===void 0?Gt(`no result for ${t}`):n.result}var bc=e=>typeof e=="string"&&/^0x([0-9a-fA-F]{2})*$/.test(e),hc=(e,t)=>{if(typeof e!="string"||!/^0x(0|[1-9a-f][0-9a-f]*)$/i.test(e))return Gt(t);let r=Number.parseInt(e,16);return Number.isSafeInteger(r)?r:Gt(t)},yc=e=>`0x${e.toString(16)}`,J0=e=>Pe(new TextEncoder().encode(e)).subarray(0,4),Q0=(...e)=>Ze(Uint8Array.from(e.flatMap(t=>Array.from(t))));async function lo(e){return await yi(e,"eth_chainId",[])!=="0x2105"&&ie("network_mismatch","the Base RPC is not on Base mainnet (chain 8453)"),as(e,"latest")}async function as(e,t){let r=await yi(e,"eth_getBlockByNumber",[typeof t=="number"?yc(t):t,!1]);return{number:hc(r?.number,"block number"),timestamp:hc(r?.timestamp,"timestamp"),...typeof r?.hash=="string"?{hash:r.hash.toLowerCase()}:{}}}async function em(e,t,r,n){let o=await yi(e,"eth_call",[{to:t,data:r},yc(n)]);return!bc(o)||o.length!==66?Gt("eth_call result"):o.toLowerCase()}var uw=async(e,t,r,n)=>BigInt(await em(e,t,r,n)),Sf=(e,t,r,n)=>uw(e,t,Q0(J0("balanceOf(address)"),mt(r)),n),CS=async(e,t,r,n,o)=>await uw(e,t,Q0(J0("authorizationState(address,bytes32)"),mt(r),Ft(n,32,"nonce")),o)!==0n;async function tm(e,t,r){let n=await yi(e,"eth_getCode",[t,yc(r)]);return bc(n)?n.toLowerCase():Gt("eth_getCode result")}var Ef=async(e,t,r)=>await tm(e,t,r)!=="0x";function US(e,t){let r=Ft(t,65,"signature");return Q0(J0("transferWithAuthorization(address,address,uint256,uint256,uint256,bytes32,uint8,bytes32,bytes32)"),mt(e.from),mt(e.to),Ge(e.value),Ge(e.validAfter),Ge(e.validBefore),Ft(e.nonce,32,"nonce"),Ge(BigInt(r[64]??0)),r.subarray(0,32),r.subarray(32,64))}async function lw(e,t,r,n){let o=await fw(e,"eth_call",[{from:r.from,to:t,data:US(r,n)},"latest"]);if(o.error){let i=String(o.error.message??"");o.error.code===3&&ie("payment_rejected",`USDC refused the authorization: ${i}`),ie("transport",`Base RPC error: ${JSON.stringify(o.error)}`)}bc(o.result)||Gt("eth_call result")}var NS=[["parentHash","bytes"],["sha3Uncles","bytes"],["miner","bytes"],["stateRoot","bytes"],["transactionsRoot","bytes"],["receiptsRoot","bytes"],["logsBloom","bytes"],["difficulty","int"],["number","int"],["gasLimit","int"],["gasUsed","int"],["timestamp","int"],["extraData","bytes"],["mixHash","bytes"],["nonce","bytes"],["baseFeePerGas","int"],["withdrawalsRoot","bytes"],["blobGasUsed","int"],["excessBlobGas","int"],["parentBeaconBlockRoot","bytes"],["requestsHash","bytes"]],pw=(e,t)=>{if(e<56)return[t+e];let r=[];for(let n=e;n>0;n=Math.floor(n/256))r.unshift(n%256);return[t+55+r.length,...r]},FS=e=>e.length===1&&(e[0]??0)<128?[...e]:[...pw(e.length,128),...e],MS=e=>{let t=BigInt(e);if(t===0n)return new Uint8Array;let r=t.toString(16);return Uint8Array.from((r.length%2?`0${r}`:r).match(/../g)??[],n=>Number.parseInt(n,16))},HS=(e,t)=>bc(e)?Uint8Array.from(e.slice(2).match(/../g)??[],r=>Number.parseInt(r,16)):Gt(`header ${t}`);async function mw(e,t){let r=await yi(e,"eth_getBlockByHash",[t,!1]),o=NS.filter(([s])=>r?.[s]!==void 0).flatMap(([s,a])=>FS(a==="int"?MS(String(r[s])):HS(r[s],s))),i=Uint8Array.from([...pw(o.length,192),...o]);return Ze(Pe(i))!==t.toLowerCase()?ie("transport",`block ${t}: the rebuilt header does not hash to it`):Ze(i)}var Y0=e=>Ze(Pe(new TextEncoder().encode(e))),hi={authorizationUsed:Y0("AuthorizationUsed(address,bytes32)"),authorizationCanceled:Y0("AuthorizationCanceled(address,bytes32)"),transfer:Y0("Transfer(address,address,uint256)")},xf=(e,t)=>typeof e=="string"&&/^0x[0-9a-fA-F]{64}$/.test(e)?e.toLowerCase():Gt(t);function hw(e){return typeof e?.address!="string"||!/^0x[0-9a-fA-F]{40}$/.test(e.address)?Gt("log address"):!Array.isArray(e.topics)||!bc(e.data)||typeof e.removed!="boolean"?Gt("log"):{address:e.address.slice(2).toLowerCase(),block_hash:xf(e.blockHash,"log blockHash").slice(2),block_number:hc(e.blockNumber,"log blockNumber"),data:e.data.toLowerCase(),log_index:hc(e.logIndex,"log logIndex"),removed:e.removed,topics:e.topics.map(t=>xf(t,"log topic").slice(2)),transaction_hash:xf(e.transactionHash,"log transactionHash").slice(2),transaction_index:hc(e.transactionIndex,"log transactionIndex")}}var uo=e=>e.slice(2).toLowerCase(),X0=e=>uo(Ze(mt(e)));function zS(e,t){let r=e;if(r?.status!=="0x1"||!Array.isArray(r.logs))return null;let n=xf(r.transactionHash,"receipt transactionHash").slice(2),o=r.logs.map(hw),i=(f,u)=>l=>l.transaction_hash===n&&!l.removed&&l.address===uo(f)&&l.topics.length===3&&l.topics[0]===uo(u),s=(f,u)=>BigInt(`0x${f.slice(2+u*64,2+(u+1)*64)||"0"}`),a=o.findIndex(f=>i(t.usdc,hi.authorizationUsed)(f)&&f.topics[1]===X0(t.from)&&f.topics[2]===uo(t.nonce)),[c,d]=[o[a],o[a+1]];return a<0||!c||!d||!i(t.usdc,hi.transfer)(d)||d.log_index!==c.log_index+1||d.topics[1]!==X0(t.from)||d.topics[2]!==X0(t.to)||d.data.length!==66?null:s(d.data,0)===t.price?[c,d]:null}async function $S(e,t,r,n){let o=Math.max(1,(Number(r)-(await as(e,t)).timestamp)*5);for(let i=t+o;;i+=o,o*=2){if(i>=n.number)return n.number;if(BigInt((await as(e,i)).timestamp)>=r)return i}}var dw=1e4;async function yw(e,t,r,n,o,i){let s=[];for(let a=n;a<=o;a+=dw){let c=Math.min(o,a+dw-1),d=await yi(e,"eth_getLogs",[{address:t,fromBlock:yc(a),toBlock:yc(c),topics:r}]);if(!Array.isArray(d))return Gt("eth_getLogs result");let f=d.map(hw).filter(u=>!u.removed);for(let u of f)if(u.address!==uo(t)||u.topics.length!==r.length||!r.every((l,p)=>[l].flat().some(m=>uo(m)===u.topics[p]))||u.block_number<a||u.block_number>c)return Gt("eth_getLogs returned a log the query did not ask for");if(s.push(...f),f.some(i))break}return s}async function LS(e,t,r,n){let o=[hi.authorizationCanceled,Ze(mt(t.from)),t.nonce.toLowerCase()],[i]=await yw(e,t.usdc,o,r,n,()=>!0);return i?i.block_number:null}async function bw(e,t){let r=await as(e,"finalized"),n=await lo(e),o=await $S(e,t.block,t.validBefore,n),i=uo(hi.authorizationUsed),s=await yw(e,t.usdc,[[hi.authorizationUsed,hi.authorizationCanceled],Ze(mt(t.from)),t.nonce.toLowerCase()],t.block,o,d=>d.topics[0]===i),a=s.find(d=>d.topics[0]===i);if(a){let d=await yi(e,"eth_getTransactionReceipt",[`0x${a.transaction_hash}`]),f=zS(d,t);return!f?.[0]||f[0].transaction_hash!==a.transaction_hash?ie("transport","the authorization was used, but not for this purchase as expected"):{state:"paid",txHash:`0x${f[0].transaction_hash}`,logIndex:f[0].log_index,logs:f}}let c=s.find(d=>d.topics[0]===uo(hi.authorizationCanceled));if(c)return c.block_number<=r.number?{state:"canceled"}:{state:"pending"};if(await CS(e,t.usdc,t.from,t.nonce,n.number)){let d=await LS(e,t,o+1,n.number);return d!==null?d<=r.number?{state:"canceled"}:{state:"pending"}:ie("transport","USDC marks the authorization used, but the RPC returned no log for it")}return BigInt(r.timestamp)>=t.validBefore?{state:"expired"}:{state:"pending"}}function nm(e){let t=e.recipients.length;if(e.allocations.length!==t)throw new TypeError("one allocation per recipient");if(!Number.isInteger(e.distributionIncentive)||e.distributionIncentive<0||e.distributionIncentive>65535)throw new RangeError("distributionIncentive is a uint16");let r=at([Ge(BigInt(t)),...e.recipients.map(mt)]),n=at([Ge(BigInt(t)),...e.allocations.map(Ge)]),o=at([Ge(4n*32n),Ge(4n*32n+BigInt(r.length)),Ge(e.totalAllocation),Ge(BigInt(e.distributionIncentive))]);return at([Ge(32n),o,r,n])}var DS=e=>Ze(Pe(nm(e))),ww=[{kind:"push",factory:"0x8e8eb0cc6ae34a38b67d5cf91aca38f60bc3ecf4",implementation:"0x1e2086a7e84a32482ac03000d56925f607ccb708"},{kind:"pull",factory:"0x6b9118074ab15142d7524e8c4ea8f62a3bdb98f1",implementation:"0x98254aedb6b2c30b70483064367f0ba24ca86244"}],xw=e=>`0x36602c57343d527f9e4ac34f21c619cefc926c8bd93b54bf5a39c7ab2127a895af1cc0691d7e3dff593da1005b3d3d3d3d363d3d37363d73${e.slice(2).toLowerCase()}5af43d3d93803e605757fd5bf3`;function qS(e,t,r,n){let o=at([Ge(64n),mt(r),nm(t).subarray(32)]),i;"salt"in n?i=Pe(at([o,Ft(n.salt,32,"salt")])):i=Pe(at([Pe(o),Ge(n.nonce)]));let s=at([Ft("0x60593d8160093d39f3",9,"init"),Ft(xw(e.implementation),89,"clone"),new Uint8Array(15)]),a=Pe(at([Uint8Array.of(255),Ft(e.factory,20,"factory"),i,Pe(s)]));return Ze(a.subarray(12))}var rm=`0x${"00".repeat(20)}`,vw=e=>Ze(Pe(new TextEncoder().encode(e)).subarray(0,4)),jS=(e,...t)=>vw(e)+Ze(at(t)).slice(2),GS="(address[],uint256[],uint256,uint16)",VS=e=>nm(e).subarray(32);var gw=100;function Sw(e){e.recipients.length>gw&&ie("bad_requirements",`the split has more than ${gw} recipients`),e.recipients.some(t=>BigInt(t)===0n)&&ie("bad_requirements","the split pays the zero address"),e.totalAllocation<1n&&ie("bad_requirements","the split allocates nothing"),e.totalAllocation>=2n**128n&&ie("bad_requirements","the split allocations are too large to distribute")}function _f(e,t,r){if(Sw(t),t.allocations.reduce((i,s)=>i+s,0n)!==t.totalAllocation)throw new RangeError("the allocations must add up to totalAllocation");let n=ww.find(i=>i.kind===e);if(!n)throw new TypeError("kind is push or pull");let o=jS(`createSplitDeterministic(${GS},address,address,bytes32)`,Ge(128n),mt(rm),mt(rm),Ft(r,32,"salt"),VS(t));return{to:n.factory,data:o,address:qS(n,t,rm,{salt:r})}}async function Ew(e,t,r){if(!/^0x[0-9a-fA-F]{40}$/.test(t))throw new TypeError("address must be 0x and 20 bytes");return Sw(r),KS(e,t.toLowerCase(),r,ww)}async function KS(e,t,r,n){let o=(await lo(e)).number,i=await tm(e,t,o),s=n.find(f=>i===xw(f.implementation));if(!s)return ie("bad_requirements",`${t} is not deployed as a known V2.2 clone`);let a=f=>em(e,t,vw(f),o).catch(u=>{throw u instanceof re&&u.code==="refused"&&ie("bad_requirements",`${t} does not answer ${f}: not an 0xSplits v2 split`),u});await a("splitHash()")!==DS(r)&&ie("bad_requirements","the split on chain is not the one described"),BigInt(await a("owner()"))!==0n&&ie("bad_requirements","the split has an owner who could change where the money goes"),BigInt(await a("paused()"))!==0n&&ie("bad_requirements","the split is paused");let c=(f,u)=>Number(f*1000000n/u)/1e4,d=1e6-r.distributionIncentive;return{kind:s.kind,shares:r.recipients.map((f,u)=>({recipient:f.toLowerCase(),percent:c(r.allocations[u]??0n,r.totalAllocation)*d/1e6})),distributorPercent:r.distributionIncentive/1e4}}function Af(e,t){if(!/^(0|[1-9][0-9]*)$/.test(t.fixed)||!Number.isSafeInteger(t.bps)||t.bps<0||t.bps>1e4)throw new TypeError("invalid protocol fee");let r=BigInt(e);if(r<=0n)throw new TypeError("positive price required");let n=(BigInt(t.fixed)*10000n+r*BigInt(t.bps)+r-1n)/r;if(n>=10000n)throw new TypeError("protocol fee leaves no seller share");return Number(n)}function WS(e,t){let r=new Map;for(let f of t){if(!f.bps)continue;if(!f.identity)throw new TypeError("sponsorship treasury unavailable");let u=ne(f.identity),l=Q(u),p=e.recipients.find(m=>Q(m.identity)===l)?.bps??0;r.set(l,{identity:u,bps:Math.max(p,f.bps,r.get(l)?.bps??0)})}if(!r.size||[...r].every(([f,u])=>e.recipients.some(l=>Q(l.identity)===f&&l.bps>=u.bps))){let f=structuredClone(e),u=e.recipients[e.remainder];if(u&&r.has(Q(u.identity))){let l=e.recipients.findIndex(p=>!r.has(Q(p.identity)));l>=0&&(f.remainder=l)}return f}let n=e.recipients[e.remainder]?.identity,o=e.recipients.filter(f=>!r.has(Q(f.identity))),i=[...r.values()],s=1e4-i.reduce((f,u)=>f+u.bps,0),a=o.reduce((f,u)=>f+u.bps,0);if(!o.length||s<=0||o.length+i.length>8)throw new TypeError("fee requires seller share and one of eight recipient slots");let c=o.map(f=>({...f,bps:Math.floor(f.bps*s/a)}));c.push(...i);let d=c.find(f=>n&&!r.has(Q(f.identity))&&Q(f.identity)===Q(n))??c[0];if(!d)throw new TypeError("seller recipient required");if(d.bps+=1e4-c.reduce((f,u)=>f+u.bps,0),c.some(f=>f.bps<=0))throw new TypeError("fee rounds a recipient to zero");return c.sort((f,u)=>Cr(Tt(f.identity),Tt(u.identity))),{...e,recipients:c,remainder:c.indexOf(d)}}function Tf(e,t,r){if(r&&t.treasuryEvm?.kind!=="evm")throw new TypeError("EVM treasury required");return WS(e,[{identity:r?t.treasuryEvm:t.treasuryNear??t.treasuryEvm,bps:Math.max(Af(e.price,t),r?Af(r,t):0)}])}var ZS=Object.freeze({fixed:"30000",bps:100});function cs(e,t,r=ZS){for(let o of[t,r])if(!/^(0|[1-9][0-9]*)$/.test(o.fixed)||!Number.isSafeInteger(o.bps)||o.bps<0||o.bps>1e4)throw new TypeError("invalid protocol fee");let n=BigInt(e);if(n<=0n)throw new TypeError("positive price required");return BigInt(t.fixed)*10000n+n*BigInt(t.bps)>BigInt(r.fixed)*10000n+n*BigInt(r.bps)}function po(e,t){let r=(n,o)=>{let i=Af(n,t);if(i&&(!o||!e.near.recipients.some(s=>Q(s.identity)===Q(o)&&s.bps>=i)))throw new TypeError("required treasury share missing")};if(r(e.near.price,e.base?t.treasuryEvm:t.treasuryNear??t.treasuryEvm),e.base){if(t.treasuryEvm?.kind!=="evm"&&Af(e.base.price,t))throw new TypeError("EVM treasury required");r(e.base.price,t.treasuryEvm)}}var Vt=class extends S{constructor(r,n){super("transaction_uncertain","Transaction submission is uncertain. Check the saved purchase and transaction hash before retrying.");this.txHash=r;this.purchaseId=n;this.name="TransactionUncertain"}txHash;purchaseId;code="transaction_uncertain"};var ds=e=>({nearUsdc:e.near.token,...e.base?{baseUsdc:e.base.usdc}:{}}),qr=`0x${"00".repeat(32)}`;function If(e){return e.kind==="near"?["stage","deposit","register","fund","publish"]:e.kind==="evm"?["stage","split","register","publish"]:["stage","register","publish"]}function ss(e){let t=e.hosting;if(!t)return;let r=e.terms;if(tt(r,ds(r)),!t||typeof t!="object"||t.origin!==di(t.origin)||!Array.isArray(t.steps)||!Array.isArray(t.completed)||JSON.stringify(t.steps)!==JSON.stringify(If(r.seller))||t.completed.some((o,i)=>o!==t.steps[i])||t.completed.length>t.steps.length||typeof t.backupConfirmed!="boolean")throw new Error("Invalid hosted record.");if(r.seller.kind==="evm"&&(!r.base||!e.baseSplit||e.baseSplit.kind!=="push"||e.baseSplit.salt!==qr||e.baseSplit.address!==r.base.pay_to))throw new Error("Invalid Base terms.");if(r.seller.kind==="near"&&t.fee!==null)throw new Error("Invalid direct fee.");if(t.fee!==null&&t.fee===void 0)throw new Error("Missing fee.");if(t.fee&&po(r,t.fee),r.seller.kind!=="evm"&&(r.base!==null||e.baseSplit!==null))throw new Error("Invalid seller routes.");if(t.pending!==null&&(!t.pending||t.pending.step!==t.steps[t.completed.length]||typeof t.pending.token!="string"))throw new Error("Invalid pending operation.");if(t.pending?.operation&&["deposit","fund"].includes(t.pending.step)){let{snapshot:o,validUntil:i}=t.pending;if(t.pending.step==="deposit"&&typeof t.pending.storageAccountExisted!="boolean"||typeof o!="string"||!/^(0|[1-9][0-9]*)$/.test(o)||BigInt(o)>=2n**128n||!Number.isSafeInteger(i)||(i??-1)<0)throw new Error("Invalid funding snapshot.")}if(t.pending?.startedAt!==void 0&&(!Number.isSafeInteger(t.pending.startedAt)||t.pending.startedAt<0))throw new Error("Invalid operation checkpoint.");if(t.lease!==null&&(!t.lease||typeof t.lease.owner!="string"||!Number.isSafeInteger(t.lease.until)))throw new Error("Invalid lease.");if(t.completed.length&&!t.backupConfirmed)throw new Error("Missing backup confirmation.");if(t.uploadId!==null&&!/^[0-9a-f]{64}$/.test(t.uploadId))throw new Error("Invalid upload.");let n=M0({intent:t.intent,manifest:t.manifest,terms:r,metadata:t.metadata,auth:t.authorization?.auth??(r.seller.kind==="near"?{kind:"near",accountId:r.seller.id,publicKey:"",signature:""}:{kind:r.seller.kind,sig:`0x${"00".repeat(r.seller.kind==="evm"?65:64)}`})});if(n.intent.termsHash!==tt(r,ds(r))||n.intent.fileId!==r.file_id||n.intent.cipherHash!==r.cipher_hash||n.intent.hostOrigin!==t.origin||Q(n.intent.seller)!==Q(r.seller))throw new Error("Invalid hosted binding.");if(t.authorization&&JSON.stringify(t.authorization.intent)!==JSON.stringify(t.intent))throw new Error("Invalid authorization binding.");if(r.seller.kind==="near"&&(!t.listingStorage||!e.storageBudget||!/^[1-9][0-9]*$/.test(t.listingStorage)||BigInt(t.listingStorage)>=2n**128n))throw new Error("Missing approved funding.");if(t.reservation){let o=nf(t.reservation);for(let i of["fileId","termsHash","cipherHash","metadataHash","hostOrigin","byteSize","plaintextSize","headerSize","network","contract"])if(o[i]!==t.intent[i])throw new Error("Invalid reservation binding.");if(o.uploadId!==t.uploadId||Q(o.seller)!==Q(r.seller))throw new Error("Invalid reservation.")}if(t.split!==null&&(!t.split||r.seller.kind!=="evm"||!["pending","ready"].includes(t.split.state)||t.split.address.toLowerCase()!==r.base?.pay_to||t.split.kind!=="push"||t.split.salt!==qr||!(t.split.txHash===null||typeof t.split.txHash=="string")))throw new Error("Invalid split checkpoint.");if(t.completed.includes("split")&&t.split?.state!=="ready")throw new Error("Missing split confirmation.");if(t.result!==null){let o=t.result,i=`${t.origin}/f/${r.file_id.slice(2)}`;if(!o||o.fileId!==r.file_id||o.url!==i||o.header!==`${i}/header`||o.expiresAt!==null&&(!Number.isSafeInteger(o.expiresAt)||o.expiresAt<=0)||t.completed.at(-1)!=="publish"||!t.header||!e.published)throw new Error("Invalid publication.")}if(!!e.published!=(t.result!==null))throw new Error("Invalid completion.");t.header!==null&&G(t.header,(t.header.length-2)/2)}function kf(e){let t=e instanceof Uint8Array?e.length:e.size;if(!Number.isSafeInteger(t)||t<0)throw new S("invalid_arguments");if(t>5e7)throw new S("too_large");return t}var _w=172800;function mo(e){if(!e.ok)throw e.error;return e.value}function Aw(e){if(e.identity.kind!=="near"||!("call"in e))throw new S("near_wallet_required");return e}var Bf=class{constructor(t,r){this.o=t;this.context=r;this.store=hf(t.rawStore,t.backupSecret)}o;context;store;quotes=new Map;async direct(t,r,n,o){let i=await Aw(t).call({receiverId:this.o.contractId,method:r,args:n,deposit:o});if(!i||typeof i!="object"||!("transaction"in i))return i;let s=i.transaction;try{let a=ci(i,this.o.contractId,{txHash:s.hash,signer:t.identity.id,method:r,args:n});if(a.state==="released")return a.answer;if(a.state==="done")return a.value}catch{throw new Vt(s.hash)}throw new Vt(s.hash)}async fundingBalance(t,r){let n=r==="deposit"?await $r(this.o.nearRpc,this.o.contractId,"storage_balance_of",{account_id:t.terms.seller.id}):(await this.context.file(t.terms.file_id))?.purchaseStorageBalance?.toString();if(n===null&&r==="deposit")return null;if(typeof n!="string"||!/^(0|[1-9][0-9]*)$/.test(n)||BigInt(n)>=2n**128n)throw new S("invalid_response");return BigInt(n)}now(){return(this.o.now??(()=>Math.floor(Date.now()/1e3)))()}key(t){return G(t,32),`annon/sell/${t}`}async load(t){try{let r=await this.store.load(this.key(t));if(!r?.hosting||r.terms.network!==this.o.network||r.terms.contract!==this.o.contractId)throw new Error;if(ss(r),await N0(r.hosting.metadata)!==r.hosting.intent.metadataHash)throw new Error;return r}catch(r){throw new S("invalid_record",void 0,{cause:r})}}async save(t,r){if(ss(r),!await this.store.compareAndSet(this.key(r.terms.file_id),t,r))throw new S("store_conflict");return await this.o.writeBackup(r.id,await gn(r,this.o.backupSecret)),r}async quote(t){if(!t.hosting?.origin)throw new S("transport_required");let r=di(t.hosting.origin),n=kf(t.data),o=ne(t.seller.identity);if(o.kind==="near"&&(!t.listingStorage||!t.storageBudget))throw new S("storage_required");for(let E of[t.listingStorage,t.storageBudget])if(E!==void 0&&(E<=0n||E>=2n**128n))throw new S("invalid_arguments");if(o.kind!=="near"&&(t.listingStorage!==void 0||t.storageBudget!==void 0))throw new S("near_wallet_required");let i=sf({filename:t.name,title:t.title??t.name,description:t.description??""}),s=await this.context.config();if(s.network!==this.o.network)throw new S("network_mismatch");let a=t.near?.recipients??[{identity:o,bps:1e4}],c=t.near?.remainder??o,d={token:s.nearUsdc,price:t.price,recipients:structuredClone(a),remainder:a.findIndex(E=>Q(E.identity)===Q(c))},f=null;if(o.kind!=="near"&&this.o.sponsorship){if(f=(await this.o.sponsorship()).fee,cs(t.price,f,this.o.maxProtocolFee)&&!t.onSplit)throw new S("protocol_fee_above_max");d=Tf(d,f,o.kind==="evm"?t.price:void 0)}let u=d.recipients[d.remainder]?.identity;d.recipients.sort((E,B)=>Cr(Tt(E.identity),Tt(B.identity))),d.remainder=d.recipients.findIndex(E=>Q(E.identity)===Q(X(u)));let l=`0x${Y(crypto.getRandomValues(new Uint8Array(32))).slice(2)}`,p=crypto.getRandomValues(new Uint8Array(32)),m=await ui(p,t.data,{fileId:G(l,32),name:i.filename,mime:t.mime,authKind:hr(o)}),h={network:s.network,contract:this.o.contractId,file_id:l,seller:o,pay2_version:2,cipher_hash:Y(m.cipherHash),moderator:null,near:d,base:null},y=null;if(o.kind==="evm"){if(d.recipients.some(B=>B.identity.kind!=="evm"))throw new S("bad_requirements");let E=_f("push",{recipients:d.recipients.map(B=>B.identity.id),allocations:d.recipients.map(B=>BigInt(B.bps)),totalAllocation:10000n,distributionIncentive:0},qr);y={address:E.address,kind:"push",salt:qr},h.base={usdc:s.usdc,price:t.price,pay_to:E.address}}let b=tt(h,{nearUsdc:s.nearUsdc,baseUsdc:s.usdc});f&&po(h,f);let x=m.headerSize(this.o.contractId),g={network:s.network,contract:this.o.contractId,seller:o,fileId:l,cipherHash:h.cipher_hash,termsHash:b,byteSize:x+n+m.manifest.metaLen+16*m.manifest.n,plaintextSize:n,headerSize:x,hostOrigin:r,metadataHash:await N0(i),nonce:Y(crypto.getRandomValues(new Uint8Array(32))),expiresAt:this.now()+600},w={kind:"sell",id:`sell:${l}`,revision:0,terms:h,baseSplit:y,fileKey:Y(p),sellerSecret:Y(fo().secret),deadline:this.now()+540,name:i.filename,mime:t.mime,previewLen:0,ckdSecret:null,...t.storageBudget?{storageBudget:String(t.storageBudget)}:{},hosting:{origin:r,metadata:i,fee:f,intent:g,manifest:m.manifest,authorization:null,uploadId:null,reservation:null,split:null,steps:If(o),completed:[],pending:null,lease:null,backupConfirmed:!1,listingStorage:t.listingStorage?String(t.listingStorage):null,header:null,result:null}},v=crypto.randomUUID();return this.quotes.set(v,{job:structuredClone(w),input:t}),structuredClone({quoteId:v,fileId:l,terms:h,fee:f,steps:w.hosting.steps,metadata:i,listingStorage:w.hosting.listingStorage,storageBudget:w.storageBudget??null})}async begin(t){let r=this.quotes.get(t);if(!r)throw new S("invalid_arguments");let n=await this.save(null,structuredClone(r.job));return this.quotes.delete(t),n}async confirmBackup(t){let r=await this.load(t),n=r.hosting;if(n.backupConfirmed)return r;if(n.pending||n.lease)throw Object.assign(new S("lease_busy"),{retryAfterSeconds:5});return this.save(r,{...r,revision:r.revision+1,hosting:{...n,backupConfirmed:!0}})}async discard(t){let r=await this.load(t);if(r.hosting.lease&&r.hosting.lease.until>this.now())throw Object.assign(new S("lease_busy"),{retryAfterSeconds:5});if(!await this.store.compareAndSet(this.key(t),r,null))throw new S("store_conflict")}async backup(t){return gn(await this.load(t),this.o.backupSecret)}async prepared(t,r){let n=kf(r.data);if(!t.fileKey)throw new S("invalid_record");if(n!==t.hosting?.intent.plaintextSize)throw new S("source_changed");let o=await ui(G(t.fileKey,32),r.data,{fileId:G(t.terms.file_id,32),name:t.name,mime:t.mime,authKind:hr(t.terms.seller)});if(Y(o.cipherHash)!==t.terms.cipher_hash)throw new S("source_changed");return o}async verifySource(t,r){await this.prepared(await this.load(t),{data:r})}async next(t,r){return await this.advance(t,r),this.load(t)}async advance(t,r){let n=await this.load(t);if(r.expectedRevision!==void 0&&r.expectedRevision!==n.revision)throw new S("store_conflict");if(Q(ne(r.seller.identity))!==Q(n.terms.seller))throw new S("wrong_identity");if(di(r.hosting.origin)!==n.hosting.origin)throw new S("config_conflict");if(n.published)return n;if(!n.hosting.backupConfirmed)throw new S("backup_secret_required");if(n.hosting.lease&&n.hosting.lease.until>this.now())throw Object.assign(new S("lease_busy"),{retryAfterSeconds:5});let o=crypto.randomUUID();n=await this.save(n,{...n,revision:n.revision+1,hosting:{...n.hosting,lease:{owner:o,until:this.now()+120}}});let i=async()=>{let T=await this.load(t);if(l||T.revision!==n.revision||T.hosting.lease?.owner!==o||T.hosting.lease.until<=this.now())throw Object.assign(new S("lease_busy"),{retryAfterSeconds:5});if(Q(ne(r.seller.identity))!==Q(n.terms.seller))throw new S("wrong_identity")},s=!1,a=!1,c=!1,d=null,f="",u=Promise.resolve(),l=!1,p=async(T,O={})=>{if(await i(),n=await this.save(n,{...n,...T,revision:n.revision+1,hosting:{...n.hosting,...O,lease:O.lease===null?null:{owner:o,until:this.now()+120}}}),d&&O.lease!==null){await i();let H={...n,revision:d.revision+1,hosting:{...n.hosting,lease:null}};if(!await this.store.compareAndSet(f,d,H))throw new S("store_conflict");d=H}},m=(T,O={})=>{let H=u.then(()=>p(T,O));return u=H.catch(()=>{}),H},h=setInterval(()=>{m({},{lease:{owner:o,until:this.now()+120}}).catch(()=>{l=!0})},3e4),y=async T=>{await u,await i();let O=await T();return await u,await i(),O},b=new ic(n.hosting.origin,this.o.fetch?{fetch:this.o.fetch}:{}),x=async()=>{let T={...n.hosting.intent,expiresAt:this.now()+600};s=!0;let O=await y(async()=>{if(n.terms.seller.kind==="near"){if(!r.hosting.signUpload)throw new S("missing_method");return r.hosting.signUpload(structuredClone(T))}let H=await r.seller.authorize(co(T));if(!H||!lt(n.terms.seller,co(T),H))throw new S("invalid_signature");return H});s=!1,await y(()=>Hg({intent:T,auth:O},{network:this.o.network,contract:this.o.contractId,hostOrigin:n.hosting.origin,now:this.now(),nearRpc:this.o.nearRpc})),await m({},{intent:T,authorization:{intent:T,auth:O}})},g=async(T,O)=>{if(!r.hosting.spool)throw new S("transport_required","A ciphertext spool is required.");await T.stage(r.hosting.spool,async H=>{let P=r.hosting.body?await r.hosting.body(H):H.read(),_=mo(await y(()=>b.body(O,X(n.hosting.authorization),P)));await m({},{reservation:_.reservation})})},w=async()=>{let T=n.hosting,O=mo(await y(()=>b.create({...X(T.authorization),terms:n.terms,manifest:T.manifest,metadata:T.metadata})));if(T.uploadId&&T.uploadId!==O.uploadId)throw new S("upload_conflict");return await m({},{uploadId:O.uploadId,...O.state==="reserved"?{reservation:O.reservation}:{}}),O},v=async()=>n.hosting.authorization&&n.hosting.intent.expiresAt<=this.now()?(await x(),w()):null,E=async()=>m({},{completed:[...n.hosting.completed,X(n.hosting.pending).step],pending:null}),B=async()=>{if(await i(),d&&!await this.store.compareAndSet(f,d,null))throw new S("store_conflict");d=null,await m({},{pending:null})},N=async(T,O,H)=>{a=!0;let P=await this.direct(r.seller,T,O,H);return a=!1,P},U=(T=30)=>Object.assign(new S("transaction_uncertain"),{retryAfterSeconds:T}),R=async(T,O)=>{let H=X(n.hosting.pending),P=!H.txHash,_=H.validUntil===void 0?H.startedAt:H.validUntil-_w;if(P&&_===void 0)throw U();return y(async()=>{try{return await Ug(this.o.nearRpc,O,n.terms.seller.id,this.o.contractId,"FINAL",{...T,...P?{notBefore:X(_)}:{}})}catch(I){throw P?U():I}})};try{let T=n.hosting,O=T.steps[T.completed.length];if(!O)throw new S("invalid_record");if(f=`annon/share-operation/${t}/${O}`,d=await this.store.load(f),await i(),d&&!T.pending){if(tt(d.terms,ds(d.terms))!==T.intent.termsHash)throw new S("invalid_record");if(await m({...d,revision:n.revision},{...X(d.hosting),lease:T.lease}),n.hosting.completed.includes(O)||n.published)return n;T=n.hosting}if(r.txHash!==void 0&&(typeof r.txHash!="string"||!r.txHash||n.terms.seller.kind!=="near"||!T.pending?.operation||!["deposit","fund","publish"].includes(O)))throw new S("invalid_arguments");if(T.pending&&(O==="stage"&&!T.authorization||O==="publish"&&!T.header||O==="register"&&n.terms.seller.kind!=="near"&&!T.pending.auth)&&(await B(),T=n.hosting),T.pending){if(O==="register"){let P=await y(()=>this.context.file(t));if(P){if(P.termsHash!==T.intent.termsHash)throw new S("file_mismatch");await E()}else{let _=T.pending,k=_.operation?.args?.args?.deadline;if(typeof k=="number"&&this.now()>k+60)await B();else if(_.operation?.method==="register"&&_.auth){let M=await y(()=>this.context.call("register",{...X(_.operation).args,auth:_.auth,hostingReservation:T.reservation,...n.baseSplit?{baseSplit:{kind:"push",salt:qr}}:{}},r.seller)),$=await y(()=>this.context.answer(M,jt(G(X(n.sellerSecret),32)).secret,t));await m({ckdSecret:Y($)}),await E()}else throw new S("transaction_uncertain")}}else if(["deposit","fund"].includes(O)){let P=T.pending;if(!P.operation)await B();else if(P.txHash||r.txHash){let _=await R(P.operation,X(P.txHash??r.txHash));if(_.state==="refused")await B();else{if(_.state!=="done")throw U();await E()}}else{let _=await y(()=>this.fundingBalance(n,O));if(O==="deposit"&&P.storageAccountExisted===!1?(_??0n)>0n:(_??0n)>=BigInt(X(P.snapshot))+BigInt(P.operation.deposit))await E();else if(this.now()>X(P.validUntil))await B();else throw U(Math.max(1,X(P.validUntil)-this.now()))}}else if(T.authorization&&["stage","split","publish"].includes(O)){await v(),n.hosting.uploadId||await w(),T=n.hosting;let P=mo(await y(()=>b.status(X(T.uploadId),X(T.authorization))));if(O==="stage"&&P.state!=="published")P.state==="receiving"?await g(await this.prepared(n,r),X(T.uploadId)):await m({},{reservation:P.reservation}),await E();else if(O==="split"){let _=P.baseSplit?.state==="ready"?P.baseSplit:mo(await y(()=>b.baseSplit(X(T.uploadId),X(T.authorization),{kind:"push",salt:qr}))).baseSplit;if(this.checkSplit(n,_),await m({},{split:_}),_?.state!=="ready")throw new S("settlement_pending");await E()}else if(O==="publish"&&P.state==="published")await this.finishPublication(P.result,n,m);else if(O==="publish"&&T.header){if(n.terms.seller.kind==="near"){let I=await y(()=>this.context.file(t)),k=G(T.header,(T.header.length-2)/2);if(I?.headerHash!==Y(await Oe(k.subarray(0,k.length-65)))){let M=X(T.pending),$=M.txHash??r.txHash;if($){let F=X(M.operation),A=await R(F,$);if(A.state==="refused")return await B(),n;if(A.state!=="done")throw U()}else return await B(),n}}let _=mo(await y(()=>b.header(X(T.uploadId),X(T.authorization),new Uint8Array(G(X(T.header),(X(T.header).length-2)/2)))));await this.finishPublication(_,n,m)}else throw new S("transaction_uncertain")}else throw new S("transaction_uncertain");return n}c=!0;let H=await this.prepared(n,r);if(await i(),await m({},{pending:{step:O,token:crypto.randomUUID(),startedAt:this.now()}}),!d){let P={...n,revision:0,hosting:{...n.hosting,lease:null}};if(await i(),!await this.store.compareAndSet(f,null,P))throw new S("store_conflict");d=P}if(O!=="stage"&&await v(),T=n.hosting,O==="stage"){await x();let P=await w();if(P.state==="published")return await this.finishPublication(P.result,n,m),n;P.state==="receiving"&&await g(H,P.uploadId)}else if(O==="split"){if(n.terms.seller.kind!=="evm"||!n.terms.base)throw new S("route_unavailable");await this.live(n,b,y);let P=mo(await y(()=>b.baseSplit(X(T.uploadId),X(T.authorization),{kind:"push",salt:qr}))).baseSplit;if(this.checkSplit(n,P),await m({},{split:P}),P?.state!=="ready")throw new S("settlement_pending")}else if(O==="deposit"||O==="fund"){await this.live(n,b,y);let P=Aw(r.seller),_={method:O==="deposit"?"storage_deposit":"fund_file_storage",args:O==="deposit"?{account_id:P.identity.id}:{file_id:t},deposit:O==="deposit"?X(T.listingStorage):X(n.storageBudget)},I=await y(()=>this.fundingBalance(n,O));await m({},{pending:{...X(n.hosting.pending),operation:_,snapshot:(I??0n).toString(),...O==="deposit"?{storageAccountExisted:I!==null}:{},validUntil:this.now()+_w}}),await y(()=>N(_.method,_.args,BigInt(_.deposit)))}else if(O==="register"){let P=await y(()=>this.context.file(t));if(P){if(P.termsHash!==T.intent.termsHash)throw new S("file_mismatch")}else{await this.live(n,b,y);let _=jt(G(X(n.sellerSecret),32)),I={terms:n.terms,seller_key:Y(_.publicKeyBytes),deadline:this.now()+540};await m({},{pending:{...X(n.hosting.pending),operation:{method:"register",args:{args:I},deposit:"0"}}});let k=await y(async()=>{if(n.terms.seller.kind==="near")return N("register",{args:I},0n);s=!0;let $=await r.seller.authorize(Wa(n.terms,I.seller_key,I.deadline,ds(n.terms)));if(s=!1,!$||!lt(n.terms.seller,Wa(n.terms,I.seller_key,I.deadline,ds(n.terms)),$))throw new S("invalid_signature");return await m({},{pending:{...X(n.hosting.pending),auth:$}}),await i(),this.context.call("register",{args:I,auth:$,hostingReservation:n.hosting.reservation,...n.baseSplit?{baseSplit:{kind:"push",salt:qr}}:{}},r.seller)}),M=await y(()=>this.context.answer(k,_.secret,t));await m({ckdSecret:Y(M)})}}else if(O==="publish"){if(!n.ckdSecret){let _=await y(()=>this.context.reopen(t,r.seller));await m({ckdSecret:Y(_)})}let P=await y(()=>H.finish({contractId:this.o.contractId,seller:n.terms.seller,ckdSecret:G(X(n.ckdSecret),48),...n.terms.seller.kind==="near"?{}:{sign:async _=>{s=!0;let I=await y(()=>r.seller.authorize(_));if(s=!1,!I||!lt(n.terms.seller,_,I))throw new S("invalid_signature");let k=G(I.sig,n.terms.seller.kind==="evm"?65:64);return n.terms.seller.kind==="solana"?{signature:k,signedMessage:new TextEncoder().encode(_)}:k}}}));try{if(P.file instanceof ReadableStream){let I=P.file.getReader();try{for(;!(await I.read()).done;);}finally{I.releaseLock()}}if(!P.consumed())throw new S("upload_incomplete");if(await m({},{header:Y(P.header)}),n.terms.seller.kind==="near"){let I={method:"publish_header",args:{file_id:t,header_hash:Y(await Oe(P.header.subarray(0,P.header.length-65)))},deposit:"0"};await m({},{pending:{...X(n.hosting.pending),operation:I}}),await y(()=>N(I.method,I.args,0n))}let _=mo(await y(()=>b.header(X(T.uploadId),X(T.authorization),new Uint8Array(P.header))));return await this.finishPublication(_,n,m),n}catch(_){throw await P.cancel(_).catch(()=>{}),_}}return await E(),n}catch(T){if((c&&n.hosting.pending?.step==="register"&&T instanceof S&&["budget","limited","rate_limited","not_sponsored","bad_request","bad_signature","bad_deadline","upload_expired"].includes(T.code)&&!("txHash"in T)||c&&(s||a)&&T instanceof S&&T.code==="rejected"&&!("txHash"in T))&&await B(),T instanceof S&&"txHash"in T&&typeof T.txHash=="string")try{await m({},{pending:{...X(n.hosting.pending),txHash:T.txHash}})}catch{}throw T}finally{clearInterval(h),await u;try{await i(),await m({},{lease:null})}catch{}}}checkSplit(t,r){if(!r||t.terms.seller.kind!=="evm"||r.address.toLowerCase()!==t.terms.base?.pay_to||r.kind!=="push"||r.salt!==qr)throw new S("bad_response")}async live(t,r,n){let o=t.hosting;if(!o)throw new S("invalid_record");if(!o.uploadId||!o.authorization)throw new S("upload_incomplete");let i=mo(await n(()=>r.status(X(o.uploadId),X(o.authorization))));if(i.state!=="reserved"||i.reservation.expiresAt<=this.now()||i.reservation.termsHash!==o.intent.termsHash)throw new S("upload_expired")}async finishPublication(t,r,n){let o=t.expiresAt;if(o!==null){if(!Number.isSafeInteger(o)||o<=0)throw new S("bad_response");let i=this.now();if(o<=i)throw new S("file_expired")}await n({published:!0,fileKey:null,sellerSecret:null,ckdSecret:null},{result:t,completed:[...r.hosting?.steps??[]],pending:null})}};function fs(e,t=Date.now()){if(!e?.trim())return;let r=e.trim();if(/^\d+$/.test(r)){let o=Number(r)*1e3;return Number.isSafeInteger(o)?o:void 0}if(!/^[A-Za-z]{3}, /.test(r))return;let n=Date.parse(r);return Number.isFinite(n)?Math.max(0,n-t):void 0}function gc(e,t){return new Promise((r,n)=>{if(t?.aborted){n(t.reason);return}let o=()=>{clearTimeout(i),n(t?.reason)},i=setTimeout(()=>{t?.removeEventListener("abort",o),r()},e);t?.addEventListener("abort",o,{once:!0})})}var YS="ANNON-BUYER-PROOF-V1_BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_",kw="Annon-Buyer-Proof",Tw=kt.longSignatures,om=new TextEncoder,XS=e=>Uint8Array.from([...om.encode("annon/v1.1 buyer proof"),10,...om.encode(e)]),Bw=e=>btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"");function JS(e,t){return Bw(Tw.sign(Tw.hash(XS(t),YS),e).toBytes(!0))}function Iw(e){if(!URL.canParse(e))return null;let t=new URL(e);return t.hash="",t.href}function Pf(e,t){let r=Iw(e);return r!==null&&r===Iw(t)}function Pw(e,t,r,n=0){if(!/^0x[0-9a-f]{64}$/.test(r)||!Number.isInteger(n)||n<0||n>4294967295)throw new TypeError("invalid purchase/grant");return Bw(om.encode(JSON.stringify({purchase_id:r,grant:n,signature:JS(e,t)})))}var $e=class extends S{code;retryAfterSeconds;purchaseId;fileId;constructor(t,r=t){super(t,r),this.code=t,this.name="DownloadError"}},wn=(e,t)=>{throw new $e(e,t)};function QS(e){let t=new URL(e),r=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&r))throw new TypeError(`${e} must be https`);return t}var eE=e=>{try{return e===null?null:JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(e),t=>t.charCodeAt(0))))}catch{return null}};function Ow(e){QS(e.url);let t=We(e.header),r=h0(t),n=Array.from({length:r.n-1},(_,I)=>I===0?r.metaLen+ve:I===1&&r.previewLen>0?r.previewLen+ve:2**r.chunkLog2+ve),o=Math.min(e.maxBytes??50086016,50086016),i=_=>{_>o&&wn("too_large","File exceeds the 50 MB size limit.")};i(t.length+n.reduce((_,I)=>_+I,0)+ve);let s=2**r.chunkLog2+ve,a=e.fetch??globalThis.fetch,c=new AbortController,d=()=>{c.abort(),O?.cancel().catch(()=>{})};e.signal?.aborted&&wn("cancelled");let f=()=>e.signal?.removeEventListener("abort",d),u=()=>{c.signal.aborted&&wn("cancelled")};async function l(_){let I=()=>{},k=new Promise((M,$)=>{I=()=>$(new $e("cancelled")),c.signal.addEventListener("abort",I,{once:!0}),c.signal.aborted&&I()});try{return await Promise.race([_,k])}finally{c.signal.removeEventListener("abort",I)}}async function p(_){await l(e.wait?e.wait(_):gc(_,c.signal))}let m=0,h=0,y=t.length,b=!1,x=e.retries??3,g=e.payment,w="";if(g){let _=eE(g.header)?.resource?.url;if(typeof _!="string"||!Pf(_,e.url))throw new TypeError("the payment names another resource than the file URL");w=_}e.signal?.addEventListener("abort",d,{once:!0});let v=0,E,B=(_,I)=>(u(),l(a(e.url,{redirect:"error",credentials:"omit",signal:c.signal,headers:{..._,range:`bytes=${I}-`}}).then(async k=>(c.signal.aborted&&await k.body?.cancel().catch(()=>{}),k)))),N=_=>_.body&&(_.status===200||_.status===206);async function U(){let _=y,I=Pw(e.proof.secret,w||e.url,e.proof.purchase_id,e.proof.grant);for(let k=0;;k++){let M=await B({[kw]:I,...g?{"PAYMENT-SIGNATURE":g.header}:{}},_);if(c.signal.aborted&&(await M.body?.cancel().catch(()=>{}),u()),N(M))return{response:M,start:_};if(M.status===416&&_>t.length){await M.body?.cancel().catch(()=>{}),_=t.length;continue}let $=M.status===503||M.status===402||M.status===429,F=M.status===429?"rate_limited":M.status===503?"unavailable":"settlement_pending",A;if([429,403,503].includes(M.status)){let j=M.body?.getReader();try{let K=[],W=0;if(j)for(;;){let Z=await l(j.read());if(Z.done||(W+=Z.value.length,W>8192))break;K.push(Z.value)}if(W<=8192){let Z=new Uint8Array(W),te=0;for(let de of K)Z.set(de,te),te+=de.length;let J=JSON.parse(new TextDecoder().decode(Z));(M.status===429&&(J.error==="download_limited"||J.error==="download_in_progress")||M.status===403&&J.error==="not_sponsored"||M.status===503&&J.error==="relayer_unavailable")&&(F=J.error),typeof J.retryAfterSeconds=="number"&&Number.isFinite(J.retryAfterSeconds)&&J.retryAfterSeconds>=0&&Number.isSafeInteger(Math.ceil(J.retryAfterSeconds))&&(A=Math.ceil(J.retryAfterSeconds))}}catch{}finally{await j?.cancel().catch(()=>{})}}else await M.body?.cancel().catch(()=>{});let z=fs(M.headers.get("Retry-After"),(e.now?.()??Date.now()/1e3)*1e3);z!==void 0&&(A=Math.max(A??0,Math.ceil(z/1e3)));let D=()=>Object.assign(new $e(F),{fileId:e.fileId,purchaseId:e.proof.purchase_id,...A===void 0?{}:{retryAfterSeconds:A}});if(F==="download_limited"||F==="not_sponsored")throw D();if(!$)return wn("not_authorized",`the host answered ${M.status}`);let q=Math.max(1,A??(M.status===402?3:5))*1e3;if(k+1>=(e.settleTries??40)||q>60*1e3-m||q>60*1e3)throw D();m+=q,await p(q)}}async function R(){let{response:_,start:I}=await U(),k=Number(_.headers.get("content-length")??Number.NaN),M=Number((/\/(\d+)$/.exec(_.headers.get("content-range")??"")??[])[1]);try{i(_.status===200?k:I+k),_.status===206&&i(M)}catch(D){throw await _.body?.cancel().catch(()=>{}),D}let $=_.body.getReader(),F=_.status===200?0:I,A={cancel:()=>$.cancel(),async read(){let D=await $.read();if(u(),!D.done){F+=D.value.length;try{i(F)}catch(q){throw await $.cancel().catch(()=>{}),q}}return D}};if(O=A,_.status===200){let D=Number(_.headers.get("content-length")??Number.NaN);return E=Number.isSafeInteger(D)?D:void 0,v=y,{reader:A,rest:await Rw(A,y,t)}}let z=/^bytes (\d+)-(\d+)\/(\d+|\*)$/.exec(_.headers.get("content-range")??"");return!z||Number(z[1])!==I||Number(z[2])<I||z[3]!=="*"&&Number(z[2])>=Number(z[3])?(await A.cancel().catch(()=>{}),wn("bad_response","the host resumed from another offset")):(E=Number(z[2])+1,i(E),v=y,{reader:A,rest:I<y?await Rw(A,y-I,new Uint8Array(0)):new Uint8Array(0)})}let T,O,H=new Uint8Array(0);async function P(_,I){_=Math.min(_,Math.max(0,o-y)+1);let k=new Uint8Array(_),M=0;for(;M<_;){if(H.length===0&&!T){let F=await R();T=F.reader,H=F.rest}if(H.length===0){let F=await T.read();if(F.done){if(I&&(E===void 0||v>=E))break;throw new Error("the connection ended early")}H=F.value}let $=Math.min(_-M,H.length);k.set(H.subarray(0,$),M),H=H.subarray($),M+=$,v+=$}return k.subarray(0,M)}return new ReadableStream({async pull(_){if(u(),!b){b=!0,_.enqueue(We(t));return}for(;;)try{let I=h===r.n-1,k=await P(I?s+1:n[h],I);I&&(k.length<ve||k.length>s)&&wn("file_mismatch","the last chunk has a wrong length, or bytes follow it"),pt(await Oe(k),r.hashes[h])||wn("file_mismatch",`chunk ${h} is not the one the header names`),_.enqueue(k),h++,y+=k.length,I&&(f(),_.close(),await T?.cancel().catch(()=>{}));return}catch(I){if(await O?.cancel().catch(()=>{}),T=void 0,H=new Uint8Array(0),c.signal.aborted&&(f(),wn("cancelled")),I instanceof $e||x--<=0)throw c.abort(),f(),I}},async cancel(){c.abort(),f(),await O?.cancel().catch(()=>{})}},{highWaterMark:0})}async function Rw(e,t,r){let n=t;for(;;){let o=await e.read();if(o.done)throw new Error("the connection ended before the resume point");let i=t-n,s=Math.min(o.value.length,n,Math.max(0,r.length-i));if(pt(o.value.subarray(0,s),r.subarray(i,i+s))||wn("file_mismatch","the host sent another header"),o.value.length>=n)return o.value.subarray(n);n-=o.value.length}}function Cw(e,t,r){let n=e.startsWith("0x")?e.slice(2):e;if(!new RegExp(`^[0-9a-fA-F]{${2*t}}$`).test(n))throw new TypeError(`${r} must be ${t} bytes of hex`);return`0x${n.toLowerCase()}`}function Uw(e,t,r){if(e!==t.terms.contract)throw new TypeError("terms contract mismatch");return io(t.seller_key),Wa(t.terms,t.seller_key,t.deadline,r)}var Nw=e=>Rg(e);function Fw(e,t,r){return io(t.key??""),["Annon: open a file again","Signing this lets whoever holds the one-time key below open the file.",`contract: ${e}`,`file: ${Cw(t.file_id,32,"file_id")}`,`seller: ${Ke(r)}`,`one-time key: ${t.key}`,`valid until: ${Vn(t.deadline)}`].join(`
49
+ `)}function Mw(e,t,r){return["Annon: stop selling a file","Signing this is final: the file can't be sold again. Past buyers keep access.",`contract: ${e}`,`file: ${Cw(t.file_id,32,"file_id")}`,`seller: ${Ke(r)}`,`valid until: ${Vn(t.deadline)}`].join(`
50
+ `)}function im(e){if(G(e.file_id,32),G(e.nonce,32),_t(e.amount,128)<=0n||!Number.isSafeInteger(e.deadline)||e.deadline<0)throw new TypeError("Invalid file funding authorization.");return["Annon: request sponsored file storage",`network: ${e.network}`,`contract: ${e.contract}`,`seller: ${Ke(e.seller)}`,`file: ${e.file_id}`,`amount: ${e.amount}`,`nonce: ${e.nonce}`,`expires: ${e.deadline}`].join(`
51
+ `)}Dh();var l4=["eth","base","arb","arbitrum","op","optimism","polygon","pol","bera","scroll","monad","xlayer","abs","plasma","bsc","avax","avalanche","gnosis"];function p4(e){return l4.includes(e)?"evm":e==="sol"||e==="solana"?"solana":e==="near"?"near":"other"}function N6(e){let t=p4(e);if(t==="other")throw new TypeError("unsupported origin chain or purchase window");return t}function m4(e,t,r,n){if(e.filter(i=>i.assetId===t&&i.blockchain===r).length!==1)throw new TypeError("select an exact catalog asset and blockchain");let o=N6(r);return qh(o,n),{asset:t,blockchain:r,chain:o,refundTo:n,refundType:"ORIGIN_CHAIN"}}function qh(e,t){if(typeof t!="string"||!t||/\s/.test(t))throw new TypeError("invalid refund address");if(e==="evm"){if(!pe(t)||/^0x0{40}$/i.test(t))throw new TypeError("invalid EVM refund address")}else if(e==="solana"){if(!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(t)||Ct.decode(t).length!==32)throw new TypeError("invalid Solana refund address")}else if(e==="near")be(t);else if(e!=="other")throw new TypeError("unsupported refund chain family")}function jh(e){if(!e||typeof e.asset!="string"||!e.asset.startsWith("nep141:")||!e.asset.slice(7)||/\s/.test(e.asset))throw new TypeError("invalid origin asset");if(e.blockchain&&N6(e.blockchain)!==e.chain)throw new TypeError("origin chain family mismatch");if(e.depositMode!==void 0&&!["SIMPLE","MEMO"].includes(e.depositMode))throw new TypeError("invalid deposit mode");if(e.refundType!==void 0&&!["ORIGIN_CHAIN","INTENTS"].includes(e.refundType))throw new TypeError("invalid refund type");qh(e.chain,e.refundTo),e.refundType==="INTENTS"&&be(e.refundTo)}var nd=class extends S{constructor(r=0){super("transport","1Click transport unavailable");this.retryAfterMs=r;this.name="TransportError"}retryAfterMs},h4=["PENDING_DEPOSIT","KNOWN_DEPOSIT_TX","PROCESSING","SUCCESS","REFUNDED","FAILED","INCOMPLETE_DEPOSIT"],od=class extends S{code="quote_expired";constructor(){super("quote_expired","The 1Click quote expired. Run buy again."),this.name="OneClickQuoteExpired"}},Ll=class extends S{code="quote_refused";minimumAmountUsdc;constructor(t){super("quote_refused",t),this.name="OneClickRefused";let r=/^Amount is too low for bridge, try at least ([0-9]{1,39})[.]?$/i.exec(t);r?.[1]&&(this.minimumAmountUsdc=ct(r[1]))}};function y4(e){return typeof e=="string"&&(/^Amount is too low for bridge, try at least [0-9]{1,39}[.]?$/i.test(e)||/^(No routes found|No liquidity available|Amount is too low|Amount is too high|Unsupported (origin|destination) asset)[.]?$/i.test(e))}function b4(e,t){let r=t.quote;if(!r||r.amountOut!==e.amount||r.minAmountOut!==void 0&&_t(r.minAmountOut,128)<BigInt(e.amount))throw new Error("1Click quote has wrong output");let n=t.quoteRequest;if(!n||Object.entries(e).some(([o,i])=>n[o]!==i))throw new Error("1Click quoteRequest echo mismatch");if(typeof r.timeEstimate!="number"||!Number.isFinite(r.timeEstimate)||r.timeEstimate<0||r.timeEstimate>600)throw new Error("1Click delivery estimate exceeds purchase delivery window");if(typeof r.amountIn!="string"||_t(r.amountIn,128)===0n)throw new Error("invalid quote input amount");return{request:e,amountIn:r.amountIn,amountOut:e.amount,timeEstimate:r.timeEstimate}}var Fn=class{constructor(t={}){this.options=t}options;async request(t,r,n){n?.throwIfAborted();let o;try{o=await(this.options.fetch??fetch)(`${this.options.endpoint??"https://1click.chaindefuser.com/v0"}${t}`,{credentials:"omit",method:r===void 0?"GET":"POST",...r===void 0?{}:{headers:{"content-type":"application/json"},body:JSON.stringify(r)},signal:n?AbortSignal.any([n,AbortSignal.timeout(2e4)]):AbortSignal.timeout(2e4)})}catch{throw n?.throwIfAborted(),new nd}if(o.status===429||o.status>=500){let s=fs(o.headers.get("retry-after"),this.now()*1e3)??0;throw new nd(Math.max(0,Math.min(3e5,s||0)))}if(!o.ok){if(t==="/quote"&&o.status>=400&&o.status<500){let a=(await o.json().catch(()=>null))?.message;throw new Ll(y4(a)?a:"The 1Click quote was refused.")}throw new Error(`1Click HTTP ${o.status}`)}let i=await o.json();if(!i||typeof i!="object"||Array.isArray(i)&&t!=="/tokens")throw new Error("malformed 1Click response");return i}now(){return(this.options.now??(()=>Math.floor(Date.now()/1e3)))()}async tokens(t){let r=await this.request("/tokens",void 0,t);if(!Array.isArray(r))throw new Error("malformed token catalog");return r.filter(n=>!!n&&typeof n=="object"&&typeof n.assetId=="string"&&n.assetId.startsWith("nep141:")&&!!n.assetId.slice(7)&&typeof n.blockchain=="string"&&!!n.blockchain&&typeof n.symbol=="string"&&Number.isInteger(n.decimals)&&n.decimals>=0&&n.decimals<=255)}async preview(t,r,n={}){return this.quote(t,r,{...n,dry:!0})}async quote(t,r,n={}){let o=es(t);if(o.route!=="near-usdc"||o.asset!==Ki)throw new TypeError("1Click requires the NEAR USDC route");let i=(this.options.now??(()=>Math.floor(Date.now()/1e3)))(),s=Number(o.expires_at)-600;if(!Number.isSafeInteger(s)||s<=i)throw new Error("purchase expired or insufficient delivery window");jh(r);let a=r.refundType??"ORIGIN_CHAIN";a==="INTENTS"&&be(r.refundTo);let c=n.slippageTolerance??100;if(!Number.isInteger(c)||c<0||c>1e4)throw new TypeError("invalid slippage");let d={dry:n.dry??!1,swapType:"EXACT_OUTPUT",slippageTolerance:c,originAsset:r.asset,depositType:"ORIGIN_CHAIN",...r.depositMode?{depositMode:r.depositMode}:{},destinationAsset:`nep141:${Ki}`,amount:o.price,refundTo:r.refundTo,refundType:a,recipient:o.contract,recipientType:"DESTINATION_CHAIN",deadline:new Date(s*1e3).toISOString(),customRecipientMsg:t},f=await this.request("/quote",d,n.signal),u=b4(d,f);if(d.dry)return u;let l=f.quote,p=typeof l.deadline=="string"?Date.parse(l.deadline):NaN;if(!Number.isFinite(p)||p<s*1e3)throw new Error("1Click deposit address deadline expires before the deposit cutoff");if(typeof l.depositAddress!="string"||!l.depositAddress||l.depositAddress.length>256)throw new Error("quote has no deposit address");let m=l.depositMemo;if(r.depositMode==="MEMO"&&(typeof m!="string"||!m)||m!==void 0&&(typeof m!="string"||m.length>256||Array.from(m).some(y=>y.charCodeAt(0)<32)))throw new Error("invalid deposit memo");let h={address:l.depositAddress,amount:u.amountIn,asset:r.asset,chain:r.chain,...r.blockchain?{blockchain:r.blockchain}:{},depositBefore:d.deadline,purchaseExpiresAt:new Date(Number(o.expires_at)*1e3).toISOString(),...m===void 0?{}:{memo:m}};return{request:d,response:f,deposit:{...h,qrData:JSON.stringify(h)}}}async status(t,r={}){if(!t||t.length>256)throw new TypeError("invalid deposit address");let n=await this.request(`/status?depositAddress=${encodeURIComponent(t)}${r.memo===void 0?"":`&depositMemo=${encodeURIComponent(r.memo)}`}`,void 0,r.signal);if(!h4.includes(n.status))throw new Error("unknown 1Click status");return n}async poll(t,r={}){let n=r.maxPolls??1200;if(!Number.isInteger(n)||n<1)throw new TypeError("invalid poll count");let o=r.intervalMs??3e3;if(!Number.isFinite(o)||o<0||o>3e4)throw new TypeError("invalid poll interval");let i=r.checkpoint??{address:t,...r.memo===void 0?{}:{memo:r.memo},attempts:0,errors:0};if(i.address!==t||i.memo!==r.memo||!Number.isSafeInteger(i.attempts)||i.attempts<0||!Number.isSafeInteger(i.errors)||i.errors<0||i.nextPollAt!==void 0&&(!Number.isFinite(i.nextPollAt)||i.nextPollAt<0))throw new TypeError("invalid poll checkpoint");if(r.signal?.throwIfAborted(),i.lastStatus&&["SUCCESS","REFUNDED","FAILED"].includes(i.lastStatus.status))return await r.onProgress?.(structuredClone(i)),i.lastStatus;i.nextPollAt&&i.nextPollAt>this.now()*1e3&&await(this.options.wait??gc)(Math.min(3e5,i.nextPollAt-this.now()*1e3),r.signal);for(let s=0;s<n;s++){r.signal?.throwIfAborted();let a,c=o;try{a=await this.status(t,r)}catch(d){if(!Ua(d))throw d;c=Math.max(Math.min(3e4,o*2**Math.min(i.errors,8)),d instanceof nd?d.retryAfterMs:0)}if(i={...i,attempts:i.attempts+1,errors:a?0:i.errors+1,...a?{lastStatus:a}:{},nextPollAt:this.now()*1e3+c},await r.onProgress?.(structuredClone(i)),a&&["SUCCESS","REFUNDED","FAILED"].includes(a.status))return a;s+1<n&&await(this.options.wait??gc)(c,r.signal)}throw new S("settlement_pending","1Click status still pending")}};var it=e=>`annon/purchase/${e}`;function F6(e){if(!e.attempts.length)throw new TypeError("a purchase record has at least one attempt");return{block:Math.min(...e.attempts.map(t=>t.searchFromBlock)),validBefore:e.attempts.reduce((t,r)=>BigInt(r.validBefore)>t?BigInt(r.validBefore):t,0n)}}function M6(e,t){for(let r of[...e.attempts].reverse())if(r.payload&&BigInt(r.validBefore)>BigInt(t))return r.payload;return null}var on=e=>Array.from(crypto.getRandomValues(new Uint8Array(e)),t=>t.toString(16).padStart(2,"0")).join("");var ql="eip155:8453",z6="annon-exact";var Dl="payment-identifier";var H6="builder-code",g4="bc_lq0mq0v9";var w4=e=>e===void 0?[]:Array.isArray(e)?e:[e];var x4=new TextEncoder,v4=e=>{let t="";for(let r of x4.encode(e))t+=String.fromCharCode(r);return btoa(t)};function $6(e,t,r,n,o,i){let s=e.extensions?.[Dl],a=e.extensions?.[H6],c=w4(a?.info?.s),d={...a??{},info:{...a?.info??{},s:[...new Set([g4,...c])]}},f=e.extensions?.annon;zr(o,{baseUsdc:t.asset});let u={...f?.info??{},version:3,network:"near:mainnet",contract:o.contract,fileId:o.file_id,purchase:zr(o,{baseUsdc:t.asset}),purchase_id:bn(o,{baseUsdc:t.asset})};return v4(JSON.stringify({x402Version:2,...e.resource===void 0?{}:{resource:e.resource},accepted:t,payload:{signature:n,authorization:{from:r.from,to:r.to,value:r.value.toString(),validAfter:r.validAfter.toString(),validBefore:r.validBefore.toString(),nonce:r.nonce}},extensions:{...e.extensions??{},annon:{...f??{},info:u},...s&&i?{[Dl]:{...s,info:{...s.info,id:i}}}:{},[H6]:d}}))}var S4=180,E4=60,jl=e=>typeof e=="string"?e.toLowerCase():void 0,_4=e=>typeof e=="string"&&/^0x[0-9a-fA-F]{40}$/.test(e);async function L6(e,t,r,n,o){let i={fileId:n,cipherHash:o.cipherHash,seller:o.seller,...o.headerHash?{publishedHeaderHash:o.headerHash}:{}},s;try{s=await(t?rg:ni)(e,i,r)}catch(a){if(a instanceof Re)return ie("file_invalid",`the PAY2 file failed its check: ${a.code}`);throw a}return s.usable||ie("file_invalid","the PAY2 header has no key for this contract"),s}async function D6(e,t,r){let n=await ai(e,t,r);return n?(n.takenDown&&ie("taken_down",`the file was taken down (${n.takenDown})`),n.salesStoppedAt!==null&&ie("sales_stopped","the seller stopped selling this file"),n):ie("unknown_file","the file is not registered on the Annon contract")}async function q6(e){if(!/^0x[0-9a-f]{64}$/.test(e.fileId))throw new TypeError("fileId must be 0x and 32 bytes of lowercase hex");if(!_4(e.buyer))throw new TypeError("buyer must be a 0x EVM address");let t=e.buyer.toLowerCase(),r=e.paymentRequired,n=r?.resource?.url;(typeof n!="string"||!Pf(n,e.url))&&ie("bad_requirements","resource.url is not the URL that answered with this 402");let o=(Array.isArray(r?.accepts)?r.accepts:[]).filter(y=>y?.scheme===z6&&y?.network===ql),[i]=o;if(o.length!==1||!i)return ie("network_mismatch","no single Annon offer on Base");let s=i.extra??{},a=r.extensions?.annon?.info;a&&(a.contract!==e.contractId||jl(a.fileId)!==e.fileId)&&ie("file_mismatch","the payment request is for another Annon contract or file");let c=i.maxTimeoutSeconds;(!Number.isSafeInteger(c)||c<1)&&ie("bad_requirements","maxTimeoutSeconds must be a positive integer"),(typeof i.amount!="string"||!/^\d{1,78}$/.test(i.amount))&&ie("bad_requirements","amount must be a decimal string");let d=await D6(e.nearRpc,e.contractId,e.fileId);d.moderator!==null&&!(e.moderators??[]).includes(d.moderator)&&ie("unknown_moderator",`the file's moderator ${d.moderator} is not one you trust`);let f=await ao(e.nearRpc,e.contractId);if((d.terms.network!==f.network||d.terms.near.token!==f.nearUsdc||d.terms.base&&d.terms.base.usdc!==f.usdc)&&ie("network_mismatch"),!(e.pay2 instanceof Uint8Array))throw new TypeError("pay2 must be the PAY2 header bytes");let u=await L6(e.pay2,a?.public===!0,e.contractId,e.fileId,d);d.terms.base||ie("method_mismatch","the file has no Base route");let l=d.payTo;(jl(i.asset)!==f.usdc||s.name!=="USD Coin"||s.version!=="2")&&ie("token_mismatch","the payment request is not for USDC on Base");let p=s.assetTransferMethod;p!==void 0&&p!=="eip3009"&&ie("method_mismatch","the offer is not a plain Annon transfer");let m=s.paymentFlow;(a?.version!==3||i.extra?.nonceVersion!==2||m!=="upfront")&&ie("method_mismatch",`unsupported payment flow ${String(s.paymentFlow)}`),s.splits!==void 0&&!(Array.isArray(s.splits)&&s.splits.length===0)&&ie("method_mismatch","the offer splits the payment; Annon pays the registered pay_to only"),jl(i.payTo)!==l&&ie("recipient_mismatch","the payment request pays an address the registration does not"),BigInt(i.amount)!==d.price&&ie("price_mismatch","the payment request asks a different price than the registration"),d.price>e.maxPrice&&ie("price_above_max","the price is above your limit");let h=await lo(e.baseRpc);return await Ef(e.baseRpc,t,h.number)&&ie("smart_wallet_unsupported","the wallet is a contract or delegated (EIP-7702); pay from a plain account"),await Sf(e.baseRpc,f.usdc,t,h.number)<d.price&&ie("insufficient_balance","not enough USDC on Base"),{nearRpc:e.nearRpc,baseRpc:e.baseRpc,contractId:e.contractId,fileId:e.fileId,buyer:t,seller:d.seller,to:l,usdc:f.usdc,price:d.price,validity:Math.min(c,S4),file:d,paymentRequired:r,offer:i,header:u.header}}var A4=(e,t=e.attempts[0])=>({from:e.terms.buyer,to:e.terms.to,value:BigInt(e.terms.price),validAfter:0n,validBefore:BigInt(t.validBefore),nonce:e.terms.nonce});async function j6(e,t){if(jl(t.wallet.address)!==e.buyer)throw new TypeError("the wallet is not the buyer the quote was made for");let r=t.purchase,n=bn(r,{baseUsdc:e.usdc}),o=zr(r,{baseUsdc:e.usdc});if(r.route!=="base-usdc"||r.contract!==e.contractId||r.file_id!==e.fileId||r.terms_hash!==e.file.termsHash||r.price!==e.price.toString()||r.asset!==e.usdc||Ze(jt(t.buyerSecret).publicKeyBytes)!==r.buyer_key||BigInt(r.expires_at)<=BigInt(Math.floor(Date.now()/1e3)))throw new TypeError("purchase does not match the checked quote/key");let i=await lo(e.baseRpc),s=Math.floor(Date.now()/1e3);Math.abs(i.timestamp-s)>E4&&ie("transport","the Base RPC is not at the current time; its deadline would be wrong");let a=await D6(e.nearRpc,e.contractId,e.fileId);(a.termsHash!==e.file.termsHash||a.price!==e.price||a.payTo!==e.file.payTo||a.moderator!==e.file.moderator||a.cipherHash!==e.file.cipherHash)&&ie("price_mismatch","the registration changed since the quote; check it again"),await L6(e.header,!1,e.contractId,e.fileId,a);let c=await as(e.baseRpc,"finalized"),d=Math.min(i.timestamp,s),f={schemaVersion:2,recoveryProved:!1,payment:{route:"base",amountUsdc:ct(e.price),amountBaseUnits:e.price.toString(),asset:{symbol:"USDC",id:e.usdc},network:ql},id:n,purchase:r,message:o,buyerSecret:Ze(t.buyerSecret),quote:null,recovery:r.recovery,checkedHeaderHash:Ze(ur(e.header)),revision:0,terms:{network:ql,contractId:e.contractId,fileId:e.fileId,buyer:e.buyer,seller:e.seller,to:e.to,usdc:e.usdc,price:e.price.toString(),buyerKey:r.buyer_key,nonce:Qd(n),headerHash:Ze(ur(e.header)),cipherHash:e.file.cipherHash,moderator:e.file.moderator},attempts:[{attemptId:on(16),...e.paymentRequired.extensions?.[Dl]?{paymentId:`pay_${on(16)}`}:{},preparedAt:d,searchFromBlock:Math.min(c.number,i.number),validBefore:Math.min(d+e.validity,Number(r.expires_at)).toString(),paymentRequired:e.paymentRequired}]},u=it(n);await t.store.compareAndSet(u,null,f)||ie("purchase_open","this wallet has an open purchase of this file: follow its nextStep");let l=f.attempts[0],p=A4(f),m=await t.wallet.signTypedData(cw(e.usdc,p));(typeof m!="string"||wf(gf(e.usdc,p),m)!==e.buyer)&&ie("bad_signature","the wallet did not return a plain signature from the buyer");let h=$6(e.paymentRequired,e.offer,p,m,r,l.paymentId),y={...f,revision:1,attempts:[{...l,payload:h}]};if(!await t.store.compareAndSet(u,f,y)){let b=new re("store_conflict","the purchase changed while the wallet signed");throw b.purchase=f,b}try{await lw(e.baseRpc,e.usdc,p,m)}catch(b){throw b instanceof re&&(b.purchase=y),b}return{header:h,purchase:y}}var G6=(e,t)=>bw(e,{usdc:t.terms.usdc,to:t.terms.to,from:t.terms.buyer,nonce:t.terms.nonce,price:BigInt(t.terms.price),...F6(t)});async function V6(e,t){if(await so(t.nearRpc,e.purchase.contract,e.id))return{step:"claim_key",args:{purchase_id:e.id,grant:0}};if(e.purchase.route==="near-usdc")return{step:"wait"};let r=await G6(t.baseRpc,e);if(r.state==="pending"){let n=M6(e,Math.floor(Date.now()/1e3));return n?{step:"resend",header:n}:{step:"wait"}}if(r.state!=="paid"){if(e.paymentState!==r.state&&!await t.store.compareAndSet(it(e.id),e,{...e,revision:e.revision+1,paymentState:r.state}))throw new re("store_conflict");return{step:"buy"}}return{step:"unlock",args:{purchase:e.message,logs:r.logs,header:await mw(t.baseRpc,`0x${r.logs[0].block_hash}`)}}}var T4=65536,W6=30,Z6=new WeakMap,Y6=e=>JSON.stringify([e.deployment,e.file.terms,e.file.termsHash,e.file.salesStoppedAt,e.file.takenDown,e.relayer,e.baseRpc]),id=e=>(e.now??(()=>Math.floor(Date.now()/1e3)))(),Gl=(e,t)=>Number.isSafeInteger(e)&&e>=0&&Math.abs(t-e)<=W6,Qe=(e,t)=>Object.assign(new S(e),{code:e,...t===void 0?{}:{retryAfterSeconds:t}}),K6=e=>typeof e=="string"&&/^(0|[1-9][0-9]*)$/.test(e)&&e.length<=39&&BigInt(e)<2n**128n;function I4(e){let t=new URL(e);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw Qe("relayer_unavailable");return t.origin}async function k4(e){if(!e.body)throw Qe("relayer_unavailable");let t=e.body.getReader(),r=[],n=0;try{for(;;){let a=await t.read();if(a.done)break;if(n+=a.value.length,n>T4)throw Qe("relayer_unavailable");r.push(a.value)}}finally{await t.cancel().catch(()=>{})}let o=new Uint8Array(n),i=0;for(let a of r)o.set(a,i),i+=a.length;let s=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(o));if(!s||typeof s!="object"||Array.isArray(s))throw Qe("relayer_unavailable");return s}function Gh(e,t){if(!e)return!1;let r=Z6.get(e),n=id(t);return!!r&&r.binding===Y6(t)&&r.value===JSON.stringify(e)&&Gl(e.checkedAt,n)&&e.splitCheckedAt<=n&&Gl(e.splitCheckedAt,n)}async function Vh(e,t){if(!t)throw Qe("relayer_unavailable");let r=e.terms;if(!r.base||e.takenDown!==null||e.salesStoppedAt!==null||r.near.recipients.some(n=>n.identity.kind!=="evm"))throw Qe("not_sponsored");try{await Ew(t,r.base.pay_to,{recipients:r.near.recipients.map(n=>n.identity.id),allocations:r.near.recipients.map(n=>BigInt(n.bps)),totalAllocation:10000n,distributionIncentive:0})}catch(n){throw n instanceof re&&n.code==="network_mismatch"?n:Qe(n instanceof re&&!Ua(n)?"not_sponsored":"relayer_unavailable")}}async function Kh(e){if(!e.relayer)throw Qe("transport_required");let t;try{let r=I4(e.relayer),n=e.deployment,o=e.file.terms;if(o.near.recipients.some(u=>u.identity.kind!=="evm")||o.network!==n.network||o.contract!==n.contractId||o.near.token!==n.nearUsdc||o.base?.usdc!==n.baseUsdc||tt(o,{nearUsdc:n.nearUsdc,baseUsdc:n.baseUsdc})!==e.file.termsHash)throw Qe("not_sponsored");let i=e.fetch??globalThis.fetch,s=async(u,l)=>{let p=await i(new URL(u,r),{redirect:"error",credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(2e4),...l?{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(l)}:{}}),m=fs(p.headers.get("Retry-After"),id(e)*1e3);if(m!==void 0&&(t=Math.max(1,Math.ceil(m/1e3))),!p.ok)throw await p.body?.cancel(),Qe("relayer_unavailable",t);return k4(p)},a=await s("/v1/capabilities");if(a.network!==n.network||a.contract!==n.contractId||a.nearUsdc!==n.nearUsdc||a.baseUsdc!==n.baseUsdc||!Array.isArray(a.methods)||!a.methods.includes("unlock")||typeof a.disabled!="boolean"||typeof a.baseSponsorship!="boolean"||typeof a.acceptingNewBasePayments!="boolean")throw Qe("relayer_unavailable");if(a.disabled||!a.baseSponsorship||!a.acceptingNewBasePayments)throw Qe("relayer_unavailable",t??5);let c=await s("/v1/base-eligibility",{fileId:o.file_id,termsHash:e.file.termsHash});if(c.network!==n.network||c.contract!==n.contractId||c.fileId!==o.file_id||c.termsHash!==e.file.termsHash||typeof c.eligible!="boolean")throw Qe("relayer_unavailable");if(!c.eligible)throw Qe("not_sponsored");if(!["listed","pool","legacy","external"].includes(String(c.tier))||typeof c.policyVersion!="string"||!c.policyVersion||!K6(c.minPrice)||!c.fee||typeof c.fee!="object"||!Gl(c.checkedAt,id(e))||!Number.isSafeInteger(c.decidedAt)||c.decidedAt<0||c.decidedAt>c.checkedAt)throw Qe("relayer_unavailable");let d=c.fee;if(!K6(d.fixed)||!Number.isSafeInteger(d.bps)||d.bps<0||d.bps>1e4||!Object.hasOwn(d,"treasuryNear")||!Object.hasOwn(d,"treasuryEvm"))throw Qe("relayer_unavailable");try{if(!o.base||BigInt(o.base.price)<BigInt(c.minPrice))throw new Error;po(o,d)}catch{throw Qe("not_sponsored")}await Vh(e.file,e.baseRpc);let f={network:n.network,contract:n.contractId,fileId:o.file_id,termsHash:e.file.termsHash,eligible:!0,tier:c.tier,policyVersion:c.policyVersion,minPrice:c.minPrice,fee:{fixed:d.fixed,bps:d.bps,treasuryNear:d.treasuryNear===null?null:ne(d.treasuryNear),treasuryEvm:d.treasuryEvm===null?null:ne(d.treasuryEvm)},decidedAt:c.decidedAt,checkedAt:c.checkedAt,splitCheckedAt:id(e)};if(!Gl(f.checkedAt,id(e)))throw Qe("relayer_unavailable");return Z6.set(f,{binding:Y6(e),value:JSON.stringify(f)}),f}catch(r){throw r&&typeof r=="object"&&"code"in r&&["not_sponsored","relayer_unavailable","network_mismatch"].includes(String(r.code))?r:Qe("relayer_unavailable",t)}}le();le();var rp=class extends L{constructor(t){super(`Call bundle failed with status: ${t.statusCode}`,{name:"BundleFailedError"}),Object.defineProperty(this,"result",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.result=t}};vt();Ql();ny();Tl();ll();_r();Eo();Qf();Bt();rd();Ye();le();fl();Si();or();Bt();xe();ed();dd();var sy="0x5792579257925792579257925792579257925792579257925792579257925792",ay=V(0,{size:32});async function np(e,t){let{account:r=e.account,chain:n=e.chain,experimental_fallback:o,experimental_fallbackDelay:i=32,forceAtomic:s=!1,id:a,version:c="2.0.0"}=t,d=r?ce(r):null,f=t.capabilities;e.dataSuffix&&!t.capabilities?.dataSuffix&&(typeof e.dataSuffix=="string"?f={...t.capabilities,dataSuffix:{value:e.dataSuffix,optional:!0}}:f={...t.capabilities,dataSuffix:{value:e.dataSuffix.value,...e.dataSuffix.required?{}:{optional:!0}}});let u=t.calls.map(l=>{let p=l,m=p.abi?Yt({abi:p.abi,functionName:p.functionName,args:p.args}):p.data;return{data:p.dataSuffix&&m?Er([m,p.dataSuffix]):m,to:p.to,value:p.value?V(p.value):void 0}});try{let l=await e.request({method:"wallet_sendCalls",params:[{atomicRequired:s,calls:u,capabilities:f,chainId:V(n.id),from:d?.address,id:a,version:c}]},{retryCount:0});return typeof l=="string"?{id:l}:l}catch(l){let p=l;if(o&&(p.name==="MethodNotFoundRpcError"||p.name==="MethodNotSupportedRpcError"||p.name==="UnknownRpcError"||p.details.toLowerCase()==="this request method is not supported"||p.details.toLowerCase().includes("does not exist / is not available")||p.details.toLowerCase().includes("missing or invalid. request()")||p.details.toLowerCase().includes("did not match any variant of untagged enum")||p.details.toLowerCase().includes("account upgraded to unsupported contract")||p.details.toLowerCase().includes("eip-7702 not supported")||p.details.toLowerCase().includes("unsupported wc_ method")||p.details.toLowerCase().includes("feature toggled misconfigured")||p.details.toLowerCase().includes("jsonrpcengine: response has no error or result for request"))){if(f&&Object.values(f).some(b=>!b.optional)){let b="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new Ro(new L(b,{details:b}))}if(s&&u.length>1){let y="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new Oo(new L(y,{details:y}))}let m=[];for(let y of u){try{let b=await zo(e,{account:d,chain:n,data:y.data,to:y.to,value:y.value?De(y.value):void 0});m.push({status:"fulfilled",value:b})}catch(b){m.push({reason:b,status:"rejected"})}i>0&&await new Promise(b=>setTimeout(b,i))}if(m.every(y=>y.status==="rejected"))throw m[0].reason;let h=m.map(y=>y.status==="fulfilled"?y.value:ay);return{id:Er([...h,V(n.id,{size:32}),sy])}}throw No(l,{...t,account:d,chain:t.chain})}}async function op(e,t){async function r(f){if(f.endsWith(sy.slice(2))){let l=Vr(vu(f,-64,-32)),p=vu(f,0,-64).slice(2).match(/.{1,64}/g),m=await Promise.all(p.map(y=>ay.slice(2)!==y?e.request({method:"eth_getTransactionReceipt",params:[`0x${y}`]},{dedupe:!0}):void 0)),h=m.some(y=>y===null)?100:m.every(y=>y?.status==="0x1")?200:m.every(y=>y?.status==="0x0")?500:600;return{atomic:!1,chainId:Xe(l),receipts:m.filter(Boolean),status:h,version:"2.0.0"}}return e.request({method:"wallet_getCallsStatus",params:[f]})}let{atomic:n=!1,chainId:o,receipts:i,version:s="2.0.0",...a}=await r(t.id),[c,d]=(()=>{let f=a.status;return f>=100&&f<200?["pending",f]:f>=200&&f<300?["success",f]:f>=300&&f<700?["failure",f]:f==="CONFIRMED"?["success",200]:f==="PENDING"?["pending",100]:[void 0,f]})();return{...a,atomic:n,chainId:o?Xe(o):void 0,receipts:i?.map(f=>({...f,blockNumber:De(f.blockNumber),gasUsed:De(f.gasUsed),status:zh[f.status]}))??[],statusCode:d,status:c,version:s}}var s5=new WeakMap,C4=0;function a5(e){let t=s5.get(e);return t===void 0&&(t=++C4,s5.set(e,t)),t}async function ip(e,t){let{id:r,pollingInterval:n=e.pollingInterval,status:o=({statusCode:h})=>h===200||h>=300,retryCount:i=4,retryDelay:s=({count:h})=>~~(1<<h)*200,timeout:a=6e4,throwOnFailure:c=!1}=t,d=qe(["waitForCallsStatus",e.uid,r,{pollingInterval:n,retryCount:i,retryDelay:typeof t.retryDelay=="function"?["function",a5(t.retryDelay)]:t.retryDelay,status:t.status?a5(t.status):void 0,throwOnFailure:c}]),{promise:f,resolve:u,reject:l}=va(),p,m=Hi(d,{resolve:u,reject:l},h=>{let y=ep(async()=>{let b=x=>{clearTimeout(p),y(),x(),m()};try{let x=await Ni(async()=>{let g=await oe(e,op,"getCallsStatus")({id:r});if(c&&g.status==="failure")throw new rp(g);return g},{retryCount:i,delay:s});if(!o(x))return;b(()=>h.resolve(x))}catch(x){b(()=>h.reject(x))}},{interval:n,emitOnBegin:!0});return y});return p=a?setTimeout(()=>{m(),clearTimeout(p),l(new cy({id:r}))},a):void 0,await f.finally(()=>m())}var cy=class extends L{constructor({id:t}){super(`Timed out while waiting for call bundle with id "${t}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}};Ye();var sp=256,ap;function cp(e=11){if(!ap||sp+e>256*2){ap="",sp=0;for(let t=0;t<256;t++)ap+=(256+Math.random()*256|0).toString(16).substring(1)}return ap.substring(sp,sp+++e)}function f5(e){let{batch:t,chain:r,ccipRead:n,dataSuffix:o,key:i="base",name:s="Base Client",tokens:a,type:c="base"}=e,d=e.experimental_blockTag??(typeof r?.experimental_preconfirmationTime=="number"?"pending":void 0),f=r?.blockTime??12e3,u=Math.min(Math.max(Math.floor(f/2),500),4e3),l=e.pollingInterval??u,p=e.cacheTime??l,m=e.account?ce(e.account):void 0,{config:h,request:y,value:b}=e.transport({account:m,chain:r,pollingInterval:l}),x={...h,...b},g={account:m,batch:t,cacheTime:p,ccipRead:n,chain:r,dataSuffix:o,key:i,name:s,pollingInterval:l,request:y,tokens:a,transport:x,type:c,uid:cp(),...d?{experimental_blockTag:d}:{}};return u5(g)}var c5=new WeakSet,U4=0;function u5(e){function t(n,o){return i=>{let s=i(n);for(let f in e)f!=="scope"&&delete s[f];let a={...n,...s};for(let f in s){let u=n[f],l=s[f];d5(u)&&d5(l)&&(a[f]={...u,...l})}let c=[...o,i],{scope:d}=a;return Object.assign(a,{extend:t(a,c),scope:typeof d=="function"&&c5.has(d)?r(c):d})}}function r(n){let o=new WeakMap,i=(s={})=>{let a=s.signal&&o.get(s.signal);if(a)return a;let c=`scope.${U4++}`,d=new AbortController,{signal:f}=s;f?.aborted?d.abort(f.reason):f?.addEventListener("abort",()=>d.abort(f.reason),{once:!0});let u=(p,m)=>e.request(p,{...m,signal:m?.signal??d.signal,uid:m?.uid??c}),l=n.reduce((p,m)=>p.extend(m),u5({...e,request:u,uid:c}));return f&&o.set(f,l),l};return c5.add(i),i}return Object.assign(e,{extend:t(e,[]),scope:r([])})}function d5(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ud(e,t){let r=(n={})=>t(e,n);for(let n of["call","calls","callWithPeriod","estimateGas","prepare","prepareRecipient","predict","simulate"])if(Object.hasOwn(t,n)){let o=t[n];r[n]=(i={})=>o.length===1?o(i):o(e,i)}for(let n of["extractEvent","extractEvents"])Object.hasOwn(t,n)&&(r[n]=t[n]);return r}Jc();Dm();ey();ty();fd();ld();async function Hn(e,t){return Hn.inner(Br,e,t)}(function(e){async function t(s,a,c){return await s(a,{...c,...e.call(a,c)})}e.inner=t;function r(s,a){return lp($4(s,a))}e.call=r;async function n(s,a){return Yl(s,{...ka(a),...e.call(s,a)})}e.estimateGas=n;async function o(s,a){return Xl(s,{...ka(a),...e.call(s,a)})}e.simulate=o;function i(s){let[a]=Pu({abi:Fi,logs:s,eventName:"Approval",strict:!0});if(!a)throw new Error("`Approval` event not found.");return a}e.extractEvent=i})(Hn||(Hn={}));function $4(e,t){let{amount:r,spender:n,token:o}=t,{address:i,decimals:s}=$o(e,{token:o});return{abi:Fi,address:i,args:[n,fp(r,s)],functionName:"approve"}}Lh();hp();ld();async function py(e,t){let{amount:r,token:n,throwOnReceiptRevert:o=!0}=t,{decimals:i}=$o(e,{token:n}),s=up(r,i),a=await Hn.inner(Ba,e,{...t,throwOnReceiptRevert:o}),{args:c}=Hn.extractEvent(a.logs);return{...c,...s===void 0?{}:{decimals:s,formatted:$l(c.value,s)},receipt:a}}Jc();Dm();ey();ty();fd();ld();async function zn(e,t){return zn.inner(Br,e,t)}(function(e){async function t(s,a,c){return await s(a,{...c,...e.call(a,c)})}e.inner=t;function r(s,a){return lp(L4(s,a))}e.call=r;async function n(s,a){return Yl(s,{...ka(a),...e.call(s,a)})}e.estimateGas=n;async function o(s,a){return Xl(s,{...ka(a),...e.call(s,a)})}e.simulate=o;function i(s){let[a]=Pu({abi:Fi,logs:s,eventName:"Transfer",strict:!0});if(!a)throw new Error("`Transfer` event not found.");return a}e.extractEvent=i})(zn||(zn={}));function L4(e,t){let{amount:r,from:n,to:o,token:i}=t,{address:s,decimals:a}=$o(e,{token:i}),c=fp(r,a);return n?{abi:Fi,address:s,args:[n,o,c],functionName:"transferFrom"}:{abi:Fi,address:s,args:[o,c],functionName:"transfer"}}Lh();hp();ld();async function my(e,t){let{amount:r,token:n,throwOnReceiptRevert:o=!0}=t,{decimals:i}=$o(e,{token:n}),s=up(r,i),a=await zn.inner(Ba,e,{...t,throwOnReceiptRevert:o}),{args:c}=zn.extractEvent(a.logs);return{...c,...s===void 0?{}:{decimals:s,formatted:$l(c.value,s)},receipt:a}}Xh();Mo();xe();async function w5(e,{chain:t}){let{id:r,name:n,nativeCurrency:o,rpcUrls:i,blockExplorers:s}=t;await e.request({method:"wallet_addEthereumChain",params:[{chainId:V(r),chainName:n,nativeCurrency:o,rpcUrls:i.default.http,blockExplorerUrls:s?Object.values(s).map(({url:a})=>a):void 0}]},{dedupe:!0,retryCount:0})}Fm();dd();function x5(e,t){let{abi:r,args:n,bytecode:o,...i}=t,s=Nc({abi:r,args:n,bytecode:o});return zo(e,{...i,...i.authorizationList?{to:null}:{},data:s})}ms();async function v5(e){return e.account?.type==="local"?[e.account.address]:(await e.request({method:"eth_accounts"},{dedupe:!0})).map(r=>_n(r))}Ye();xe();async function S5(e,t={}){let{account:r=e.account,chainId:n}=t,o=r?ce(r):void 0,i=n?[o?.address,[V(n)]]:[o?.address],s=await e.request({method:"wallet_getCapabilities",params:i}),a={};for(let[c,d]of Object.entries(s)){a[Number(c)]={};for(let[f,u]of Object.entries(d))f==="addSubAccount"&&(f="unstable_addSubAccount"),a[Number(c)][f]=u}return typeof n=="number"?a[n]:a}async function E5(e){return await e.request({method:"wallet_getPermissions"},{dedupe:!0})}Ye();Mn();Ei();vt();Mo();$h();async function yp(e,t){let{account:r=e.account,chainId:n,nonce:o}=t;if(!r)throw new st({docsPath:"/docs/eip7702/prepareAuthorization"});let i=ce(r),s=(()=>{if(t.executor)return t.executor==="self"?t.executor:ce(t.executor)})(),a={address:t.contractAddress??t.address,chainId:n,nonce:o};return typeof a.chainId>"u"&&(a.chainId=e.chain?.id??await oe(e,Dt,"getChainId")({})),typeof a.nonce>"u"&&(a.nonce=await oe(e,Nl,"getTransactionCount")({address:i.address,blockTag:"pending"}),(s==="self"||s?.address&&Ht(s.address,i.address))&&(a.nonce+=1)),a}cd();ms();async function _5(e){return(await e.request({method:"eth_requestAccounts"},{dedupe:!0,retryCount:0})).map(r=>$1(r))}async function A5(e,t){return e.request({method:"wallet_requestPermissions",params:[t]},{retryCount:0})}vt();async function T5(e,t){let{chain:r=e.chain}=t,n=t.timeout??Math.max((r?.blockTime??0)*3,5e3),o=await oe(e,np,"sendCalls")(t);return await oe(e,ip,"waitForCallsStatus")({...t,id:o.id,timeout:n})}oy();fy();dd();ly();async function I5(e,t){let{id:r}=t;await e.request({method:"wallet_showCallsStatus",params:[r]})}Ye();Mn();async function k5(e,t){let{account:r=e.account}=t;if(!r)throw new st({docsPath:"/docs/eip7702/signAuthorization"});let n=ce(r);if(!n.signAuthorization)throw new ar({docsPath:"/docs/eip7702/signAuthorization",metaMessages:["The `signAuthorization` Action does not support JSON-RPC Accounts."],type:n.type});let o=await yp(e,t);return n.signAuthorization(o)}Ye();Mn();xe();async function B5(e,{account:t=e.account,message:r}){if(!t)throw new st({docsPath:"/docs/actions/wallet/signMessage"});let n=ce(t);if(n.signMessage)return n.signMessage({message:r});let o=typeof r=="string"?_c(r):r.raw instanceof Uint8Array?ht(r.raw):r.raw;return e.request({method:"personal_sign",params:[o,n.address]},{retryCount:0})}Ye();Mn();Ol();xe();Mi();vt();Uo();Mo();async function P5(e,t){let{account:r=e.account,chain:n=e.chain,...o}=t;if(!r)throw new st({docsPath:"/docs/actions/wallet/signTransaction"});let i=ce(r);Lt({account:i,...t});let s=await oe(e,Dt,"getChainId")({});n!==null&&Sa({currentChainId:s,chain:n});let c=(n?.formatters||e.chain?.formatters)?.transactionRequest?.format||sr;return i.signTransaction?i.signTransaction({...o,account:i,chainId:s},{serializer:e.chain?.serializers?.transaction}):await e.request({method:"eth_signTransaction",params:[{...c({...o,account:i},"signTransaction"),chainId:V(s),from:i.address}]},{retryCount:0})}Ye();Mn();O6();async function R5(e,t){let{account:r=e.account,domain:n,message:o,primaryType:i}=t;if(!r)throw new st({docsPath:"/docs/actions/wallet/signTypedData"});let s=ce(r),a={EIP712Domain:R6({domain:n}),...t.types};if(P6({domain:n,message:o,primaryType:i,types:a}),s.signTypedData)return s.signTypedData({domain:n,message:o,primaryType:i,types:a});let c=B6({domain:n,message:o,primaryType:i,types:a});return e.request({method:"eth_signTypedData_v4",params:[s.address,c]},{retryCount:0})}xe();async function O5(e,{id:t}){await e.request({method:"wallet_switchEthereumChain",params:[{chainId:V(t)}]},{retryCount:0})}async function C5(e,t){return await e.request({method:"wallet_watchAsset",params:t},{retryCount:0})}fd();hp();function U5(e){return{addChain:t=>w5(e,t),deployContract:t=>x5(e,t),fillTransaction:t=>Wl(e,t),getAddresses:()=>v5(e),getCallsStatus:t=>op(e,t),getCapabilities:t=>S5(e,t),getChainId:()=>Dt(e),getPermissions:()=>E5(e),prepareAuthorization:t=>yp(e,t),prepareTransactionRequest:t=>Ho(e,t),requestAddresses:()=>_5(e),requestPermissions:t=>A5(e,t),sendCalls:t=>np(e,t),sendCallsSync:t=>T5(e,t),sendRawTransaction:t=>tp(e,t),sendRawTransactionSync:t=>pp(e,t),sendTransaction:t=>zo(e,t),sendTransactionSync:t=>mp(e,t),showCallsStatus:t=>I5(e,t),signAuthorization:t=>k5(e,t),signMessage:t=>B5(e,t),signTransaction:t=>P5(e,t),signTypedData:t=>R5(e,t),switchChain:t=>O5(e,t),waitForCallsStatus:t=>ip(e,t),watchAsset:t=>C5(e,t),writeContract:t=>Br(e,t),writeContractSync:t=>Ba(e,t),token:{approve:ud(e,Hn),approveSync:ud(e,py),transfer:ud(e,zn),transferSync:ud(e,my)}}}function hy(e){let{key:t="wallet",name:r="Wallet Client",transport:n}=e;return f5({...e,key:t,name:r,transport:n,type:"walletClient"}).extend(U5)}M2();function N5({key:e,methods:t,name:r,request:n,retryCount:o=3,retryDelay:i=150,timeout:s,type:a},c){let d=cp();return{config:{key:e,methods:t,name:r,request:n,retryCount:o,retryDelay:i,timeout:s,type:a},request:F2(n,{methods:t,retryCount:o,retryDelay:i,uid:d}),value:c}}function yy(e,t={}){let{key:r="custom",methods:n,name:o="Custom Provider",retryDelay:i}=t;return({retryCount:s})=>N5({key:r,methods:n,name:o,request:e.request.bind(e),retryCount:t.retryCount??s,retryDelay:i,type:"custom"})}var F5={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}};Bt();Hh();_a();rd();var M5={block:T6({format(e){return{transactions:e.transactions?.map(r=>{if(typeof r=="string")return r;let n=Nn(r);return n.typeHex==="0x7e"&&(n.isSystemTx=r.isSystemTx,n.mint=r.mint?De(r.mint):void 0,n.sourceHash=r.sourceHash,n.type="deposit"),n}),stateRoot:e.stateRoot}}}),transaction:A6({format(e){let t={};return e.type==="0x7e"&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?De(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}}),transactionReceipt:I6({format(e){return{...e.depositNonce?{depositNonce:De(e.depositNonce)}:{},...e.depositReceiptVersion?{depositReceiptVersion:Xe(e.depositReceiptVersion)}:{},l1GasPrice:e.l1GasPrice?De(e.l1GasPrice):null,l1GasUsed:e.l1GasUsed?De(e.l1GasUsed):null,l1Fee:e.l1Fee?De(e.l1Fee):null,l1FeeScalar:e.l1FeeScalar?Number(e.l1FeeScalar):null}}})};Gr();Zt();or();xe();Ru();Eh();function D4(e,t){return j4(e)?q4(e):P2(e,t)}var H5={transaction:D4};function q4(e){G4(e);let{sourceHash:t,data:r,from:n,gas:o,isSystemTx:i,mint:s,to:a,value:c}=e,d=[t,n,a??"0x",s?ht(s):"0x",c?ht(c):"0x",o?ht(o):"0x",i?"0x1":"0x",r??"0x"];return Le(["0x7e",Ar(d)])}function j4(e){return e.type==="deposit"||typeof e.sourceHash<"u"}function G4(e){let{from:t,to:r}=e;if(t&&!pe(t))throw new Ce({address:t});if(r&&!pe(r))throw new Ce({address:r})}var by={blockTime:2e3,contracts:F5,formatters:M5,serializers:H5};v6();var pd=1,bp=Nh({...by,id:8453,name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://basescan.org",apiUrl:"https://api.basescan.org/api"}},contracts:{...by.contracts,disputeGameFactory:{[pd]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[pd]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[pd]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[pd]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:pd}),V4=Nh({...bp,experimental_preconfirmationTime:200,rpcUrls:{default:{http:["https://mainnet-preconf.base.org"]}}});function z5(e,t){let r="provider"in e?e.provider:e,n=ne({kind:"evm",id:t}),o=hy({chain:bp,transport:yy(r)}),i=async()=>{let s=await r.request({method:"eth_accounts"});if(!Array.isArray(s)||!s.some(a=>typeof a=="string"&&a.toLowerCase()===n.id))throw new S("wrong_identity","wallet does not control the selected identity")};return{identity:n,address:n.id,async authorize(s){await i();let c={kind:"evm",sig:await o.signMessage({account:n.id,message:s})};if(!lt(n,s,c))throw new S("invalid_signature","wallet signature does not match identity");return c},async signTypedData(s){return await i(),o.signTypedData({...s,account:n.id})}}}function K4(e,t,r,n){return{identity:ne({kind:"near",id:e}),...n?{proveControl:n}:{},async authorize(i){await t()},async call(i){return await t(),r(i)},async transferPurchase(i,s){let a=es(i,s);if(a.route!=="near-usdc")throw new TypeError("not a NEAR USDC purchase");if(BigInt(a.expires_at)<=BigInt(Math.floor(Date.now()/1e3)))throw new S("payment_expired","purchase expired");return await t(),r({receiverId:a.asset,method:"ft_transfer_call",args:{receiver_id:a.contract,amount:a.price,msg:i},gas:150000000000000n,deposit:1n})}}}function $5(e,t,r){return K4(t,async()=>{if(!(await e.getAccounts()).some(n=>n.accountId===t))throw new S("wrong_identity","wallet does not control the NEAR account")},n=>e.signAndSendTransaction({signerId:t,receiverId:n.receiverId,actions:[{type:"FunctionCall",params:{methodName:n.method,args:n.args,gas:String(n.gas??300000000000000n),deposit:String(n.deposit??0n)}}]}),r??((n,o)=>{if(!e.signMessage)throw new S("missing_method","NEAR recovery requires NEP-413 signMessage");return rf(t,n,o,i=>e.signMessage?.(i)??Promise.resolve(void 0))}))}var zi=class extends S{code="funding_refused";constructor(){super("funding_refused","File funding was refused."),this.name="FileFundingRefused"}};async function gy(e,t,r,n,o=!1){if(n<=0n||n>=2n**128n||!/^0x[0-9a-f]{64}$/.test(r))throw new RangeError("invalid file funding");let i={receiverId:be(t),method:"fund_file_storage",args:{file_id:r,amount:n.toString()},deposit:o?0n:n,gas:30000000000000n},s=c=>{if(!c||typeof c!="object"||!("transaction"in c))return!1;try{let d=c.transaction;return ci(c,t,{txHash:d.hash,signer:d.signer_id,method:i.method,args:i.args}).state==="refused"}catch{return!1}},a;try{a=await e.call(i)}catch(c){throw c&&typeof c=="object"&&"transactionResult"in c&&s(c.transactionResult)?new zi:c}if(s(a))throw new zi;return a}var Lo=e=>{if(e.identity.kind!=="near"||!("call"in e)||typeof e.call!="function")throw new S("near_wallet_required","a NEAR transaction wallet is required");return e},L5=e=>({nearUsdc:e.near.token,...e.base?{baseUsdc:e.base.usdc}:{}}),gp=(e,t)=>({fileId:e,cipherHash:t.cipherHash,seller:t.seller,...t.headerHash?{publishedHeaderHash:t.headerHash}:{}}),Do=class extends S{constructor(r,n){let o=n?.cause,i=o instanceof S||o instanceof br?o.code:"sell_incomplete";super(i,o instanceof Error?o.message:"Sell incomplete; resume with fileId.",n);this.fileId=r;this.name="SellError";let s=Ko(o);s.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=s.retryAfterSeconds),o instanceof S&&"txHash"in o&&typeof o.txHash=="string"&&(this.txHash=o.txHash)}fileId;txHash;retryAfterSeconds},$i=class{constructor(t){this.o=t;be(t.contractId),Gn(t.network),this.hosted=new Bf(t,{config:()=>ao(t.nearRpc,t.contractId),file:r=>ai(t.nearRpc,t.contractId,r),call:(r,n,o)=>this.call(r,n,o),answer:(r,n,o)=>this.answer(r,n,o),reopen:(r,n)=>this.reopenSeller({fileId:r,seller:n})}),this.store=this.withBackup(mi(t.rawStore,t.backupSecret),r=>pf(r,t.backupSecret)),this.sellerKeys=this.withBackup(tw(t.rawStore,t.backupSecret),r=>W0(r,t.backupSecret)),this.sells=this.withBackup(hf(t.rawStore,t.backupSecret),r=>gn(r,t.backupSecret)),this.recoveries=this.withBackup(lc(t.rawStore,t.backupSecret),r=>is(r,t.backupSecret))}o;store;hosted;sellerKeys;sells;recoveries;selfUnlockWallets=new Map;unlocked=new Map;withBackup(t,r){return{load:n=>t.load(n),compareAndSet:async(n,o,i)=>{let s=await t.compareAndSet(n,o,i);return s&&i&&await this.o.writeBackup(i.id,await r(i)),s}}}now(){return(this.o.now??(()=>Math.floor(Date.now()/1e3)))()}async auth(t,r){let n=ne(t.identity),o=await t.authorize(r);if(!lt(n,r,o,n.kind==="near"?n.id:void 0))throw new S("invalid_signature","wallet did not authorize the exact text");return o}async call(t,r,n){let o=n?.identity.kind==="near"?Lo(n):void 0,i=this.o.send?await this.o.send(t,r,o):o?await o.call({receiverId:this.o.contractId,method:t,args:r}):(()=>{throw new S("transport_required","configure a transaction transport for relayed calls")})();if(i&&typeof i=="object"&&"transaction"in i){let s=i.transaction,a=ci(i,this.o.contractId,{txHash:s.hash,signer:s.signer_id,method:t,args:t==="fund_file_storage"?{file_id:r.args.file_id,amount:r.args.amount}:t==="register"?Object.fromEntries(Object.entries(r).filter(([c])=>c!=="baseSplit"&&c!=="hostingReservation")):r});if(a.state==="released")return a.answer;if(a.state==="done")return a.value;throw Fg("reason"in a?a.reason:"")?new re("storage_required"):new S(a.state==="pending"?"settlement_pending":"refused")}return i}async fund(t,r,n,o={}){if(G(t,32),r<=0n||r>=2n**128n)throw new re("bad_requirements");let i=await ai(this.o.nearRpc,this.o.contractId,t);if(!i)throw new re("unknown_file");if(i.terms.network!==this.o.network||i.terms.contract!==this.o.contractId)throw new re("network_mismatch");if(Q(ne(n.identity))!==Q(i.seller))throw new re("wrong_identity");if(i.takenDown!==null)throw new re("taken_down");if(i.salesStoppedAt!==null)throw new re("sales_stopped");if(n.identity.kind==="near")return gy(Lo(n),this.o.contractId,t,r);let s=o.deadline??this.now()+600;if(!Number.isSafeInteger(s)||s<=this.now()||s>this.now()+600)throw new re("bad_requirements");let a={file_id:t,amount:String(r),nonce:o.nonce??`0x${on(32)}`,deadline:s},c=im({...a,network:this.o.network,contract:this.o.contractId,seller:i.seller}),d=await this.auth(n,c);return this.call("fund_file_storage",{args:a,auth:d},n)}async answer(t,r,n){let o=t&&typeof t=="object"&&"answer"in t?t.answer:t,i=await ao(this.o.nearRpc,this.o.contractId),s=await $r(this.o.nearRpc,i.mpc,"public_key",{domain_id:i.ckdDomain});if(typeof s!="string"||!s.startsWith("bls12381g2:"))throw new S("ckd_invalid","MPC domain has no CKD key");if(this.o.mpcKey&&this.o.mpcKey!==s)throw new S("ckd_invalid","configured MPC key differs from the contract MPC domain");return Zg(o,{secret:r,appId:Wg(this.o.contractId,G(n,32)),mpcKey:s})}async file(t,r=!1){let n=await ai(this.o.nearRpc,this.o.contractId,t);if(!n)throw new re("unknown_file");if(n.takenDown)throw new re("taken_down");if(r&&n.salesStoppedAt!==null)throw new re("sales_stopped");let o=await ao(this.o.nearRpc,this.o.contractId);if(n.terms.network!==this.o.network||o.network!==this.o.network||n.terms.near.token!==o.nearUsdc||n.terms.base&&n.terms.base.usdc!==o.usdc)throw new re("network_mismatch");return n}async startShare(t){let r=await this.hosted.quote(t);await t.onSplit?.(structuredClone(r.terms.near),r.fee??void 0,r.fee?cs(t.price,r.fee,this.o.maxProtocolFee):!1);try{let n=await this.hosted.begin(r.quoteId);if(!t.confirmBackup)throw new S("backup_secret_required");return await t.confirmBackup({fileId:r.fileId,text:await this.hosted.backup(r.fileId)}),await this.hosted.confirmBackup(n.terms.file_id),n}catch(n){throw n instanceof Do?n:new Do(r.fileId,{cause:n})}}async share(t){let r=await this.startShare(t);return this.resumeShare({...t,fileId:r.terms.file_id})}async resumeShare(t){try{for(kf(t.data);;){let r=await this.hosted.load(t.fileId);if(r.hosting?.result)return r.hosting.result;await this.hosted.next(t.fileId,t)}}catch(r){throw new Do(t.fileId,{cause:r})}}async hostedFile(t,r,n){let o=await this.hosted.load(t.terms.file_id);if(!o.hosting.result||!o.hosting.header||!t.fileKey)throw new S("invalid_record");let i=G(o.hosting.header,(o.hosting.header.length-2)/2),s=await ui(G(t.fileKey,32),r,{fileId:G(o.terms.file_id,32),name:o.name,mime:o.mime,authKind:hr(o.terms.seller)});if(Y(s.cipherHash)!==o.terms.cipher_hash)throw new br;let a=!1,c;if(r instanceof Uint8Array)c=Te(i,new Uint8Array(await new Response(s.body()).arrayBuffer())),a=!0;else{let d=s.body().getReader(),f=!0;c=new ReadableStream({async pull(u){if(f){f=!1,u.enqueue(i);return}try{let l=await d.read();l.done?(a=!0,u.close(),d.releaseLock()):u.enqueue(l.value)}catch(l){u.error(l),d.releaseLock()}},async cancel(u){try{await d.cancel(u)}finally{d.releaseLock()}}},{highWaterMark:0})}try{if(await n({file:c,header:i,terms:o.terms}),!a)throw new S("upload_incomplete")}catch(d){throw c instanceof ReadableStream&&await c.cancel(d).catch(()=>{}),d}return{terms:o.terms,...o.baseSplit?{baseSplit:o.baseSplit}:{},file:c,header:i}}async sell(t){if(t.base&&ne(t.seller.identity).kind!=="evm")throw new S("route_unavailable");if(t.hosting){if(t.fileId||t.moderator||(t.previewLen??0)!==0||t.base&&t.base.price!==t.near.price)throw new S("invalid_arguments");let x={data:t.data,name:t.name,mime:t.mime,seller:t.seller,price:t.near.price,near:{recipients:t.near.recipients,remainder:t.near.remainder},hosting:t.hosting,...t.storageBudget!==void 0?{storageBudget:t.storageBudget}:{},...t.hosting.listingStorage!==void 0?{listingStorage:t.hosting.listingStorage}:{},...t.hosting.confirmBackup?{confirmBackup:t.hosting.confirmBackup}:{},...t.onSplit?{onSplit:t.onSplit}:{}},g=await this.startShare(x);return await this.resumeShare({...x,fileId:g.terms.file_id}),this.hostedFile(g,t.data,t.publish)}if((t.data instanceof Uint8Array?t.data.length:t.data.size)>5e7)throw new $e("too_large");if(t.storageBudget!==void 0&&(t.storageBudget<=0n||t.storageBudget>=2n**128n))throw new S("invalid_arguments","invalid storage budget");if(t.storageBudget!==void 0&&t.seller.identity.kind!=="near")throw new S("near_wallet_required","storage budget requires a NEAR wallet");let r=await ao(this.o.nearRpc,this.o.contractId);if(r.network!==this.o.network)throw new re("network_mismatch");let n={nearUsdc:r.nearUsdc,baseUsdc:r.usdc},o=ne(t.seller.identity),i=t.fileId??`0x${on(32)}`,s=crypto.getRandomValues(new Uint8Array(32)),a=await ui(s,t.data,{fileId:G(i,32),name:t.name,mime:t.mime,authKind:hr(o),...t.previewLen===void 0?{}:{previewLen:t.previewLen}}),c={token:r.nearUsdc,...t.near,remainder:t.near.recipients.findIndex(x=>Q(x.identity)===Q(t.near.remainder))},d;if(this.o.sponsorship&&o.kind!=="near"){let x=(await this.o.sponsorship()).fee;if(d=x,!t.onSplit&&[c.price,...t.base?[t.base.price]:[]].some(g=>cs(g,x,this.o.maxProtocolFee)))throw new re("protocol_fee_above_max");c=Tf(c,d,t.base?.price),po({near:c,base:t.base?{price:t.base.price}:null},d)}let f=d!==void 0&&[c.price,...t.base?[t.base.price]:[]].some(x=>cs(x,d,this.o.maxProtocolFee));if(f&&!t.onSplit)throw new re("protocol_fee_above_max");await t.onSplit?.(c,d,f);let u=c.recipients[c.remainder]?.identity,l=c.recipients.map(x=>({...x,identity:ne(x.identity)})).sort((x,g)=>Cr(Tt(x.identity),Tt(g.identity))),p=l.findIndex(x=>Q(x.identity)===Q(u)),m={network:this.o.network,contract:this.o.contractId,file_id:i,seller:o,pay2_version:2,cipher_hash:Y(a.cipherHash),moderator:t.moderator??null,near:{token:r.nearUsdc,price:t.near.price,recipients:l,remainder:p},base:null};tt(m,n);let h=null;if(t.base){if(l.some(v=>v.identity.kind!=="evm"))throw new S("bad_requirements","Base split requires only EVM recipients");let x=t.base.kind??"push",g=`0x${on(32)}`,w=_f(x,{recipients:l.map(v=>v.identity.id),allocations:l.map(v=>BigInt(v.bps)),totalAllocation:10000n,distributionIncentive:0},g);h={address:w.address,kind:x,salt:g},m.base={usdc:r.usdc,price:t.base.price,pay_to:w.address},tt(m,n),await t.base.sendTransaction(w)}let y=fo(),b={kind:"sell",...t.storageBudget!==void 0?{storageBudget:t.storageBudget.toString()}:{},id:`sell:${i}`,revision:0,terms:m,baseSplit:h,fileKey:Y(s),sellerSecret:Y(y.secret),deadline:this.now()+540,name:t.name,mime:t.mime,previewLen:t.previewLen??0,ckdSecret:null};try{if(!await this.sells.compareAndSet(`annon/sell/${i}`,null,b))throw new re("store_conflict");return await this.finishSell(b,a,t.seller,t.publish,!1)}catch(x){throw new Do(i,{cause:x})}}async resumeSell(t){if((t.data instanceof Uint8Array?t.data.length:t.data.size)>5e7)throw new $e("too_large");let r=await this.sells.load(`annon/sell/${t.fileId}`);if(!r)throw new S("invalid_record","no saved sell job");if(r.hosting&&!r.published){if(!t.hosting)throw new S("transport_required");return await this.resumeShare({fileId:t.fileId,data:t.data,seller:t.seller,hosting:t.hosting}),this.hostedFile(r,t.data,t.publish)}if(r.published)throw await this.o.writeBackup(r.id,await gn(r,this.o.backupSecret)),new S("invalid_record","sell already published; secrets cleared");if(!r.fileKey||!r.sellerSecret)throw new S("invalid_record","sell job has no file key");if(r.terms.contract!==this.o.contractId||Q(r.terms.seller)!==Q(t.seller.identity))throw new S("wrong_identity","sell job identity mismatch");await this.o.writeBackup(r.id,await gn(r,this.o.backupSecret));let n=await ui(G(r.fileKey,32),t.data,{fileId:G(t.fileId,32),name:r.name,mime:r.mime,authKind:hr(r.terms.seller),previewLen:r.previewLen});if(Y(n.cipherHash)!==r.terms.cipher_hash)throw new S("cipher_hash_mismatch","original data cipher hash mismatch");let o=await ai(this.o.nearRpc,this.o.contractId,t.fileId);if(o&&o.termsHash!==tt(r.terms,L5(r.terms)))throw new S("file_mismatch","registered sell job mismatch");try{return await this.finishSell(r,n,t.seller,t.publish,o!==null)}catch(i){throw new Do(t.fileId,{cause:i})}}async reopenSeller(t){let r=await this.file(t.fileId);if(Q(r.seller)!==Q(t.seller.identity))throw new S("wrong_identity","not the registered seller");let n=`annon/seller-key/${t.fileId}`,o=await this.sellerKeys.load(n),i=fo(),s={kind:"seller-key",id:`seller-key:${t.fileId}`,file_id:t.fileId,seller:r.seller,revision:(o?.revision??-1)+1,buyerSecret:Y(i.secret),deadline:this.now()+540};if(!await this.sellerKeys.compareAndSet(n,o,s))throw new re("store_conflict");let a={file_id:t.fileId,key:Y(i.publicKeyBytes),deadline:s.deadline},c=await this.auth(t.seller,Fw(this.o.contractId,a,r.seller)),d=await this.answer(await this.call("reopen_seller",{args:a,...c?{auth:c}:{}},t.seller),i.secret,t.fileId);if(!await this.sellerKeys.compareAndSet(n,s,{...s,revision:s.revision+1,buyerSecret:null}))throw new re("store_conflict");return i.secret.fill(0),d}async finishSell(t,r,n,o,i){let s=t.terms.file_id,a;if(t.ckdSecret)a=G(t.ckdSecret,48);else{if(i)a=await this.reopenSeller({fileId:s,seller:n});else{let x=jt(G(t.sellerSecret,32)),g={terms:t.terms,seller_key:Y(x.publicKeyBytes),deadline:this.now()+540},w=await this.auth(n,Uw(this.o.contractId,g,L5(t.terms)));a=await this.answer(await this.call("register",{args:g,...w?{auth:w}:{},...w&&t.baseSplit?{baseSplit:{kind:t.baseSplit.kind,salt:t.baseSplit.salt}}:{}},n),x.secret,s)}let y=await this.sells.load(`annon/sell/${s}`);if(!y)throw new S("invalid_record","sell job missing");let b={...y,revision:y.revision+1,ckdSecret:Y(a)};if(!await this.sells.compareAndSet(`annon/sell/${s}`,y,b))throw new re("store_conflict")}let{file:c,header:d,consumed:f,cancel:u}=await r.finish({contractId:this.o.contractId,ckdSecret:a,seller:t.terms.seller,...n.identity.kind==="near"?{}:{sign:async y=>{let b=await this.auth(n,y);if(!b)throw new S("invalid_signature","missing header authorization");let x=G(b.sig,n.identity.kind==="evm"?65:64);return n.identity.kind==="solana"?{signature:x,signedMessage:new TextEncoder().encode(y)}:x}}}),l=d.length;try{if(n.identity.kind==="near"&&await this.call("publish_header",{file_id:s,header_hash:Y(await Oe(d.subarray(0,l-65)))},n),t.storageBudget){let y=`annon/sell/${s}`,b=await this.sells.load(y);if(!b)throw new S("invalid_record","sell job missing");let x=BigInt(t.storageBudget);if(b.storageFunding==="pending"){if((await U0(this.o.nearRpc,this.o.contractId,s)).available<x)throw new re("storage_required","Previous file funding is uncertain; inspect it and explicitly fund before resuming.")}else if(b.storageFunding!=="funded"){let g={...b,revision:b.revision+1,storageFunding:"pending"};if(!await this.sells.compareAndSet(y,b,g))throw new re("store_conflict");b=g;try{await gy(Lo(n),this.o.contractId,s,x)}catch(w){throw w instanceof zi&&!await this.sells.compareAndSet(y,b,{...b,revision:b.revision+1,storageFunding:"refused"})?new re("store_conflict"):w}}if(b.storageFunding!=="funded"&&!await this.sells.compareAndSet(y,b,{...b,revision:b.revision+1,storageFunding:"funded"}))throw new re("store_conflict")}if(await o({file:c,header:d,terms:t.terms}),!f())throw new S("upload_incomplete","publish did not consume the complete file stream")}catch(y){throw await u(y).catch(()=>{}),y}let p=`annon/seller-key/${s}`,m=await this.sellerKeys.load(p);if(m?.buyerSecret&&!await this.sellerKeys.compareAndSet(p,m,{...m,revision:m.revision+1,buyerSecret:null}))throw new re("store_conflict");let h=await this.sells.load(`annon/sell/${s}`);if(!h||!await this.sells.compareAndSet(`annon/sell/${s}`,h,{...h,revision:h.revision+1,published:!0,fileKey:null,sellerSecret:null,ckdSecret:null}))throw new re("store_conflict");return a.fill(0),{terms:t.terms,...t.baseSplit?{baseSplit:t.baseSplit}:{},file:c,header:d}}async buy(t){if(typeof t.maxPrice!="bigint"||t.maxPrice<=0n||t.maxPrice>=2n**128n)throw new S("max_price_required","maxPrice must be a positive human-approved cap");let r=await this.file(t.fileId,!0);if(r.moderator!==null&&!(t.moderators??[]).includes(r.moderator))throw new re("unknown_moderator");let n=await ni(t.header,gp(t.fileId,r),this.o.contractId);if(!n.usable)throw new re("file_invalid");if(t.route!==void 0&&!["near","base","1click"].includes(t.route))throw new S("invalid_arguments","invalid purchase route");if(t.route==="base"&&!r.terms.base)throw new S("route_unavailable");if(t.route==="near"&&t.payer?.identity.kind!=="near")throw new S("near_wallet_required","direct NEAR requires a NEAR payment wallet");if(t.route==="1click"&&!t.origin)throw new S("origin_required","a 1Click origin is required");if(t.route==="base"&&(t.payer?.identity.kind!=="evm"||!("signTypedData"in t.payer)))throw new S("base_wallet_required","Base requires Base terms and an EVM payment wallet");let o=t.route==="1click"||t.route===void 0&&t.payer?.identity.kind!=="near",i={load:B=>this.store.load(B),compareAndSet:async(B,N,U)=>{U&&await t.beforeSave?.(U);let R=await this.store.compareAndSet(B,N,U);return R&&U&&await t.onSaved?.(U),R}},s=t.route==="base"?"base-usdc":"near-usdc";if(t.route===void 0&&t.payer?.identity.kind==="evm"&&r.terms.base&&"signTypedData"in t.payer){let B=await lo(this.o.baseRpc);!await Ef(this.o.baseRpc,t.payer.identity.id,B.number)&&await Sf(this.o.baseRpc,r.terms.base.usdc,t.payer.identity.id,B.number)>=BigInt(r.terms.base.price)&&(s="base-usdc")}let a=s==="base-usdc"?"base":o?"1click":"near";s==="near-usdc"&&o&&t.origin&&jh(t.origin);let c=s==="base-usdc"&&r.terms.base?r.terms.base.price:r.terms.near.price;if(BigInt(c)>t.maxPrice)throw new re("price_above_max");let d=async()=>{};if(s==="base-usdc"){if(t.baseUnlock!==void 0&&!["relayer","self"].includes(t.baseUnlock))throw new S("invalid_arguments","invalid Base unlock transport");if(t.baseUnlock==="self")Lo(t.recovery),d=async()=>Vh(r,this.o.baseRpc);else{if(!this.o.relayer)throw new S("transport_required");let B=await ao(this.o.nearRpc,this.o.contractId),N={deployment:{network:this.o.network,contractId:this.o.contractId,nearUsdc:B.nearUsdc,baseUsdc:B.usdc},file:r,baseRpc:this.o.baseRpc,relayer:this.o.relayer,...this.o.fetch?{fetch:this.o.fetch}:{},now:()=>this.now()},U=t.baseSponsorship;d=async()=>{Gh(U,N)||(U=await Kh(N))}}}if(await d(),s==="near-usdc"){let B=await U0(this.o.nearRpc,this.o.contractId,t.fileId);if(B.available<B.admissionRequirement)throw new re("file_storage_low")}if(s==="near-usdc"&&t.payer?.identity.kind!=="near"&&!t.origin)throw new S("origin_required","a 1Click origin is required for cross-chain payment");let f=ne(t.recovery.identity),u=fo(),l={version:2,refund:ne(t.refund),network:s==="base-usdc"?"eip155:8453":this.o.network,contract:this.o.contractId,route:s,asset:s==="base-usdc"&&r.terms.base?r.terms.base.usdc:r.terms.near.token,file_id:t.fileId,terms_hash:r.termsHash,price:c,nonce:`0x${on(32)}`,buyer_key:Y(u.publicKeyBytes),recovery:f,expires_at:String(this.now()+3600)},p={nearUsdc:r.terms.near.token,...r.terms.base?{baseUsdc:r.terms.base.usdc}:{}},m=bn(l,p),h=zr(l,p);es(h,p);let y=`Annon: verify purchase recovery
52
52
  contract: ${this.o.contractId}
53
53
  purchase: ${m}
54
- recovery: ${Ke(f)}`,b=async()=>{if(f.kind==="near"){let B=Lo(t.recovery);if(!B.proveControl)throw new S("missing_method","NEAR recovery requires an account ownership proof before payment");await B.proveControl(y,{contractId:this.o.contractId,nearRpc:this.o.nearRpc})}else await this.auth(t.recovery,y)},x=s==="near-usdc"&&o&&t.onQuote;if(x||await b(),s==="base-usdc"){if(!t.paymentRequired||!t.url||!t.payer||!("signTypedData"in t.payer))throw new TypeError("Base requires paymentRequired, resource URL and an EVM payment wallet");let B=t.payer,N=await z6({nearRpc:this.o.nearRpc,baseRpc:this.o.baseRpc,contractId:this.o.contractId,fileId:t.fileId,buyer:B.identity.id,paymentRequired:t.paymentRequired,url:t.url,pay2:t.header,maxPrice:t.maxPrice,...t.moderators?{moderators:t.moderators}:{}});await d();let U=await H6(N,{purchase:l,buyerSecret:u.secret,wallet:{address:B.identity.id,signTypedData:T=>B.signTypedData(T)},store:i}),R={...U.purchase,revision:U.purchase.revision+1,recoveryProved:!0};if(!await i.compareAndSet(ft(m),U.purchase,R))throw new re("store_conflict");return await t.beforePayment?.(R),t.baseUnlock==="self"&&this.selfUnlockWallets.set(m,Lo(t.recovery)),t.submitBase&&await t.submitBase(U.header),{route:a,record:R,payment:U.header}}let g=Y(n.headerHash),w={schemaVersion:2,payment:{route:a,amountUsdc:at(BigInt(c)),amountBaseUnits:c,asset:{symbol:"USDC",id:l.asset},network:l.network},recoveryProved:!x,id:m,revision:0,purchase:l,message:h,buyerSecret:Y(u.secret),quote:null,recovery:f,checkedHeaderHash:g,terms:{network:l.network,contractId:l.contract,fileId:l.file_id,buyer:t.payer?.identity.id??f.id,seller:r.seller,to:l.contract,usdc:l.asset,price:l.price,buyerKey:l.buyer_key,nonce:l.nonce,headerHash:g,cipherHash:r.cipherHash,moderator:r.moderator},attempts:[]};if(!await i.compareAndSet(ft(m),null,w))throw new re("store_conflict");if(!o&&t.payer?.identity.kind==="near"){await t.beforePayment?.(w);try{await Lo(t.payer).transferPurchase(h,p)}catch(B){if(!(B instanceof Vt))throw B;let N={...w,revision:w.revision+1,nearSubmission:{state:"uncertain",txHash:B.txHash}};if(!await i.compareAndSet(ft(m),w,N))throw new Vt(B.txHash,m);return{route:a,record:N,uncertain:{purchaseId:m,txHash:B.txHash}}}return{route:a,record:w}}if(!t.origin)throw new S("origin_required","a 1Click origin is required for cross-chain payment");let v=await(t.oneClick??new Mi).quote(h,t.origin),E={...w,revision:w.revision+1,quote:v};if(!await i.compareAndSet(ft(m),w,E))throw new re("store_conflict");if(w=E,t.onQuote){await t.onQuote(v);let B=()=>{let N=Date.parse(v.deposit.depositBefore);if(!Number.isFinite(N)||N-this.now()*1e3<6e5)throw new od};B(),await b(),B()}if(!w.recoveryProved){let B={...w,revision:w.revision+1,recoveryProved:!0};if(!await i.compareAndSet(ft(m),w,B))throw new re("store_conflict");w=B}return await t.beforePayment?.(w),{route:a,record:w,instructions:v.deposit}}async proveRecovery(t,r){let n=await this.store.load(ft(t.id));if(!n||n.revision!==t.revision)throw new re("store_conflict");if(n.purchase.contract!==this.o.contractId||n.purchase.network!==(n.purchase.route==="base-usdc"?"eip155:8453":this.o.network))throw new S("network_mismatch","saved purchase is outside this SDK scope");if(Q(ne(r.identity))!==Q(n.recovery))throw new S("wrong_identity","purchase recovery identity mismatch");let o=`Annon: verify purchase recovery
54
+ recovery: ${Ke(f)}`,b=async()=>{if(f.kind==="near"){let B=Lo(t.recovery);if(!B.proveControl)throw new S("missing_method","NEAR recovery requires an account ownership proof before payment");await B.proveControl(y,{contractId:this.o.contractId,nearRpc:this.o.nearRpc})}else await this.auth(t.recovery,y)},x=s==="near-usdc"&&o&&t.onQuote;if(x||await b(),s==="base-usdc"){if(!t.paymentRequired||!t.url||!t.payer||!("signTypedData"in t.payer))throw new TypeError("Base requires paymentRequired, resource URL and an EVM payment wallet");let B=t.payer,N=await q6({nearRpc:this.o.nearRpc,baseRpc:this.o.baseRpc,contractId:this.o.contractId,fileId:t.fileId,buyer:B.identity.id,paymentRequired:t.paymentRequired,url:t.url,pay2:t.header,maxPrice:t.maxPrice,...t.moderators?{moderators:t.moderators}:{}});await d();let U=await j6(N,{purchase:l,buyerSecret:u.secret,wallet:{address:B.identity.id,signTypedData:T=>B.signTypedData(T)},store:i}),R={...U.purchase,revision:U.purchase.revision+1,recoveryProved:!0};if(!await i.compareAndSet(it(m),U.purchase,R))throw new re("store_conflict");return await t.beforePayment?.(R),t.baseUnlock==="self"&&this.selfUnlockWallets.set(m,Lo(t.recovery)),t.submitBase&&await t.submitBase(U.header),{route:a,record:R,payment:U.header}}let g=Y(n.headerHash),w={schemaVersion:2,payment:{route:a,amountUsdc:ct(BigInt(c)),amountBaseUnits:c,asset:{symbol:"USDC",id:l.asset},network:l.network},recoveryProved:!x,id:m,revision:0,purchase:l,message:h,buyerSecret:Y(u.secret),quote:null,recovery:f,checkedHeaderHash:g,terms:{network:l.network,contractId:l.contract,fileId:l.file_id,buyer:t.payer?.identity.id??f.id,seller:r.seller,to:l.contract,usdc:l.asset,price:l.price,buyerKey:l.buyer_key,nonce:l.nonce,headerHash:g,cipherHash:r.cipherHash,moderator:r.moderator},attempts:[]};if(!await i.compareAndSet(it(m),null,w))throw new re("store_conflict");if(!o&&t.payer?.identity.kind==="near"){await t.beforePayment?.(w);try{await Lo(t.payer).transferPurchase(h,p)}catch(B){if(!(B instanceof Vt))throw B;let N={...w,revision:w.revision+1,nearSubmission:{state:"uncertain",...B.txHash?{txHash:B.txHash}:{}}};if(!await i.compareAndSet(it(m),w,N))throw new Vt(B.txHash,m);return{route:a,record:N,uncertain:{purchaseId:m,...B.txHash?{txHash:B.txHash}:{}}}}return{route:a,record:w}}if(!t.origin)throw new S("origin_required","a 1Click origin is required for cross-chain payment");let v=await(t.oneClick??new Fn).quote(h,t.origin),E={...w,revision:w.revision+1,quote:v};if(!await i.compareAndSet(it(m),w,E))throw new re("store_conflict");if(w=E,t.onQuote){await t.onQuote(v);let B=()=>{let N=Date.parse(v.deposit.depositBefore);if(!Number.isFinite(N)||N-this.now()*1e3<6e5)throw new od};B(),await b(),B()}if(!w.recoveryProved){let B={...w,revision:w.revision+1,recoveryProved:!0};if(!await i.compareAndSet(it(m),w,B))throw new re("store_conflict");w=B}return await t.beforePayment?.(w),{route:a,record:w,instructions:v.deposit}}async proveRecovery(t,r){let n=await this.store.load(it(t.id));if(!n||n.revision!==t.revision)throw new re("store_conflict");if(n.purchase.contract!==this.o.contractId||n.purchase.network!==(n.purchase.route==="base-usdc"?"eip155:8453":this.o.network))throw new S("network_mismatch","saved purchase is outside this SDK scope");if(Q(ne(r.identity))!==Q(n.recovery))throw new S("wrong_identity","purchase recovery identity mismatch");let o=`Annon: verify purchase recovery
55
55
  contract: ${this.o.contractId}
56
56
  purchase: ${n.id}
57
- recovery: ${Ke(n.recovery)}`;if(n.recovery.kind==="near"){let s=Lo(r);if(!s.proveControl)throw new S("missing_method","NEAR recovery requires an account ownership proof before payment");await s.proveControl(o,{contractId:this.o.contractId,nearRpc:this.o.nearRpc})}else await this.auth(r,o);let i={...n,revision:n.revision+1,recoveryProved:!0};if(!await this.store.compareAndSet(ft(n.id),n,i))throw new re("store_conflict");return i}async accept(t,r=t?.id,n={}){if(t&&lf(t),!r)throw new S("purchase_required","missing purchase id");if(await so(this.o.nearRpc,this.o.contractId,r))return!0;if(t?.purchase.route!=="base-usdc")return!1;if(!this.o.baseRpc)throw new S("base_rpc_required","configure baseRpc to resume a Base purchase");let o=await L6(t,{nearRpc:this.o.nearRpc,baseRpc:this.o.baseRpc,store:this.store});if(o.step==="unlock"){let i=await this.call("unlock",{args:o.args},n.unlockWallet??this.selfUnlockWallets.get(r));if(this.unlocked.set(r,i),this.unlocked.size>64){let s=this.unlocked.keys().next().value;s!==void 0&&this.unlocked.delete(s)}}return await so(this.o.nearRpc,this.o.contractId,r)!==null}async open(t){return this.openSource(t)}async openTo(t){return Dg(t.file,r=>this.openSource({...t,file:r}),t.spool)}async openSource(t){if((t.file instanceof Uint8Array?t.file.length:t.file.size)>50086016)throw new $e("too_large");if(!t.record&&!t.recovery)throw new S("purchase_required","a saved purchase or recovery grant is required");let r=t.recovery;if(r&&r.grant===null)throw new S("recovery_not_final","recovery grant is not final");let n=r?.purchase_id??t.record?.id;if(!n)throw new S("purchase_required","missing purchase id");if(!await this.accept(t.record,n))throw new re("settlement_pending","purchase not accepted; check status and resume");let o=r?.file_id??t.record?.purchase.file_id;if(!o)throw new S("file_required","missing file id");let i=r?.grant??0,s=r?.buyerSecret??t.record?.buyerSecret;if(!s)throw new S("invalid_record","missing buyer secret");let a=G(s,32),c=await so(this.o.nearRpc,this.o.contractId,n),d=await U0(this.o.nearRpc,this.o.contractId,n,i);if(!c||c.file_id!==o||!d||Y(Gt(a).publicKeyBytes)!==d.buyer_key)throw new S("invalid_record","saved key does not match the final grant");let f=await this.file(o),u=t.file instanceof Uint8Array?void 0:await qg(t.file,{listing:wp(o,f),contractId:this.o.contractId}),l=await ni(u?u.header:t.file.subarray(0,new DataView(t.file.buffer,t.file.byteOffset).getUint32(8)),wp(o,f),this.o.contractId);if(t.record&&Y(l.headerHash)!==t.record.checkedHeaderHash)throw new S("file_mismatch","header differs from the checked purchase header");let p=i===0?this.unlocked.get(n):void 0;i===0&&this.unlocked.delete(n);let m;if(p)try{m=await this.answer(p,a,o)}catch{}if(m||(m=await this.answer(await this.call("claim_key",{purchase_id:n,grant:i}),a,o)),u){if(!t.sink)throw new S("invalid_arguments","a plaintext sink is required");let y=await u.writeTo(t.sink,async()=>m);if(y.size>5e7)throw new $e("too_large");return{meta:y}}let h=await ng(t.file,{contractId:this.o.contractId,listing:wp(o,f),ckdSecret:async()=>m});if(h.meta.size>5e7)throw new $e("too_large");return h}async recover(t){let r=ne(t.wallet.identity),n=[];if(t.purchaseId)n.push(t.purchaseId);else{let i=t.limit??50;for(let s=0;;s+=i){let a=await Rg(this.o.nearRpc,this.o.contractId,r,s,i);if(n.push(...a),a.length<i)break}}let o=[];for(let i of n)try{let s=await so(this.o.nearRpc,this.o.contractId,i);if(!s||Q(s.recovery)!==Q(r))throw new S("wrong_identity","purchase recovery identity mismatch");await this.file(s.file_id);let a=`annon/recovery/${i}`,c=await this.recoveries.load(a);if(c?.grant!==null&&c?.grant!==void 0){o.push(c);continue}if(!c){let m=fo();if(c={kind:"recovery",id:`recovery:${i}`,revision:0,purchase_id:i,file_id:s.file_id,recovery:r,buyerSecret:Y(m.secret),fresh_key:Y(m.publicKeyBytes),nonce:`0x${sn(32)}`,deadline:this.now()+540,grant:null},!await this.recoveries.compareAndSet(a,null,c))throw new re("store_conflict")}let d=c,f=async m=>{for(let h=1;h<m;h++)if((await U0(this.o.nearRpc,this.o.contractId,i,h))?.buyer_key===d.fresh_key)return h;return null},u=await f(s.grants),l;if(u===null){if(c.deadline<=this.now()){await this.o.writeBackup(`${c.id}:revision:${c.revision}`,await is(c,this.o.backupSecret));let b=fo(),x={...c,revision:c.revision+1,buyerSecret:Y(b.secret),fresh_key:Y(b.publicKeyBytes),nonce:`0x${sn(32)}`,deadline:this.now()+540};if(!await this.recoveries.compareAndSet(a,c,x))throw new re("store_conflict");c=x,d=x}await this.o.writeBackup(c.id,await is(c,this.o.backupSecret));let m={purchase_id:i,fresh_key:c.fresh_key,nonce:c.nonce,deadline:c.deadline},h=await this.auth(t.wallet,Pw({...m,contract:this.o.contractId,file_id:s.file_id,recovery:r}));l=await this.call("reopen",{args:m,...h?{auth:h}:{}},t.wallet);let y=await so(this.o.nearRpc,this.o.contractId,i);u=await f(y?.grants??s.grants)}if(u===null)throw new S("recovery_not_final","reopen grant is not final; resume the saved recovery");l&&typeof l=="object"&&("big_y"in l||"answer"in l)&&await this.answer(l,G(c.buyerSecret,32),s.file_id);let p={...c,revision:c.revision+1,grant:u};if(!await this.recoveries.compareAndSet(a,c,p))throw new re("store_conflict");o.push(p)}catch(s){if(t.purchaseId)throw s;t.onError?.(i,s)}return o}async stop(t){let r=await this.file(t.fileId);if(Q(r.seller)!==Q(t.seller.identity))throw new S("wrong_identity","not the registered seller");let n={file_id:t.fileId,key:null,deadline:this.now()+540},o=await this.auth(t.seller,Ow(this.o.contractId,n,r.seller));await this.call("stop_sales",{args:n,...o?{auth:o}:{}},t.seller)}};var D4="/.well-known/annon-shop.json";function Rr(e){if(typeof e!="string")throw new TypeError("invalid URL");let t=new URL(e);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash)throw new TypeError("invalid discovery URL");return t.href}function Ra(e){let t=new URL(Rr(e));if(t.pathname!=="/")throw new TypeError("service must be an origin");return t.origin}function xp(e){return new URL(D4,Rr(e)).href}var q4=e=>typeof e=="string"&&/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(e);function Li(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("invalid object");return e}function vp(e){if(typeof e!="string")throw new TypeError("invalid text")}function md(e,t=Number.MAX_SAFE_INTEGER){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0||e>t)throw new TypeError("invalid integer")}function M5(e){try{let t=Li(e),r={};if(t.shopDirectoryUrl!==void 0&&(r.shopDirectoryUrl=Rr(t.shopDirectoryUrl)),t.shops!==void 0){if(!Array.isArray(t.shops)||t.shops.length>100)throw new TypeError("invalid shops");let n=new Set,o=new Set;r.shops=t.shops.map(i=>{let s=Li(i);ae(s,["manifest",...["id","profile"].filter(d=>Object.hasOwn(s,d))]);let a=xp(s.manifest);if(o.has(a))throw new TypeError("duplicate shop");o.add(a);let c={manifest:a};if(s.id!==void 0){if(!q4(s.id)||n.has(s.id))throw new TypeError("invalid alias");n.add(s.id),c.id=s.id}if(s.profile!==void 0){let d=Li(s.profile);if(ae(d,["network","contract","nearRpc","relayer","host",...Object.hasOwn(d,"baseRpc")?["baseRpc"]:[]]),d.network!=="near:mainnet")throw new TypeError("invalid profile network");c.profile={network:d.network,contract:be(d.contract),nearRpc:Rr(d.nearRpc),...d.baseRpc!==void 0?{baseRpc:Rr(d.baseRpc)}:{},relayer:Ra(d.relayer),host:Ra(d.host)}}return c})}if(t.defaultShop!==void 0){if(vp(t.defaultShop),!r.shops?.some(n=>n.id===t.defaultShop||n.manifest===t.defaultShop))throw new TypeError("unknown default shop");r.defaultShop=t.defaultShop}return r}catch(t){throw new S("invalid_config",void 0,{cause:t})}}function j4(e){let t=Li(e),r=["uploadsPerPersonPerDay","attemptsPerPersonPerDay","fileLifetimeDays","maxFileBytes"];if(ae(t,["text",...r.filter(n=>Object.hasOwn(t,n))]),vp(t.text),!t.text.trim()||new TextEncoder().encode(t.text).byteLength>4096||/[\p{Cc}\p{Cs}\u2028\u2029]|(?![\u200c\u200d])\p{Cf}/u.test(t.text))throw new TypeError("invalid rules text");for(let n of r)Object.hasOwn(t,n)&&(n==="fileLifetimeDays"&&t[n]===null||md(t[n]));return t}function G4(e){let t=Li(e);ae(t,["version","name","shopUrl","network","contract","relayer","host","catalog",...Object.hasOwn(t,"rules")?["rules"]:[]]);let r=Li(t.catalog);if(ae(r,["url","format","search"]),t.version!==1||t.network!=="near:mainnet"||r.format!=="annon-catalog-array-v1"||r.search!=="client")throw new TypeError("unsupported manifest");if(vp(t.name),!t.name.trim())throw new TypeError("missing shop name");let n=Ra(t.host),o=Rr(r.url);if(new URL(o).origin!==n)throw new TypeError("catalog origin mismatch");return{version:1,...Object.hasOwn(t,"rules")?{rules:j4(t.rules)}:{},name:t.name,shopUrl:Rr(t.shopUrl),network:t.network,contract:be(t.contract),relayer:Ra(t.relayer),host:n,catalog:{url:o,format:r.format,search:r.search}}}async function xy(e,t,r){try{let n=await r(Rr(e),{credentials:"omit",redirect:"error",cache:"no-store",signal:AbortSignal.timeout(1e4)});if(n.status!==200||n.redirected||n.url&&n.url!==e||!n.body)throw new S("bad_response");let o=n.body.getReader();try{if(Number(n.headers.get("content-length"))>t)throw new S("too_large");let i=0,s=[];for(;;){let{done:d,value:f}=await o.read();if(d)break;if(i+=f.byteLength,i>t)throw new S("too_large");s.push(f)}let a=new Uint8Array(i),c=0;for(let d of s)a.set(d,c),c+=d.byteLength;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch(d){throw new S("invalid_record",void 0,{cause:d})}}finally{await o.cancel().catch(()=>{})}}catch(n){throw n instanceof S?n:new S("transport",void 0,{cause:n})}}async function z5(e,t=globalThis.fetch){let r=xp(e.manifest),n;try{let o=Li(await xy(r,65536,t)),i=e.profile;if(i&&(o.network!==i.network||o.contract!==i.contract||Ra(o.relayer)!==i.relayer||Ra(o.host)!==i.host||o.nearRpc!==void 0&&Rr(o.nearRpc)!==i.nearRpc||o.baseRpc!==void 0&&Rr(o.baseRpc)!==i.baseRpc))throw new S("config_conflict");n=G4(o)}catch(o){throw o instanceof S?o:new S("invalid_record",void 0,{cause:o})}return{manifest:r,...e.id!==void 0?{id:e.id}:{},info:n,trusted:e.profile!==void 0}}function H5(e){let{limit:t=20,offset:r=0,search:n=""}=e;if(!Number.isSafeInteger(t)||t<1||t>100||!Number.isSafeInteger(r)||r<0||typeof n!="string")throw new S("invalid_arguments");return{limit:t,offset:r,search:n.toLowerCase()}}function $5(e,{limit:t,offset:r}){let n=e.slice(r,r+t),o=r+n.length<e.length?r+n.length:null;return{items:n,total:e.length,nextOffset:o}}async function L5(e,t){let r=[...e.shops??[]];if(e.shopDirectoryUrl){let n=await xy(e.shopDirectoryUrl,262144,t);try{if(ae(n,["version","shops"]),n.version!==1||!Array.isArray(n.shops))throw new TypeError("invalid directory");if(n.shops.length>100)throw new S("too_large");for(let o of n.shops){ae(o,["manifest"]);let i=xp(o.manifest);r.some(s=>s.manifest===i)||r.push({manifest:i})}}catch(o){throw o instanceof S?o:new S("invalid_record",void 0,{cause:o})}}return r}async function V4(e={},t={},r=globalThis.fetch){let n=H5(t),o=M5(e),i=await L5(o,r),s=new Array(i.length),a=0,c=await Promise.allSettled(Array.from({length:Math.min(4,i.length)},async()=>{for(;a<i.length;){let d=a++,f=X(i[d]);try{s[d]=await z5(f,r)}catch(u){if(f.profile&&u instanceof S&&u.code==="config_conflict")throw u;s[d]={manifest:f.manifest,...f.id!==void 0?{id:f.id}:{},trusted:!!f.profile,error:Ko(u).code}}}}));for(let d of c)if(d.status==="rejected")throw d.reason;return $5(s.filter(d=>("info"in d?d.info.name:d.id??d.manifest).toLowerCase().includes(n.search)),n)}function K4(e,t){if(!Array.isArray(e))throw new TypeError("invalid catalog");if(e.length>1e4)throw new S("too_large");return e.map(r=>{ae(r,["name","fileId","title","description","url","header","byteSize","plaintextSize","createdAt","expiresAt","termsHash","terms","salesStopped","takenDown"]);for(let o of["name","title","description"])vp(r[o]);G(r.fileId,32),G(r.termsHash,32);for(let o of["url","header"])if(new URL(Rr(r[o])).origin!==t.host)throw new S("config_conflict");if(md(r.byteSize,50086016),md(r.plaintextSize,5e7),md(r.createdAt),r.expiresAt!==null&&(md(r.expiresAt),r.expiresAt<r.createdAt))throw new TypeError("invalid expiry");if(typeof r.salesStopped!="boolean"||typeof r.takenDown!="boolean")throw new TypeError("invalid listing flags");let n=r.terms;if(n.contract!==t.contract||n.network!==t.network)throw new S("config_conflict");if(n.file_id!==r.fileId||tt(n)!==r.termsHash)throw new TypeError("invalid catalog terms");return r})}async function W4(e,t={},r=globalThis.fetch){let n=H5(t),o=M5(e),i=t.shop??o.defaultShop;if(typeof i!="string"||!i)throw new S("invalid_arguments");let a=o.shops?.find(f=>f.id===i||f.manifest===i)??(await L5(o,r)).find(f=>f.manifest===i);if(!a)throw new S("invalid_arguments");let c=await z5(a,r),d;try{d=K4(await xy(c.info.catalog.url,8388608,r),c.info)}catch(f){throw f instanceof S?f:new S("invalid_record",void 0,{cause:f})}return d=d.filter(f=>[f.name,f.title,f.description].some(u=>u.toLowerCase().includes(n.search))),d.sort((f,u)=>u.createdAt-f.createdAt||(f.fileId<u.fileId?-1:f.fileId>u.fileId?1:0)),{...$5(d,n),...c.info.rules?{shop:{manifest:c.manifest,name:c.info.name},rules:c.info.rules}:{}}}var Oa=50086016;function Sp(e,t){try{e?.(t)}catch{}}async function vy(e){if(e.size!==void 0&&(!Number.isSafeInteger(e.size)||e.size<0))throw new TypeError("invalid file size");if(e.size!==void 0&&e.size>Oa)throw new $e("too_large","File exceeds the 50 MB size limit.");if(e.signal?.aborted)throw new $e("cancelled");let t=await ni(e.header,e.listing,e.contractId);if(Y(t.headerHash)!==e.checkedHeaderHash)throw new $e("file_mismatch","header differs from the checked purchase header");let r=Iw({...e,maxBytes:Oa}).getReader(),n=[],o=0;try{for(;;){let i=await r.read();if(e.signal?.aborted)throw new $e("cancelled");if(i.done)return Te(...n);if(o+=i.value.length,o>Oa)throw new $e("too_large","File exceeds the 50 MB size limit.");n.push(i.value),Sp(e.onProgress,{phase:"downloading",received:o,...e.size===void 0?{}:{total:e.size}})}}finally{await r.cancel().catch(()=>{}),r.releaseLock()}}var Sy="annon/browser/index",cr=()=>new S("store_conflict","browser purchase store conflict; reload the saved purchase"),Ey=e=>`annon/browser/entry/${e}`,Ep=e=>`annon/browser/backup/${e}`,D5=32;async function Ay(e={}){let t=uc(e),r="annon/browser/secret",n=await t.load(r);if(!n){let b={id:"browser-secret",revision:0,secret:Y(lc())};await t.compareAndSet(r,null,b)?n=b:n=await t.load(r)}if(n?.id!=="browser-secret")throw new Error("local backup secret missing");let o=G(n.secret,32),i=uc(e),s=rw(i,o),a=nw(i,o),c=()=>s.load(Sy),d=()=>({kind:"browser-purchase-index",id:"browser-index",revision:0,entries:[]});async function f(b){for(let x=0;x<D5;x++){let g=await c(),w=g?structuredClone({...g,revision:g.revision+1}):d(),v=await b(w),E=await yf(Sy,w,o);if(await i.compareAndSetMany([{key:Sy,expected:g,next:E},...v]))return}throw cr()}let u=async b=>{let x=await a.load(Ey(b));if(!x)return null;let{kind:g,...w}=x;return w},l=async(b,x,g=!1)=>{fc(b,x),await f(async w=>{if(g&&x.purchase&&w.entries.some(N=>N.purchaseId===x.purchase?.id))throw cr();let v=w.entries.find(N=>N.id===x.id);if(b?!v||v.revision!==b.revision:v)throw cr();let E=Date.now(),B={id:x.id,revision:x.revision,fileId:x.fileId,route:x.route,state:x.state,resourceUrl:x.resourceUrl,createdAt:v?.createdAt??E,updatedAt:Math.max(v?.updatedAt??E,E),...x.purchase?{purchaseId:x.purchase.id}:{}};return v?w.entries[w.entries.indexOf(v)]=B:w.entries.push(B),[{key:Ey(x.id),expected:b,next:await yf(Ey(x.id),{...x,kind:"browser-purchase"},o)}]})},p=ow(i,o),m=b=>`annon/browser/archives/${b}`,h=async b=>{let x=await p.load(m(b));return Promise.all((x?.names??[]).map(async g=>{let w=await i.load(Ep(g));if(!w)throw new Error("recovery archive missing");let v=await mf(w.backup,o);if(v.purchase_id!==b||g!==`${v.id}:revision:${v.revision}`)throw new Error("recovery archive mismatch");return v}))},y=async(b,x)=>{let g=Ep(b),w=b.replace(/:revision:[0-9]+$/,""),v=w.startsWith("recovery:")?await mf(x,o):void 0,E=v?.revision??(/^0x[0-9a-f]{64}$/.test(w)?(await K0(x,o)).revision:void 0),B=b!==w;if(B&&(!v||b!==`${v.id}:revision:${v.revision}`))throw new TypeError("invalid recovery archive name");for(let N=0;N<D5;N++){let U=await i.load(g);if(E!==void 0&&U?.sourceRevision!==void 0&&U.sourceRevision>=E)return;let R={...E===void 0?{}:{sourceRevision:E},id:b,revision:U?U.revision+1:0,backup:x};if(B&&v){let T=m(v.purchase_id),O=await p.load(T),z=O?.names??[],P={kind:"browser-recovery-archives",id:`recovery-archives:${v.purchase_id}`,revision:O?O.revision+1:0,purchaseId:v.purchase_id,names:z.includes(b)?z:[...z,b]};if(await i.compareAndSetMany([{key:g,expected:U,next:R},{key:T,expected:O,next:await yf(T,P,o)}]))return}else if(await i.compareAndSet(g,U,R))return}throw cr()};return{rawStore:i,backupSecret:o,load:u,save:l,writeBackup:y,recoveryArchives:h,async restorePurchase(b){let x=ss(i,o),g=ft(b.id),w=await x.load(g);if(w&&(w.message!==b.message||w.buyerSecret!==b.buyerSecret))throw cr();if(w&&w.revision>=b.revision)return w;let v={...b,revision:w?w.revision+1:0};if(!await x.compareAndSet(g,w,v))throw cr();return await y(v.id,await pf(v,o)),v},async list(){return((await c())?.entries??[]).map(({id:b,fileId:x,route:g,state:w})=>({id:b,fileId:x,route:g,state:w}))},async exportReceipt(b,x){let g=await u(b);if(!g)throw new Error("purchase missing");let w=structuredClone(g);if(g.purchase&&(w.recoveryArchives=await h(g.purchase.id)),g.purchase){let v=await ss(i,o).load(ft(g.purchase.id));v&&v.revision>=g.purchase.revision&&(w.purchase=v);let E=await i.load(Ep(g.purchase.id));if(E){let U=await K0(E.backup,o);U.revision>(w.purchase?.revision??-1)&&(w.purchase=U)}let B=await pc(i,o).load(`annon/recovery/${g.purchase.id}`),N=await i.load(Ep(`recovery:${g.purchase.id}`));B?w.recovery=B:N&&(w.recovery=await mf(N.backup,o))}return ew({kind:"browser-receipt",entry:w},x)},async importReceipt(b,x){let{entry:g}=await tw(b,x);if(await u(g.id))throw cr();if(g.purchase){if((await c())?.entries.some(N=>N.purchaseId===g.purchase?.id))throw cr();let v=ss(i,o),E={...g.purchase,revision:0},B=await v.load(ft(E.id));if(B&&(B.message!==E.message||B.buyerSecret!==E.buyerSecret)||!B&&!await v.compareAndSet(ft(E.id),null,E))throw cr();g.purchase=B??E}if(g.recovery){let w=pc(i,o),v=`annon/recovery/${g.recovery.purchase_id}`,E=await w.load(v);if(E&&E.buyerSecret!==g.recovery.buyerSecret)throw cr();let B={...g.recovery,revision:0};if(!E&&!await w.compareAndSet(v,null,B))throw cr();g.recovery=E??B}for(let w of g.recoveryArchives??[])await y(`${w.id}:revision:${w.revision}`,await is(w,o));return await l(null,{...g,revision:0,needsProof:!0,lease:void 0,state:["terms_review","refunded","failed","expired","recovering","accepted","file_ready","abandoned"].includes(g.state)?g.state:"payment_uncertain"},!0),g.id}}}function Z4(e,t){return new $i({...t,rawStore:e.rawStore,backupSecret:e.backupSecret,writeBackup:e.writeBackup})}var Y4=120,X4=3e4,_p=class extends S{constructor(r){super("lease_busy","Another tab holds this purchase; wait for its lease to expire.");this.waitUntil=r;this.name="PurchaseLeaseBusy"}waitUntil;code="lease_busy"},_y=class e{constructor(t){this.options=t;this.storage=t.storage}options;storage;owner=crypto.randomUUID();listeners=new Set;static async create(t,r){let n={id:r.id,revision:0,fileId:r.fileId,header:Y(r.header),resourceUrl:r.resourceUrl,route:r.route,maxPrice:String(r.maxPrice),state:"terms_review",submission:"not_submitted"};return await t.storage.save(null,n),new e({...t,id:r.id})}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}async read(){let t=await this.storage.load(this.options.id);if(!t)throw new Error("purchase missing");return t}async snapshot(){let t=await this.read();return{id:t.id,state:t.state,revision:t.revision,fileId:t.fileId,route:t.route,resourceUrl:t.resourceUrl,...this.waiting(t),...t.checkpoint?.lastStatus?{swapStatus:t.checkpoint.lastStatus.status}:{}}}now(){return(this.options.now??(()=>Math.floor(Date.now()/1e3)))()}waiting(t){return t.lease&&t.lease.expiresAt>this.now()?{leaseWaitUntil:t.lease.expiresAt}:{}}emit(t){for(let r of this.listeners)try{r(t)}catch{}}busy(t){if(!(!t.lease||t.lease.expiresAt<=this.now()))return this.emit({id:t.id,state:t.state,revision:t.revision,...this.waiting(t)}),new _p(t.lease.expiresAt)}async withLease(t,r={}){let n=await this.read(),o=this.busy(n);if(o)throw o;if(r.initial?.state==="preparing"&&n.state!=="terms_review")throw new Error("purchase already started; resume the saved purchase");let i=()=>({owner:this.owner,expiresAt:this.now()+Y4}),s={record:await this.change(n,{...r.initial,lease:i()}),change:u=>d(async()=>{if(c)throw c;if(s.record.lease?.owner!==this.owner||s.record.lease.expiresAt<=this.now())throw new Error("purchase lease expired; resume the saved purchase");return s.record=await this.change(s.record,{...u,lease:i()}),s.record})},a=Promise.resolve(),c;function d(u){let l=a.then(u);return a=l.catch(()=>{}),l}let f=setInterval(()=>{s.change({}).catch(u=>{c=u})},X4);try{let u=await t(s);return r.finalCheckpoint!==!1&&await s.change({}),u}finally{clearInterval(f),await a,await this.change(s.record,{lease:void 0}).catch(()=>{})}}async change(t,r){let n={...t,...r,id:t.id,revision:t.revision+1};await this.storage.save(t,n);let o={id:n.id,state:n.state,revision:n.revision,...n.checkpoint?.lastStatus?{swapStatus:n.checkpoint.lastStatus.status}:{}};return this.emit(o),n}async start(t){let r=await this.read();if(r.state!=="terms_review")throw new Error("purchase already started; resume the saved purchase");if(r.route==="base"&&typeof t.submitBase!="function")throw new TypeError("Base requires submitBase");await this.withLease(async n=>{let o=async i=>{await n.change(i)};try{let i=await this.options.sdk.buy({...t,fileId:n.record.fileId,header:G(n.record.header,(n.record.header.length-2)/2),url:n.record.resourceUrl,route:n.record.route,maxPrice:BigInt(n.record.maxPrice),beforeSave:async s=>{await o({purchase:s,...n.record.route==="base"&&s.attempts.some(a=>!!a.payload)?{submission:"uncertain"}:{}})},onSaved:async s=>{n.record.purchase?.revision!==s.revision&&await o({purchase:s,...n.record.route==="base"&&s.attempts.some(a=>!!a.payload)?{submission:"uncertain"}:{}})},beforePayment:async s=>{if(!s.recoveryProved||n.record.purchase?.id!==s.id)throw new Error("durable recovery proof required");if(n.record.lease?.owner!==this.owner||n.record.lease.expiresAt<=this.now())throw new Error("purchase lease expired");n.record.route!=="1click"&&await o({state:"payment_uncertain",purchase:s,submission:"uncertain",paymentStarted:!0})}});await o({purchase:i.record,state:n.record.route==="1click"?"awaiting_deposit":"payment_uncertain",submission:n.record.route==="1click"?"not_submitted":i.uncertain?"uncertain":n.record.submission==="not_submitted"?"not_submitted":"submitted"})}catch(i){throw await n.change({state:n.record.purchase?"payment_uncertain":"terms_review"}).catch(()=>{}),i}},{initial:{state:"preparing",submission:"not_submitted"},finalCheckpoint:!1})}deposit(t){return t.purchase?.quote?.deposit}async instructions(){let t=await this.read(),r=this.deposit(t);return!["awaiting_deposit","incomplete_deposit"].includes(t.state)||t.needsProof||!t.purchase?.recoveryProved||!r||!Number.isFinite(Date.parse(r.depositBefore))||Date.parse(r.depositBefore)-this.now()*1e3<6e5?null:structuredClone(r)}async resume(t={}){let r=await this.read();if(this.busy(r)||["terms_review","refunded","failed","file_ready","accepted","abandoned"].includes(r.state))return;if(r.state==="recovering"){t.recovery&&await this.recover(t.recovery);return}let n=r.lease!==void 0;return this.withLease(async o=>{if(r=o.record,!r.purchase){await o.change({state:"terms_review"});return}let i=r.purchase,s=i.attempts.some(l=>!!l.payload);if(r.route!=="1click"&&r.submission==="not_submitted"&&!s&&!r.paymentStarted&&!r.purchase.nearSubmission){await o.change({state:"abandoned"});return}(n||s)&&r.submission==="not_submitted"&&(r=await o.change({...s?{submission:"uncertain"}:{}}));let a=await this.storage.restorePurchase(i);JSON.stringify(a)!==JSON.stringify(r.purchase)&&(r=await o.change({purchase:a}));let c=()=>r.route==="base"&&a.paymentState!=="expired"&&(s||r.submission!=="not_submitted"||r.state==="accepting");if(c()&&r.state!=="accepting"&&(r=await o.change({state:"accepting"})),await this.options.sdk.accept(a)){await o.change({state:"accepted"});return}a=await this.storage.restorePurchase(a),JSON.stringify(a)!==JSON.stringify(r.purchase)&&(r=await o.change({purchase:a}));let d=r.checkpoint?.lastStatus?.status,f=d==="SUCCESS"||r.state==="accepting"?"accepting":d==="PROCESSING"||d==="KNOWN_DEPOSIT_TX"||r.state==="processing"?"processing":null;if(r.route==="1click"&&f){await o.change({state:f});return}if(r.state==="expired"&&r.route!=="base")return;if(r.route!=="1click"){await o.change({state:c()?"accepting":this.now()>=Number(a.purchase.expires_at)?"expired":r.submission==="submitted"?"accepting":"payment_uncertain"});return}let u=this.deposit(r);if(!u||!Number.isFinite(Date.parse(u.depositBefore))||Date.parse(u.depositBefore)-this.now()*1e3<6e5){await o.change({state:"expired"});return}if(r.needsProof||!r.purchase?.recoveryProved){if(!t.recovery)return;let l=await this.options.sdk.proveRecovery(a,t.recovery);if(r=await o.change({purchase:l,needsProof:!1}),Date.parse(u.depositBefore)-this.now()*1e3<6e5){await o.change({state:"expired"});return}}await o.change({state:d==="SUCCESS"?"accepting":d==="INCOMPLETE_DEPOSIT"?"incomplete_deposit":d==="PROCESSING"?"processing":"awaiting_deposit"})})}async poll(t={}){return this.withLease(async r=>{let n=r.record,o=this.deposit(n);if(n.route!=="1click"||!o||["terms_review","accepted","recovering","file_ready","refunded","failed","abandoned"].includes(n.state))throw new Error("no pollable 1Click deposit in this state");let{oneClick:i=new Mi,...s}=t;await i.poll(o.address,{...s,...o.memo===void 0?{}:{memo:o.memo},...n.checkpoint?{checkpoint:n.checkpoint}:{},onProgress:async a=>{let c=a.lastStatus?.status,f=c?{PENDING_DEPOSIT:"awaiting_deposit",KNOWN_DEPOSIT_TX:"processing",PROCESSING:"processing",INCOMPLETE_DEPOSIT:"incomplete_deposit",SUCCESS:"accepting",REFUNDED:"refunded",FAILED:"failed"}[c]??n.state:n.state;["awaiting_deposit","incomplete_deposit"].includes(f)&&(n.state==="expired"||Date.parse(o.depositBefore)<=this.now()*1e3)&&(f="expired"),n=await r.change({checkpoint:a,state:f})}}),n.state==="accepting"&&n.purchase&&await this.options.sdk.accept(n.purchase)&&await r.change({state:"accepted"})})}async recover(t){return this.withLease(async r=>{let n=r.record;if(!n.purchase)throw new Error("saved purchase required");let o=await this.storage.restorePurchase(n.purchase);n=await r.change({state:"recovering",purchase:o});let s=(await this.options.sdk.recover({wallet:t,purchaseId:o.id}))[0];if(!s||s.grant===null)throw new Error("recovery not final; resume recovery");await r.change({recovery:s,state:"accepted"})})}async open(t={}){return this.withLease(async r=>{let n=r.record;if(!["accepted","file_ready"].includes(n.state)||!n.purchase)throw new Error("purchase is not accepted");let o=await this.storage.restorePurchase(n.purchase);JSON.stringify(o)!==JSON.stringify(n.purchase)&&(n=await r.change({purchase:o}));let i=t instanceof Uint8Array?{}:t;if(t instanceof Uint8Array&&t.length>Oa)throw new $e("too_large","File exceeds the 50 MB size limit.");let s=G(n.header,(n.header.length-2)/2);if(n.recovery?.grant===null)throw new Error("recovery grant is not final");let a=t instanceof Uint8Array?t:await vy({...i,url:n.resourceUrl,contractId:o.terms.contractId,fileId:n.fileId,header:s,checkedHeaderHash:o.checkedHeaderHash,listing:{fileId:n.fileId,cipherHash:o.terms.cipherHash,seller:o.terms.seller,publishedHeaderHash:Y(await Oe(s.subarray(0,-65)))},proof:{secret:G(n.recovery?.buyerSecret??o.buyerSecret,32),purchase_id:o.id,grant:n.recovery?.grant??0}});if(i.signal?.aborted)throw new $e("cancelled");Sp(i.onProgress,{phase:"decrypting",received:a.length});let c=await this.options.sdk.open({file:a,record:o,...n.recovery?{recovery:n.recovery}:{}});if(i.signal?.aborted)throw new $e("cancelled");return await r.change({state:"file_ready"}),Sp(i.onProgress,{phase:"ready",received:a.length}),c})}exportReceipt(t){return this.storage.exportReceipt(this.options.id,t)}};var hd="annon/browser/sale";function Ty(e,t){if(typeof e!="string"||!new RegExp(`^(0|[1-9][0-9]*)(\\.[0-9]{1,${t}})?$`).test(e))throw new S("invalid_arguments");let[r,n=""]=e.split("."),o=BigInt(X(r))*10n**BigInt(t)+BigInt(n.padEnd(t,"0"));if(o<=0n||o>=2n**128n)throw new S("invalid_arguments");return o}function q5(e){let t=BigInt(e),r=(t%10n**24n).toString().padStart(24,"0").replace(/0+$/,"");return`${t/10n**24n}${r?`.${r}`:""}`}var G5=async(e,t)=>{let r=await new Response(e).blob();return t(dc(r))};function Ca(e){let t=X(e.hosting),{expiresAt:r,...n}=t.intent;return JSON.stringify([n,e.terms,e.baseSplit,t.origin,t.metadata,t.manifest,t.listingStorage,e.storageBudget??null,t.fee,t.steps])}function Ua(e){return JSON.stringify([e.fileKey,e.sellerSecret])}function j5(e){let t=X(e.hosting),r=e.terms,n=BigInt(r.near.price),o=r.near.recipients.map(c=>n*BigInt(c.bps)/10000n);o[r.near.remainder]=X(o[r.near.remainder])+n-o.reduce((c,d)=>c+d,0n);let i=r.near.recipients.findIndex(c=>Q(c.identity)===Q(r.seller)),s=o[i]??0n,a=r.near.recipients.map((c,d)=>d).sort((c,d)=>c===i?-1:d===i?1:c-d);return{seller:{kind:r.seller.kind,label:Ke(r.seller)},sellerIdentity:Ke(r.seller),filename:e.name,title:t.metadata.title,priceUsdc:at(n),shares:a.map(c=>({label:c===i?"You":"Protocol fee",bps:X(r.near.recipients[c]).bps,amountUsdc:at(X(o[c]))})),fee:t.fee?{fixedUsdc:at(t.fee.fixed),bps:t.fee.bps,amountUsdc:at(n-s)}:null,funding:r.seller.kind==="near"?{listingStorageNear:q5(X(t.listingStorage)),purchaseStorageNear:q5(X(e.storageBudget))}:null,routes:r.base?["near","base","1click"]:["near","1click"],baseSplit:r.base!==null,steps:["backup",...t.steps],contract:r.contract,host:t.origin}}async function J4(e={}){let t={...e,name:e.name??"annon-selling"},{rawStore:r,backupSecret:n,writeBackup:o}=await Ay(t);return{rawStore:r,backupSecret:n,writeBackup:o,indexStore:uc(t)}}function Q4(e){let t=e.fileLifetimeDays;if(t!=null&&(!Number.isSafeInteger(t)||t<0))throw new S("invalid_arguments");let r=new $i(e),n=new Map,o=new Map,i=new Map,s=l=>{let p=n.get(l);return p||(p={},n.set(l,p)),p},a=async()=>{try{let l=await e.indexStore.load(hd);if(l&&(l.id!=="browser-sale"||!Number.isSafeInteger(l.revision)||l.revision<0||!/^0x[0-9a-f]{64}$/.test(l.fileId)||!(l.backup===null||typeof l.backup=="string")||Object.keys(l).some(p=>!["id","revision","fileId","backup"].includes(p))))throw new Error;return l}catch(l){throw new S("invalid_record",void 0,{cause:l})}},c=async l=>{let p=await a();if(!p||p.fileId!==l)throw new S("invalid_record");let m=await r.hosted.load(l);if(s(l).approved&&s(l).approved!==Ca(m))throw new S("invalid_record");if(!m.published&&s(l).approvedKeys&&s(l).approvedKeys!==Ua(m))throw new S("invalid_record");let h=s(l).secret;if(h){if(!p.backup)throw new S("backup_secret_required");let y;try{y=await W0(p.backup,h)}catch(b){throw new S("invalid_record",void 0,{cause:b})}if(Ca(m)!==Ca(y)||!m.published&&Ua(m)!==Ua(y))throw new S("invalid_record")}if((await r.hosted.load(l)).revision!==m.revision||(await a())?.revision!==p.revision)throw new S("store_conflict");return{saved:p,job:m}},d=async l=>{let{job:p}=await c(l),m=X(p.hosting),h=s(l),y=m.result,b={...j5(p),id:l,revision:p.revision,done:[...m.backupConfirmed?["backup"]:[],...m.completed],next:y?null:m.backupConfirmed?m.steps[m.completed.length]??null:"backup",pending:m.pending!==null,needs:y?[]:[...h.connection?[]:["wallet"],...h.file?[]:["file"],...m.backupConfirmed&&!h.secret?["secret"]:[]],registered:m.completed.includes("register"),result:y?{fileId:y.fileId,url:y.url,expiresAt:y.expiresAt}:null};return structuredClone(b)},f=async l=>{let p=await d(l);for(let m of i.get(l)??[])try{m(structuredClone(p))}catch{}return p},u=l=>({id:l,view:()=>d(l),subscribe(p){let m=i.get(l)??new Set;return i.set(l,m),m.add(p),()=>{m.delete(p)}},async exportBackup(){let{job:p,saved:m}=await c(l);if(X(p.hosting).backupConfirmed||X(p.hosting).pending||X(p.hosting).lease)throw new S("invalid_arguments");let h=lc(),y=await wn(p,h);if((await r.hosted.load(l)).revision!==p.revision)throw new S("store_conflict");if(!await e.indexStore.compareAndSet(hd,m,{...m,revision:m.revision+1,backup:y}))throw new S("store_conflict");return s(l).secret=h,{filename:`annon-seller-${l.slice(2)}.json`,text:y,secret:Y(h).slice(2)}},async confirmBackup(){let{saved:p}=await c(l);if(!s(l).secret||!p.backup)throw new S("backup_secret_required");await r.hosted.confirmBackup(l),await f(l)},async attachWallet(p){let{job:m}=await c(l),h=e.wallet(p);if(p.kind!==m.terms.seller.kind||Q(ne(h.wallet.identity))!==Q(m.terms.seller))throw new S("wrong_identity");s(l).connection=p,await f(l)},async attachFile(p){await c(l),await r.hosted.verifySource(l,dc(p)),s(l).file=p,await f(l)},async unlock(p){try{if(!/^[0-9a-f]{64}$/.test(p))throw new Error;let{job:m,saved:h}=await c(l);if(!h.backup)throw new Error;let y=G(`0x${p}`,32),b=await W0(h.backup,y);if(Ca(m)!==Ca(b)||!m.published&&Ua(m)!==Ua(b)||(await r.hosted.load(l)).revision!==m.revision)throw new Error;s(l).secret=y}catch(m){throw new S("invalid_record",void 0,{cause:m})}await f(l)},async next(p={}){if(p.signal?.aborted)throw new S("cancelled");let{job:m,saved:h}=await c(l),y=s(l);if(!y.secret||!h.backup||!X(m.hosting).backupConfirmed)throw new S("backup_secret_required");if(X(m.hosting).result)return d(l);if(!y.connection)throw new S("signer_required");if(!y.file)throw new S("file_required");let{wallet:b,signUpload:x}=e.wallet(y.connection);if(Q(ne(b.identity))!==Q(m.terms.seller))throw new S("wrong_identity");let g=(v,E)=>{try{p.onProgress?.({phase:v,done:E,total:X(y.file).size})}catch{}};g("encrypting",0),await r.hosted.next(l,{expectedRevision:m.revision,...p.txHash?{txHash:p.txHash}:{},data:dc(y.file),seller:b,hosting:{origin:e.host,...x?{signUpload:x}:{},spool:G5,body:async v=>(g("encrypting",X(y.file).size),g("uploading",0),new Response(v.read()).blob())}}),g("uploading",y.file.size);let w=await f(l);return w.result&&delete y.approvedKeys,w},async discard(){let p=await a();if(!p||p.fileId!==l)throw new S("invalid_record");if(await e.rawStore.load(`annon/sell/${l}`))try{await c(l),await r.hosted.discard(l)}catch(m){if(!(m instanceof S)||m.code!=="invalid_record")throw m}if(!await e.indexStore.compareAndSet(hd,p,null))throw new S("store_conflict");s(l).secret?.fill(0),n.delete(l)}});return{kind:"sdk",live:!0,async active(){let l=await a();return l?u(l.fileId):null},async quote(l,p){let{wallet:m,signUpload:h}=e.wallet(l);if(l.kind!==m.identity.kind)throw new S("wrong_identity");let y={data:dc(p.file),name:p.file.name,mime:p.file.type||"application/octet-stream",seller:m,price:String(Ty(p.priceUsdc,6)),title:p.title,description:p.description,hosting:{origin:e.host,...h?{signUpload:h}:{}},...m.identity.kind==="near"?{listingStorage:Ty(p.listingStorageNear??"0.01",24),storageBudget:Ty(p.storageBudgetNear??"0.05",24)}:{}},b=await r.hosted.quote(y),x=j5({terms:b.terms,name:b.metadata.filename,storageBudget:b.storageBudget??void 0,hosting:{origin:e.host,metadata:b.metadata,fee:b.fee,steps:b.steps,listingStorage:b.listingStorage}});return o.set(b.quoteId,{quote:structuredClone(b),draft:{...p},connection:l,shown:x}),structuredClone({...x,quoteId:b.quoteId,description:b.metadata.description,byteSize:p.file.size,...e.fileLifetimeDays===void 0?{}:{hostedDays:e.fileLifetimeDays}})},async begin(l){let p=o.get(l);if(!p)throw new S("invalid_arguments");let m=await a();if(m&&!await e.rawStore.load(`annon/sell/${m.fileId}`)){if(!await e.indexStore.compareAndSet(hd,m,null))throw new S("store_conflict");m=null}if(m&&!(await r.hosted.load(m.fileId)).published)throw new S("sell_incomplete");let h={id:"browser-sale",revision:(m?.revision??-1)+1,fileId:p.quote.fileId,backup:null},y=await r.hosted.begin(l);if(!await e.indexStore.compareAndSet(hd,m,h))throw await r.hosted.discard(h.fileId),new S("sell_incomplete");return n.set(h.fileId,{approved:Ca(y),approvedKeys:Ua(y),file:p.draft.file,connection:p.connection}),o.delete(l),u(h.fileId)}}}var an=class extends S{constructor(r,n,o){super(r,n,o);this.code=r;this.name="BrowserWalletError"}code};function Ee(e,t){throw new an(e,t)}async function $n(e){try{return await e()}catch(t){if(t instanceof an||t instanceof Vt)throw t;let r=t;for(let n=0;n<8&&r&&typeof r=="object";n++){let o=r;if(o.code===4001||o.code==="ACTION_REJECTED")throw new an("rejected","The wallet request was rejected.",{cause:t});if(o.code===4901||o.code===4902)throw new an("wrong_chain","Select Base in the wallet.",{cause:t});if(o.code===-32601||o.code===4200)throw new an("missing_method","The wallet does not support this method.",{cause:t});r=o.cause}throw new an("wallet_error","The wallet request failed.",{cause:t})}}function e_(e,t){let r=ne({kind:"evm",id:t}),n=a=>$n(async()=>{typeof e.request!="function"&&Ee("missing_method","EIP-1193 request is unavailable.");let c=await e.request(a);return a.method==="eth_accounts"&&(!Array.isArray(c)||!c.some(d=>typeof d=="string"&&d.toLowerCase()===r.id))&&Ee("wrong_identity","The wallet does not control the selected identity."),c}),o=U5({request:n},r.id),i=async()=>{let a=await n({method:"eth_chainId"});try{return typeof a!="string"||!/^0x[0-9a-f]+$/i.test(a)?!1:BigInt(a)===BigInt(hc)}catch{return!1}},s=async a=>{await i()||(a&&await n({method:"wallet_switchEthereumChain",params:[{chainId:"0x2105"}]}),(!a||!await i())&&Ee("wrong_chain","Select Base in the wallet.")),await n({method:"eth_accounts"})};return{identity:r,address:r.id,authorize:a=>$n(async()=>{await n({method:"eth_accounts"});let c;try{c=await o.authorize(a)}catch(d){throw d instanceof S&&d.code==="invalid_signature"&&Ee("invalid_signature","The wallet returned an invalid recovery signature."),d}return lt(r,a,c)||Ee("invalid_signature","The wallet returned an invalid recovery signature."),await n({method:"eth_accounts"}),c}),signTypedData:a=>$n(async()=>{a.domain.chainId!==hc&&Ee("wrong_chain","Payment authorization must name Base."),a.message.from.toLowerCase()!==r.id&&Ee("wrong_identity","Payment authorization names another identity."),await s(!0);let c=await o.signTypedData(a);return(typeof c!="string"||wf(gf(a.domain.verifyingContract,a.message),c)!==r.id)&&Ee("invalid_signature","The wallet returned an invalid payment signature."),await s(!1),c})}}function V5(e){try{return e?ne({kind:"solana",id:typeof e=="string"?e:Ut.encode(e instanceof Uint8Array?e:e.toBytes())}).id:Ee("wrong_identity","No Solana identity is selected.")}catch{return Ee("wrong_identity","The wallet returned another Solana identity.")}}function t_(e,t){let r=ne({kind:"solana",id:t}),n=()=>{V5(e.publicKey)!==r.id&&Ee("wrong_identity","Select the requested Solana identity.")};return{identity:r,authorize:o=>$n(async()=>{n();let i=e.signMessage?.bind(e);typeof i!="function"&&Ee("missing_method","Solana signMessage is unavailable.");let s=await i(new TextEncoder().encode(o)),a=s instanceof Uint8Array?s:s?.signature;!(s instanceof Uint8Array)&&s?.publicKey&&V5(s.publicKey)!==r.id&&Ee("wrong_identity","The signature names another Solana identity."),(!(a instanceof Uint8Array)||a.length!==64)&&Ee("invalid_signature","The wallet returned an invalid Solana signature.");let c={kind:"solana",sig:Y(a)};return lt(r,o,c)||Ee("invalid_signature","The wallet did not sign the exact recovery text."),n(),c})}}function r_(e,t){let r=ne({kind:"near",id:t}),n=async()=>{typeof e.getAccounts!="function"&&Ee("missing_method","NEAR getAccounts is unavailable.");let i=await e.getAccounts();return(!Array.isArray(i)||!i.some(s=>s?.accountId===r.id))&&Ee("wrong_identity","Select the requested NEAR identity."),i},o=N5({getAccounts:n,signAndSendTransaction:async i=>{typeof e.signAndSendTransaction!="function"&&Ee("missing_method","NEAR transaction signing is unavailable.");let s=await e.signAndSendTransaction({signerId:i.signerId,receiverId:i.receiverId,actions:i.actions.map(({params:a})=>({functionCall:{methodName:a.methodName,args:new TextEncoder().encode(JSON.stringify(a.args)),gas:BigInt(a.gas),deposit:BigInt(a.deposit)}}))});if(s&&typeof s=="object"&&"transaction"in s){let a=s.transaction;if(a?.signer_id!==r.id){if(a?.hash)throw new Vt(a.hash);Ee("wrong_identity","The transaction names another NEAR identity.")}}else Ee("invalid_response","The wallet returned no NEAR transaction.");return s}},r.id);return{identity:r,authorize:i=>$n(()=>o.authorize(i)),call:i=>$n(async()=>{let s=await o.call(i);try{await n()}catch{let a=s.transaction;throw new Vt(a.hash)}return s}),transferPurchase:(i,s)=>$n(()=>o.transferPurchase(i,s)),proveControl:(i,s)=>$n(async()=>{await n();let a=e.signMessage?.bind(e);typeof a!="function"&&Ee("missing_method","NEAR recovery requires NEP-413 signMessage.");try{await rf(r.id,i,s,async c=>{let d=await a(c);d||Ee("invalid_response","The wallet returned no NEP-413 signature."),d.accountId!==r.id&&Ee("wrong_identity","The signature names another NEAR identity.");try{(typeof d.publicKey!="string"||!d.publicKey.startsWith("ed25519:")||Ut.decode(d.publicKey.slice(8)).length!==32||typeof d.signature!="string"||wd.decode(d.signature).length!==64)&&Ee("invalid_signature","The wallet returned a malformed NEP-413 signature.")}catch{Ee("invalid_signature","The wallet returned a malformed NEP-413 signature.")}return d})}catch(c){throw c instanceof an||c instanceof S&&c.code==="invalid_signature"&&Ee("invalid_signature","The wallet returned an invalid NEP-413 ownership proof."),c}await n()})}}async function n_(e,t,r){let n=ac(t);if(n.seller.kind!=="near")throw new S("wrong_identity");return $n(async()=>{let o=async()=>{(!e.getAccounts||!e.signMessage)&&Ee("missing_method","NEAR hosting requires NEP-413 signing."),(await e.getAccounts()).some(c=>c.accountId===n.seller.id)||Ee("wrong_identity","Select the requested NEAR identity.")};await o();let i={message:co(n),recipient:n.hostOrigin,nonce:G(n.nonce,32)},s=await X(e.signMessage,"invalid_response").call(e,{...i,nonce:i.nonce.slice()});return await ic(n.seller.id,i,s,r),await o(),{kind:"near",accountId:X(s,"invalid_response").accountId,publicKey:X(s,"invalid_response").publicKey,signature:X(s,"invalid_response").signature}})}export{$i as Annon,S as AnnonError,q6 as BASE_ELIGIBILITY_MAX_AGE_SECONDS,Oa as BROWSER_DOWNLOAD_LIMIT,Sf as BaseRpcRateLimited,_y as BrowserPurchaseController,an as BrowserWalletError,af as CkdError,$e as DownloadError,Hi as FileFundingRefused,df as HTTP_RETRY_MAX_WAIT_SECONDS,qr as MAX_PAY2_BYTES,Dr as MAX_PLAINTEXT_BYTES,ts as NearError,nc as NearRpcRateLimited,Mi as OneClick,od as OneClickQuoteExpired,Dl as OneClickRefused,Re as Pay2Error,re as PayError,_p as PurchaseLeaseBusy,Do as SellError,br as SourceChangedError,Vt as TransactionUncertain,sc as UploadClient,Z4 as browserAnnon,vy as browserDownload,e_ as browserEvmWallet,r_ as browserNearWallet,Ay as browserPurchaseStorage,G5 as browserSellerSpool,J4 as browserSellerStorage,t_ as browserSolanaWallet,xp as canonicalManifestUrl,W4 as catalog,Wh as checkBaseSponsorship,Q4 as createBrowserSeller,Z0 as exportSellerKey,sm as fileFundingText,AS as importSellerKey,Na as isTransient,V4 as listShops,lc as newBackupSecret,c4 as originFromToken,n_ as signNearUpload,Ko as toPublicError,co as uploadText,Vh as validBaseSponsorship,jh as validateRefundAddress};
57
+ recovery: ${Ke(n.recovery)}`;if(n.recovery.kind==="near"){let s=Lo(r);if(!s.proveControl)throw new S("missing_method","NEAR recovery requires an account ownership proof before payment");await s.proveControl(o,{contractId:this.o.contractId,nearRpc:this.o.nearRpc})}else await this.auth(r,o);let i={...n,revision:n.revision+1,recoveryProved:!0};if(!await this.store.compareAndSet(it(n.id),n,i))throw new re("store_conflict");return i}async accept(t,r=t?.id,n={}){if(t&&lf(t),!r)throw new S("purchase_required","missing purchase id");if(await so(this.o.nearRpc,this.o.contractId,r))return!0;if(t?.purchase.route!=="base-usdc")return!1;if(!this.o.baseRpc)throw new S("base_rpc_required","configure baseRpc to resume a Base purchase");let o=await V6(t,{nearRpc:this.o.nearRpc,baseRpc:this.o.baseRpc,store:this.store});if(o.step==="unlock"){let i=await this.call("unlock",{args:o.args},n.unlockWallet??this.selfUnlockWallets.get(r));if(this.unlocked.set(r,i),this.unlocked.size>64){let s=this.unlocked.keys().next().value;s!==void 0&&this.unlocked.delete(s)}}return await so(this.o.nearRpc,this.o.contractId,r)!==null}async open(t){return this.openSource(t)}async openTo(t){return jg(t.file,r=>this.openSource({...t,file:r}),t.spool)}async openSource(t){if((t.file instanceof Uint8Array?t.file.length:t.file.size)>50086016)throw new $e("too_large");if(!t.record&&!t.recovery)throw new S("purchase_required","a saved purchase or recovery grant is required");let r=t.recovery;if(r&&r.grant===null)throw new S("recovery_not_final","recovery grant is not final");let n=r?.purchase_id??t.record?.id;if(!n)throw new S("purchase_required","missing purchase id");if(!await this.accept(t.record,n))throw new re("settlement_pending","purchase not accepted; check status and resume");let o=r?.file_id??t.record?.purchase.file_id;if(!o)throw new S("file_required","missing file id");let i=r?.grant??0,s=r?.buyerSecret??t.record?.buyerSecret;if(!s)throw new S("invalid_record","missing buyer secret");let a=G(s,32),c=await so(this.o.nearRpc,this.o.contractId,n),d=await C0(this.o.nearRpc,this.o.contractId,n,i);if(!c||c.file_id!==o||!d||Y(jt(a).publicKeyBytes)!==d.buyer_key)throw new S("invalid_record","saved key does not match the final grant");let f=await this.file(o),u=t.file instanceof Uint8Array?void 0:await Gg(t.file,{listing:gp(o,f),contractId:this.o.contractId}),l=await ni(u?u.header:t.file.subarray(0,new DataView(t.file.buffer,t.file.byteOffset).getUint32(8)),gp(o,f),this.o.contractId);if(t.record&&Y(l.headerHash)!==t.record.checkedHeaderHash)throw new S("file_mismatch","header differs from the checked purchase header");let p=i===0?this.unlocked.get(n):void 0;i===0&&this.unlocked.delete(n);let m;if(p)try{m=await this.answer(p,a,o)}catch{}if(m||(m=await this.answer(await this.call("claim_key",{purchase_id:n,grant:i}),a,o)),u){if(!t.sink)throw new S("invalid_arguments","a plaintext sink is required");let y=await u.writeTo(t.sink,async()=>m);if(y.size>5e7)throw new $e("too_large");return{meta:y}}let h=await ig(t.file,{contractId:this.o.contractId,listing:gp(o,f),ckdSecret:async()=>m});if(h.meta.size>5e7)throw new $e("too_large");return h}async recover(t){let r=ne(t.wallet.identity),n=[];if(t.purchaseId)n.push(t.purchaseId);else{let i=t.limit??50;for(let s=0;;s+=i){let a=await Cg(this.o.nearRpc,this.o.contractId,r,s,i);if(n.push(...a),a.length<i)break}}let o=[];for(let i of n)try{let s=await so(this.o.nearRpc,this.o.contractId,i);if(!s||Q(s.recovery)!==Q(r))throw new S("wrong_identity","purchase recovery identity mismatch");await this.file(s.file_id);let a=`annon/recovery/${i}`,c=await this.recoveries.load(a);if(c?.grant!==null&&c?.grant!==void 0){o.push(c);continue}if(!c){let m=fo();if(c={kind:"recovery",id:`recovery:${i}`,revision:0,purchase_id:i,file_id:s.file_id,recovery:r,buyerSecret:Y(m.secret),fresh_key:Y(m.publicKeyBytes),nonce:`0x${on(32)}`,deadline:this.now()+540,grant:null},!await this.recoveries.compareAndSet(a,null,c))throw new re("store_conflict")}let d=c,f=async m=>{for(let h=1;h<m;h++)if((await C0(this.o.nearRpc,this.o.contractId,i,h))?.buyer_key===d.fresh_key)return h;return null},u=await f(s.grants),l;if(u===null){if(c.deadline<=this.now()){await this.o.writeBackup(`${c.id}:revision:${c.revision}`,await is(c,this.o.backupSecret));let b=fo(),x={...c,revision:c.revision+1,buyerSecret:Y(b.secret),fresh_key:Y(b.publicKeyBytes),nonce:`0x${on(32)}`,deadline:this.now()+540};if(!await this.recoveries.compareAndSet(a,c,x))throw new re("store_conflict");c=x,d=x}await this.o.writeBackup(c.id,await is(c,this.o.backupSecret));let m={purchase_id:i,fresh_key:c.fresh_key,nonce:c.nonce,deadline:c.deadline},h=await this.auth(t.wallet,Nw({...m,contract:this.o.contractId,file_id:s.file_id,recovery:r}));l=await this.call("reopen",{args:m,...h?{auth:h}:{}},t.wallet);let y=await so(this.o.nearRpc,this.o.contractId,i);u=await f(y?.grants??s.grants)}if(u===null)throw new S("recovery_not_final","reopen grant is not final; resume the saved recovery");l&&typeof l=="object"&&("big_y"in l||"answer"in l)&&await this.answer(l,G(c.buyerSecret,32),s.file_id);let p={...c,revision:c.revision+1,grant:u};if(!await this.recoveries.compareAndSet(a,c,p))throw new re("store_conflict");o.push(p)}catch(s){if(t.purchaseId)throw s;t.onError?.(i,s)}return o}async stop(t){let r=await this.file(t.fileId);if(Q(r.seller)!==Q(t.seller.identity))throw new S("wrong_identity","not the registered seller");let n={file_id:t.fileId,key:null,deadline:this.now()+540},o=await this.auth(t.seller,Mw(this.o.contractId,n,r.seller));await this.call("stop_sales",{args:n,...o?{auth:o}:{}},t.seller)}};var W4="/.well-known/annon-shop.json";function Pr(e){if(typeof e!="string")throw new TypeError("invalid URL");let t=new URL(e);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash)throw new TypeError("invalid discovery URL");return t.href}function Pa(e){let t=new URL(Pr(e));if(t.pathname!=="/")throw new TypeError("service must be an origin");return t.origin}function wp(e){return new URL(W4,Pr(e)).href}var Z4=e=>typeof e=="string"&&/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(e);function Li(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("invalid object");return e}function xp(e){if(typeof e!="string")throw new TypeError("invalid text")}function md(e,t=Number.MAX_SAFE_INTEGER){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0||e>t)throw new TypeError("invalid integer")}function D5(e){try{let t=Li(e),r={};if(t.shopDirectoryUrl!==void 0&&(r.shopDirectoryUrl=Pr(t.shopDirectoryUrl)),t.shops!==void 0){if(!Array.isArray(t.shops)||t.shops.length>100)throw new TypeError("invalid shops");let n=new Set,o=new Set;r.shops=t.shops.map(i=>{let s=Li(i);ae(s,["manifest",...["id","profile"].filter(d=>Object.hasOwn(s,d))]);let a=wp(s.manifest);if(o.has(a))throw new TypeError("duplicate shop");o.add(a);let c={manifest:a};if(s.id!==void 0){if(!Z4(s.id)||n.has(s.id))throw new TypeError("invalid alias");n.add(s.id),c.id=s.id}if(s.profile!==void 0){let d=Li(s.profile);if(ae(d,["network","contract","nearRpc","relayer","host",...Object.hasOwn(d,"baseRpc")?["baseRpc"]:[]]),d.network!=="near:mainnet")throw new TypeError("invalid profile network");c.profile={network:d.network,contract:be(d.contract),nearRpc:Pr(d.nearRpc),...d.baseRpc!==void 0?{baseRpc:Pr(d.baseRpc)}:{},relayer:Pa(d.relayer),host:Pa(d.host)}}return c})}if(t.defaultShop!==void 0){if(xp(t.defaultShop),!r.shops?.some(n=>n.id===t.defaultShop||n.manifest===t.defaultShop))throw new TypeError("unknown default shop");r.defaultShop=t.defaultShop}return r}catch(t){throw new S("invalid_config",void 0,{cause:t})}}function Y4(e){let t=Li(e),r=["uploadsPerPersonPerDay","attemptsPerPersonPerDay","fileLifetimeDays","maxFileBytes"];if(ae(t,["text",...r.filter(n=>Object.hasOwn(t,n))]),xp(t.text),!t.text.trim()||new TextEncoder().encode(t.text).byteLength>4096||/[\p{Cc}\p{Cs}\u2028\u2029]|(?![\u200c\u200d])\p{Cf}/u.test(t.text))throw new TypeError("invalid rules text");for(let n of r)Object.hasOwn(t,n)&&(n==="fileLifetimeDays"&&t[n]===null||md(t[n]));return t}function X4(e){let t=Li(e);ae(t,["version","name","shopUrl","network","contract","relayer","host","catalog",...Object.hasOwn(t,"rules")?["rules"]:[]]);let r=Li(t.catalog);if(ae(r,["url","format","search"]),t.version!==1||t.network!=="near:mainnet"||r.format!=="annon-catalog-array-v1"||r.search!=="client")throw new TypeError("unsupported manifest");if(xp(t.name),!t.name.trim())throw new TypeError("missing shop name");let n=Pa(t.host),o=Pr(r.url);if(new URL(o).origin!==n)throw new TypeError("catalog origin mismatch");return{version:1,...Object.hasOwn(t,"rules")?{rules:Y4(t.rules)}:{},name:t.name,shopUrl:Pr(t.shopUrl),network:t.network,contract:be(t.contract),relayer:Pa(t.relayer),host:n,catalog:{url:o,format:r.format,search:r.search}}}async function wy(e,t,r){try{let n=await r(Pr(e),{credentials:"omit",redirect:"error",cache:"no-store",signal:AbortSignal.timeout(1e4)});if(n.status!==200||n.redirected||n.url&&n.url!==e||!n.body)throw new S("bad_response");let o=n.body.getReader();try{if(Number(n.headers.get("content-length"))>t)throw new S("too_large");let i=0,s=[];for(;;){let{done:d,value:f}=await o.read();if(d)break;if(i+=f.byteLength,i>t)throw new S("too_large");s.push(f)}let a=new Uint8Array(i),c=0;for(let d of s)a.set(d,c),c+=d.byteLength;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch(d){throw new S("invalid_record",void 0,{cause:d})}}finally{await o.cancel().catch(()=>{})}}catch(n){throw n instanceof S?n:new S("transport",void 0,{cause:n})}}async function q5(e,t=globalThis.fetch){let r=wp(e.manifest),n;try{let o=Li(await wy(r,65536,t)),i=e.profile;if(i&&(o.network!==i.network||o.contract!==i.contract||Pa(o.relayer)!==i.relayer||Pa(o.host)!==i.host||o.nearRpc!==void 0&&Pr(o.nearRpc)!==i.nearRpc||o.baseRpc!==void 0&&Pr(o.baseRpc)!==i.baseRpc))throw new S("config_conflict");n=X4(o)}catch(o){throw o instanceof S?o:new S("invalid_record",void 0,{cause:o})}return{manifest:r,...e.id!==void 0?{id:e.id}:{},info:n,trusted:e.profile!==void 0}}function j5(e){let{limit:t=20,offset:r=0,search:n=""}=e;if(!Number.isSafeInteger(t)||t<1||t>100||!Number.isSafeInteger(r)||r<0||typeof n!="string")throw new S("invalid_arguments");return{limit:t,offset:r,search:n.toLowerCase()}}function G5(e,{limit:t,offset:r}){let n=e.slice(r,r+t),o=r+n.length<e.length?r+n.length:null;return{items:n,total:e.length,nextOffset:o}}async function V5(e,t){let r=[...e.shops??[]];if(e.shopDirectoryUrl){let n=await wy(e.shopDirectoryUrl,262144,t);try{if(ae(n,["version","shops"]),n.version!==1||!Array.isArray(n.shops))throw new TypeError("invalid directory");if(n.shops.length>100)throw new S("too_large");for(let o of n.shops){ae(o,["manifest"]);let i=wp(o.manifest);r.some(s=>s.manifest===i)||r.push({manifest:i})}}catch(o){throw o instanceof S?o:new S("invalid_record",void 0,{cause:o})}}return r}async function J4(e={},t={},r=globalThis.fetch){let n=j5(t),o=D5(e),i=await V5(o,r),s=new Array(i.length),a=0,c=await Promise.allSettled(Array.from({length:Math.min(4,i.length)},async()=>{for(;a<i.length;){let d=a++,f=X(i[d]);try{s[d]=await q5(f,r)}catch(u){if(f.profile&&u instanceof S&&u.code==="config_conflict")throw u;s[d]={manifest:f.manifest,...f.id!==void 0?{id:f.id}:{},trusted:!!f.profile,error:Ko(u).code}}}}));for(let d of c)if(d.status==="rejected")throw d.reason;return G5(s.filter(d=>("info"in d?d.info.name:d.id??d.manifest).toLowerCase().includes(n.search)),n)}function Q4(e,t){if(!Array.isArray(e))throw new TypeError("invalid catalog");if(e.length>1e4)throw new S("too_large");return e.map(r=>{ae(r,["name","fileId","title","description","url","header","byteSize","plaintextSize","createdAt","expiresAt","termsHash","terms","salesStopped","takenDown"]);for(let o of["name","title","description"])xp(r[o]);G(r.fileId,32),G(r.termsHash,32);for(let o of["url","header"])if(new URL(Pr(r[o])).origin!==t.host)throw new S("config_conflict");if(md(r.byteSize,50086016),md(r.plaintextSize,5e7),md(r.createdAt),r.expiresAt!==null&&(md(r.expiresAt),r.expiresAt<r.createdAt))throw new TypeError("invalid expiry");if(typeof r.salesStopped!="boolean"||typeof r.takenDown!="boolean")throw new TypeError("invalid listing flags");let n=r.terms;if(n.contract!==t.contract||n.network!==t.network)throw new S("config_conflict");if(n.file_id!==r.fileId||tt(n)!==r.termsHash)throw new TypeError("invalid catalog terms");return r})}async function e_(e,t={},r=globalThis.fetch){let n=j5(t),o=D5(e),i=t.shop??o.defaultShop;if(typeof i!="string"||!i)throw new S("invalid_arguments");let a=o.shops?.find(f=>f.id===i||f.manifest===i)??(await V5(o,r)).find(f=>f.manifest===i);if(!a)throw new S("invalid_arguments");let c=await q5(a,r),d;try{d=Q4(await wy(c.info.catalog.url,8388608,r),c.info)}catch(f){throw f instanceof S?f:new S("invalid_record",void 0,{cause:f})}return d=d.filter(f=>[f.name,f.title,f.description].some(u=>u.toLowerCase().includes(n.search))),d.sort((f,u)=>u.createdAt-f.createdAt||(f.fileId<u.fileId?-1:f.fileId>u.fileId?1:0)),{...G5(d,n),...c.info.rules?{shop:{manifest:c.manifest,name:c.info.name},rules:c.info.rules}:{}}}var Ra=50086016;function vp(e,t){try{e?.(t)}catch{}}async function xy(e){if(e.size!==void 0&&(!Number.isSafeInteger(e.size)||e.size<0))throw new TypeError("invalid file size");if(e.size!==void 0&&e.size>Ra)throw new $e("too_large","File exceeds the 50 MB size limit.");if(e.signal?.aborted)throw new $e("cancelled");let t=await ni(e.header,e.listing,e.contractId);if(Y(t.headerHash)!==e.checkedHeaderHash)throw new $e("file_mismatch","header differs from the checked purchase header");let r=Ow({...e,maxBytes:Ra}).getReader(),n=[],o=0;try{for(;;){let i=await r.read();if(e.signal?.aborted)throw new $e("cancelled");if(i.done)return Te(...n);if(o+=i.value.length,o>Ra)throw new $e("too_large","File exceeds the 50 MB size limit.");n.push(i.value),vp(e.onProgress,{phase:"downloading",received:o,...e.size===void 0?{}:{total:e.size}})}}finally{await r.cancel().catch(()=>{}),r.releaseLock()}}function Ey(e){if(e.state!=="failed"||!e.purchase)throw new Error("only a failed saved purchase can be checked again");return Sy(e,e.purchase),e.purchase}var vy=e=>e?.quote?.deposit;function Sy(e,t){if(e.route!=="1click")return;let r=vy(e.purchase),n=vy(t),o=e.checkpoint;if(r?.address!==n?.address||r?.memo!==n?.memo||o&&(o.address!==r?.address||o.memo!==r?.memo))throw new Error("saved purchase changed deposit; check it with support")}var t_={SUCCESS:"accepting",REFUNDED:"refunded"};function r_(e,t,r,n){let o=e&&e.address===t&&e.memo===r?e:{address:t,...r===void 0?{}:{memo:r},attempts:0,errors:0},{nextPollAt:i,...s}=o;return{...s,attempts:s.attempts+1,errors:0,lastStatus:n}}async function K5(e,t,r={}){let n=e.record,o=Ey(n);if(n.route==="1click"){let c=await t.loadCanonical(o.id);c&&Sy(n,c)}let i=await t.restorePurchase(o);if(i.id!==n.purchase?.id)throw new Error("saved purchase changed identity");if(Sy(n,i),JSON.stringify(i)!==JSON.stringify(n.purchase)&&(n=await e.change({purchase:i})),await t.accept(i))return n=await e.change({state:"accepted"}),{state:n.state};let s=vy(i);if(n.route!=="1click"||!s)return{state:n.state};let a=await(r.oneClick??new Fn).status(s.address,{...s.memo===void 0?{}:{memo:s.memo},...r.signal?{signal:r.signal}:{}});return n=await e.change({checkpoint:r_(n.checkpoint,s.address,s.memo,a),state:t_[a.status]??"failed"}),{state:n.state,swapStatus:a.status}}var _y="annon/browser/index",cr=()=>new S("store_conflict","browser purchase store conflict; reload the saved purchase"),Ay=e=>`annon/browser/entry/${e}`,Sp=e=>`annon/browser/backup/${e}`,W5=32;async function Iy(e={}){let t=fc(e),r="annon/browser/secret",n=await t.load(r);if(!n){let b={id:"browser-secret",revision:0,secret:Y(uc())};await t.compareAndSet(r,null,b)?n=b:n=await t.load(r)}if(n?.id!=="browser-secret")throw new Error("local backup secret missing");let o=G(n.secret,32),i=fc(e),s=ow(i,o),a=iw(i,o),c=()=>s.load(_y),d=()=>({kind:"browser-purchase-index",id:"browser-index",revision:0,entries:[]});async function f(b){for(let x=0;x<W5;x++){let g=await c(),w=g?structuredClone({...g,revision:g.revision+1}):d(),v=await b(w),E=await yf(_y,w,o);if(await i.compareAndSetMany([{key:_y,expected:g,next:E},...v]))return}throw cr()}let u=async b=>{let x=await a.load(Ay(b));if(!x)return null;let{kind:g,...w}=x;return w},l=async(b,x,g=!1)=>{dc(b,x),await f(async w=>{if(g&&x.purchase&&w.entries.some(N=>N.purchaseId===x.purchase?.id))throw cr();let v=w.entries.find(N=>N.id===x.id);if(b?!v||v.revision!==b.revision:v)throw cr();let E=Date.now(),B={id:x.id,revision:x.revision,fileId:x.fileId,route:x.route,state:x.state,resourceUrl:x.resourceUrl,createdAt:v?.createdAt??E,updatedAt:Math.max(v?.updatedAt??E,E),...x.purchase?{purchaseId:x.purchase.id}:{}};return v?w.entries[w.entries.indexOf(v)]=B:w.entries.push(B),[{key:Ay(x.id),expected:b,next:await yf(Ay(x.id),{...x,kind:"browser-purchase"},o)}]})},p=sw(i,o),m=b=>`annon/browser/archives/${b}`,h=async b=>{let x=await p.load(m(b));return Promise.all((x?.names??[]).map(async g=>{let w=await i.load(Sp(g));if(!w)throw new Error("recovery archive missing");let v=await mf(w.backup,o);if(v.purchase_id!==b||g!==`${v.id}:revision:${v.revision}`)throw new Error("recovery archive mismatch");return v}))},y=async(b,x)=>{let g=Sp(b),w=b.replace(/:revision:[0-9]+$/,""),v=w.startsWith("recovery:")?await mf(x,o):void 0,E=v?.revision??(/^0x[0-9a-f]{64}$/.test(w)?(await V0(x,o)).revision:void 0),B=b!==w;if(B&&(!v||b!==`${v.id}:revision:${v.revision}`))throw new TypeError("invalid recovery archive name");for(let N=0;N<W5;N++){let U=await i.load(g);if(E!==void 0&&U?.sourceRevision!==void 0&&U.sourceRevision>=E)return;let R={...E===void 0?{}:{sourceRevision:E},id:b,revision:U?U.revision+1:0,backup:x};if(B&&v){let T=m(v.purchase_id),O=await p.load(T),H=O?.names??[],P={kind:"browser-recovery-archives",id:`recovery-archives:${v.purchase_id}`,revision:O?O.revision+1:0,purchaseId:v.purchase_id,names:H.includes(b)?H:[...H,b]};if(await i.compareAndSetMany([{key:g,expected:U,next:R},{key:T,expected:O,next:await yf(T,P,o)}]))return}else if(await i.compareAndSet(g,U,R))return}throw cr()};return{rawStore:i,backupSecret:o,load:u,save:l,writeBackup:y,recoveryArchives:h,async restorePurchase(b){let x=mi(i,o),g=it(b.id),w=await x.load(g);if(w&&(w.message!==b.message||w.buyerSecret!==b.buyerSecret))throw cr();if(w&&w.revision>=b.revision)return w;let v={...b,revision:w?w.revision+1:0};if(!await x.compareAndSet(g,w,v))throw cr();return await y(v.id,await pf(v,o)),v},async list(){return((await c())?.entries??[]).map(({id:b,fileId:x,route:g,state:w})=>({id:b,fileId:x,route:g,state:w}))},async exportReceipt(b,x){let g=await u(b);if(!g)throw new Error("purchase missing");let w=structuredClone(g);if(g.purchase&&(w.recoveryArchives=await h(g.purchase.id)),g.purchase){let v=await mi(i,o).load(it(g.purchase.id));v&&v.revision>=g.purchase.revision&&(w.purchase=v);let E=await i.load(Sp(g.purchase.id));if(E){let U=await V0(E.backup,o);U.revision>(w.purchase?.revision??-1)&&(w.purchase=U)}let B=await lc(i,o).load(`annon/recovery/${g.purchase.id}`),N=await i.load(Sp(`recovery:${g.purchase.id}`));B?w.recovery=B:N&&(w.recovery=await mf(N.backup,o))}return rw({kind:"browser-receipt",entry:w},x)},async importReceipt(b,x){let{entry:g}=await nw(b,x);if(await u(g.id))throw cr();if(g.purchase){if((await c())?.entries.some(N=>N.purchaseId===g.purchase?.id))throw cr();let v=mi(i,o),E={...g.purchase,revision:0},B=await v.load(it(E.id));if(B&&(B.message!==E.message||B.buyerSecret!==E.buyerSecret)||!B&&!await v.compareAndSet(it(E.id),null,E))throw cr();g.purchase=B??E}if(g.recovery){let w=lc(i,o),v=`annon/recovery/${g.recovery.purchase_id}`,E=await w.load(v);if(E&&E.buyerSecret!==g.recovery.buyerSecret)throw cr();let B={...g.recovery,revision:0};if(!E&&!await w.compareAndSet(v,null,B))throw cr();g.recovery=E??B}for(let w of g.recoveryArchives??[])await y(`${w.id}:revision:${w.revision}`,await is(w,o));return await l(null,{...g,revision:0,needsProof:!0,lease:void 0,state:["terms_review","refunded","failed","expired","recovering","accepted","file_ready","abandoned"].includes(g.state)?g.state:"payment_uncertain"},!0),g.id}}}function n_(e,t){return new $i({...t,rawStore:e.rawStore,backupSecret:e.backupSecret,writeBackup:e.writeBackup})}var o_=120,i_=3e4,Ep=class extends S{constructor(r){super("lease_busy","Another tab holds this purchase; wait for its lease to expire.");this.waitUntil=r;this.name="PurchaseLeaseBusy"}waitUntil;code="lease_busy"},Ty=class e{constructor(t){this.options=t;this.storage=t.storage}options;storage;owner=crypto.randomUUID();listeners=new Set;static async create(t,r){let n={id:r.id,revision:0,fileId:r.fileId,header:Y(r.header),resourceUrl:r.resourceUrl,route:r.route,maxPrice:String(r.maxPrice),state:"terms_review",submission:"not_submitted"};return await t.storage.save(null,n),new e({...t,id:r.id})}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}async read(){let t=await this.storage.load(this.options.id);if(!t)throw new Error("purchase missing");return t}async snapshot(){let t=await this.read();return{id:t.id,state:t.state,revision:t.revision,fileId:t.fileId,route:t.route,resourceUrl:t.resourceUrl,...this.waiting(t),...t.checkpoint?.lastStatus?{swapStatus:t.checkpoint.lastStatus.status}:{}}}now(){return(this.options.now??(()=>Math.floor(Date.now()/1e3)))()}waiting(t){return t.lease&&t.lease.expiresAt>this.now()?{leaseWaitUntil:t.lease.expiresAt}:{}}emit(t){for(let r of this.listeners)try{r(t)}catch{}}busy(t){if(!(!t.lease||t.lease.expiresAt<=this.now()))return this.emit({id:t.id,state:t.state,revision:t.revision,...this.waiting(t)}),new Ep(t.lease.expiresAt)}async withLease(t,r={}){let n=await this.read(),o=this.busy(n);if(o)throw o;if(r.initial?.state==="preparing"&&n.state!=="terms_review")throw new Error("purchase already started; resume the saved purchase");let i=()=>({owner:this.owner,expiresAt:this.now()+o_}),s={record:await this.change(n,{...r.initial,lease:i()}),change:u=>d(async()=>{if(c)throw c;if(s.record.lease?.owner!==this.owner||s.record.lease.expiresAt<=this.now())throw new Error("purchase lease expired; resume the saved purchase");return s.record=await this.change(s.record,{...u,lease:i()}),s.record})},a=Promise.resolve(),c;function d(u){let l=a.then(u);return a=l.catch(()=>{}),l}let f=setInterval(()=>{s.change({}).catch(u=>{c=u})},i_);try{let u=await t(s);return r.finalCheckpoint!==!1&&await s.change({}),u}finally{clearInterval(f),await a,await this.change(s.record,{lease:void 0}).catch(()=>{})}}async change(t,r){let n={...t,...r,id:t.id,revision:t.revision+1};await this.storage.save(t,n);let o={id:n.id,state:n.state,revision:n.revision,...n.checkpoint?.lastStatus?{swapStatus:n.checkpoint.lastStatus.status}:{}};return this.emit(o),n}async start(t){let r=await this.read();if(r.state!=="terms_review")throw new Error("purchase already started; resume the saved purchase");if(r.route==="base"&&typeof t.submitBase!="function")throw new TypeError("Base requires submitBase");await this.withLease(async n=>{let o=async i=>{await n.change(i)};try{let i=await this.options.sdk.buy({...t,fileId:n.record.fileId,header:G(n.record.header,(n.record.header.length-2)/2),url:n.record.resourceUrl,route:n.record.route,maxPrice:BigInt(n.record.maxPrice),beforeSave:async s=>{await o({purchase:s,...n.record.route==="base"&&s.attempts.some(a=>!!a.payload)?{submission:"uncertain"}:{}})},onSaved:async s=>{n.record.purchase?.revision!==s.revision&&await o({purchase:s,...n.record.route==="base"&&s.attempts.some(a=>!!a.payload)?{submission:"uncertain"}:{}})},beforePayment:async s=>{if(!s.recoveryProved||n.record.purchase?.id!==s.id)throw new Error("durable recovery proof required");if(n.record.lease?.owner!==this.owner||n.record.lease.expiresAt<=this.now())throw new Error("purchase lease expired");n.record.route!=="1click"&&await o({state:"payment_uncertain",purchase:s,submission:"uncertain",paymentStarted:!0})}});await o({purchase:i.record,state:n.record.route==="1click"?"awaiting_deposit":"payment_uncertain",submission:n.record.route==="1click"?"not_submitted":i.uncertain?"uncertain":n.record.submission==="not_submitted"?"not_submitted":"submitted"})}catch(i){throw await n.change({state:n.record.purchase?"payment_uncertain":"terms_review"}).catch(()=>{}),i}},{initial:{state:"preparing",submission:"not_submitted"},finalCheckpoint:!1})}deposit(t){return t.purchase?.quote?.deposit}async instructions(){let t=await this.read(),r=this.deposit(t);return!["awaiting_deposit","incomplete_deposit"].includes(t.state)||t.needsProof||!t.purchase?.recoveryProved||!r||!Number.isFinite(Date.parse(r.depositBefore))||Date.parse(r.depositBefore)-this.now()*1e3<6e5?null:structuredClone(r)}async resume(t={}){let r=await this.read();if(this.busy(r)||["terms_review","refunded","failed","file_ready","accepted","abandoned"].includes(r.state))return;if(r.state==="recovering"){t.recovery&&await this.recover(t.recovery);return}let n=r.lease!==void 0;return this.withLease(async o=>{if(r=o.record,!r.purchase){await o.change({state:"terms_review"});return}let i=r.purchase,s=i.attempts.some(l=>!!l.payload);if(r.route!=="1click"&&r.submission==="not_submitted"&&!s&&!r.paymentStarted&&!r.purchase.nearSubmission){await o.change({state:"abandoned"});return}(n||s)&&r.submission==="not_submitted"&&(r=await o.change({...s?{submission:"uncertain"}:{}}));let a=await this.storage.restorePurchase(i);JSON.stringify(a)!==JSON.stringify(r.purchase)&&(r=await o.change({purchase:a}));let c=()=>r.route==="base"&&a.paymentState!=="expired"&&(s||r.submission!=="not_submitted"||r.state==="accepting");if(c()&&r.state!=="accepting"&&(r=await o.change({state:"accepting"})),await this.options.sdk.accept(a)){await o.change({state:"accepted"});return}a=await this.storage.restorePurchase(a),JSON.stringify(a)!==JSON.stringify(r.purchase)&&(r=await o.change({purchase:a}));let d=r.checkpoint?.lastStatus?.status,f=d==="SUCCESS"||r.state==="accepting"?"accepting":d==="PROCESSING"||d==="KNOWN_DEPOSIT_TX"||r.state==="processing"?"processing":null;if(r.route==="1click"&&f){await o.change({state:f});return}if(r.state==="expired"&&r.route!=="base")return;if(r.route!=="1click"){await o.change({state:c()?"accepting":this.now()>=Number(a.purchase.expires_at)?"expired":r.submission==="submitted"?"accepting":"payment_uncertain"});return}let u=this.deposit(r);if(!u||!Number.isFinite(Date.parse(u.depositBefore))||Date.parse(u.depositBefore)-this.now()*1e3<6e5){await o.change({state:"expired"});return}if(r.needsProof||!r.purchase?.recoveryProved){if(!t.recovery)return;let l=await this.options.sdk.proveRecovery(a,t.recovery);if(r=await o.change({purchase:l,needsProof:!1}),Date.parse(u.depositBefore)-this.now()*1e3<6e5){await o.change({state:"expired"});return}}await o.change({state:d==="SUCCESS"?"accepting":d==="INCOMPLETE_DEPOSIT"?"incomplete_deposit":d==="PROCESSING"?"processing":"awaiting_deposit"})})}async poll(t={}){return this.withLease(async r=>{let n=r.record,o=this.deposit(n);if(n.route!=="1click"||!o||["terms_review","accepted","recovering","file_ready","refunded","failed","abandoned"].includes(n.state))throw new Error("no pollable 1Click deposit in this state");let{oneClick:i=new Fn,...s}=t;await i.poll(o.address,{...s,...o.memo===void 0?{}:{memo:o.memo},...n.checkpoint?{checkpoint:n.checkpoint}:{},onProgress:async a=>{let c=a.lastStatus?.status,f=c?{PENDING_DEPOSIT:"awaiting_deposit",KNOWN_DEPOSIT_TX:"processing",PROCESSING:"processing",INCOMPLETE_DEPOSIT:"incomplete_deposit",SUCCESS:"accepting",REFUNDED:"refunded",FAILED:"failed"}[c]??n.state:n.state;["awaiting_deposit","incomplete_deposit"].includes(f)&&(n.state==="expired"||Date.parse(o.depositBefore)<=this.now()*1e3)&&(f="expired"),n=await r.change({checkpoint:a,state:f})}}),n.state==="accepting"&&n.purchase&&await this.options.sdk.accept(n.purchase)&&await r.change({state:"accepted"})})}async reconcile(t={}){let r=await this.read(),n=this.busy(r);if(n)throw n;return Ey(r),this.withLease(o=>K5(o,{accept:i=>this.options.sdk.accept(i),restorePurchase:i=>this.storage.restorePurchase(i),loadCanonical:i=>mi(this.storage.rawStore,this.storage.backupSecret).load(it(i))},t))}async recover(t){return this.withLease(async r=>{let n=r.record;if(!n.purchase)throw new Error("saved purchase required");let o=await this.storage.restorePurchase(n.purchase);n=await r.change({state:"recovering",purchase:o});let s=(await this.options.sdk.recover({wallet:t,purchaseId:o.id}))[0];if(!s||s.grant===null)throw new Error("recovery not final; resume recovery");await r.change({recovery:s,state:"accepted"})})}async open(t={}){return this.withLease(async r=>{let n=r.record;if(!["accepted","file_ready"].includes(n.state)||!n.purchase)throw new Error("purchase is not accepted");let o=await this.storage.restorePurchase(n.purchase);JSON.stringify(o)!==JSON.stringify(n.purchase)&&(n=await r.change({purchase:o}));let i=t instanceof Uint8Array?{}:t;if(t instanceof Uint8Array&&t.length>Ra)throw new $e("too_large","File exceeds the 50 MB size limit.");let s=G(n.header,(n.header.length-2)/2);if(n.recovery?.grant===null)throw new Error("recovery grant is not final");let a=t instanceof Uint8Array?t:await xy({...i,url:n.resourceUrl,contractId:o.terms.contractId,fileId:n.fileId,header:s,checkedHeaderHash:o.checkedHeaderHash,listing:{fileId:n.fileId,cipherHash:o.terms.cipherHash,seller:o.terms.seller,publishedHeaderHash:Y(await Oe(s.subarray(0,-65)))},proof:{secret:G(n.recovery?.buyerSecret??o.buyerSecret,32),purchase_id:o.id,grant:n.recovery?.grant??0}});if(i.signal?.aborted)throw new $e("cancelled");vp(i.onProgress,{phase:"decrypting",received:a.length});let c=await this.options.sdk.open({file:a,record:o,...n.recovery?{recovery:n.recovery}:{}});if(i.signal?.aborted)throw new $e("cancelled");return await r.change({state:"file_ready"}),vp(i.onProgress,{phase:"ready",received:a.length}),c})}exportReceipt(t){return this.storage.exportReceipt(this.options.id,t)}};var hd="annon/browser/sale";function ky(e,t){if(typeof e!="string"||!new RegExp(`^(0|[1-9][0-9]*)(\\.[0-9]{1,${t}})?$`).test(e))throw new S("invalid_arguments");let[r,n=""]=e.split("."),o=BigInt(X(r))*10n**BigInt(t)+BigInt(n.padEnd(t,"0"));if(o<=0n||o>=2n**128n)throw new S("invalid_arguments");return o}function Z5(e){let t=BigInt(e),r=(t%10n**24n).toString().padStart(24,"0").replace(/0+$/,"");return`${t/10n**24n}${r?`.${r}`:""}`}var X5=async(e,t)=>{let r=await new Response(e).blob();return t(cc(r))};function Oa(e){let t=X(e.hosting),{expiresAt:r,...n}=t.intent;return JSON.stringify([n,e.terms,e.baseSplit,t.origin,t.metadata,t.manifest,t.listingStorage,e.storageBudget??null,t.fee,t.steps])}function Ca(e){return JSON.stringify([e.fileKey,e.sellerSecret])}function Y5(e){let t=X(e.hosting),r=e.terms,n=BigInt(r.near.price),o=r.near.recipients.map(c=>n*BigInt(c.bps)/10000n);o[r.near.remainder]=X(o[r.near.remainder])+n-o.reduce((c,d)=>c+d,0n);let i=r.near.recipients.findIndex(c=>Q(c.identity)===Q(r.seller)),s=o[i]??0n,a=r.near.recipients.map((c,d)=>d).sort((c,d)=>c===i?-1:d===i?1:c-d);return{seller:{kind:r.seller.kind,label:Ke(r.seller)},sellerIdentity:Ke(r.seller),filename:e.name,title:t.metadata.title,priceUsdc:ct(n),shares:a.map(c=>({label:c===i?"You":"Protocol fee",bps:X(r.near.recipients[c]).bps,amountUsdc:ct(X(o[c]))})),fee:t.fee?{fixedUsdc:ct(t.fee.fixed),bps:t.fee.bps,amountUsdc:ct(n-s)}:null,funding:r.seller.kind==="near"?{listingStorageNear:Z5(X(t.listingStorage)),purchaseStorageNear:Z5(X(e.storageBudget))}:null,routes:r.base?["near","base","1click"]:["near","1click"],baseSplit:r.base!==null,steps:["backup",...t.steps],contract:r.contract,host:t.origin}}async function s_(e={}){let t={...e,name:e.name??"annon-selling"},{rawStore:r,backupSecret:n,writeBackup:o}=await Iy(t);return{rawStore:r,backupSecret:n,writeBackup:o,indexStore:fc(t)}}function a_(e){let t=e.fileLifetimeDays;if(t!=null&&(!Number.isSafeInteger(t)||t<0))throw new S("invalid_arguments");let r=new $i(e),n=new Map,o=new Map,i=new Map,s=l=>{let p=n.get(l);return p||(p={},n.set(l,p)),p},a=async()=>{try{let l=await e.indexStore.load(hd);if(l&&(l.id!=="browser-sale"||!Number.isSafeInteger(l.revision)||l.revision<0||!/^0x[0-9a-f]{64}$/.test(l.fileId)||!(l.backup===null||typeof l.backup=="string")||Object.keys(l).some(p=>!["id","revision","fileId","backup"].includes(p))))throw new Error;return l}catch(l){throw new S("invalid_record",void 0,{cause:l})}},c=async l=>{let p=await a();if(!p||p.fileId!==l)throw new S("invalid_record");let m=await r.hosted.load(l);if(s(l).approved&&s(l).approved!==Oa(m))throw new S("invalid_record");if(!m.published&&s(l).approvedKeys&&s(l).approvedKeys!==Ca(m))throw new S("invalid_record");let h=s(l).secret;if(h){if(!p.backup)throw new S("backup_secret_required");let y;try{y=await K0(p.backup,h)}catch(b){throw new S("invalid_record",void 0,{cause:b})}if(Oa(m)!==Oa(y)||!m.published&&Ca(m)!==Ca(y))throw new S("invalid_record")}if((await r.hosted.load(l)).revision!==m.revision||(await a())?.revision!==p.revision)throw new S("store_conflict");return{saved:p,job:m}},d=async l=>{let{job:p}=await c(l),m=X(p.hosting),h=s(l),y=m.result,b={...Y5(p),id:l,revision:p.revision,done:[...m.backupConfirmed?["backup"]:[],...m.completed],next:y?null:m.backupConfirmed?m.steps[m.completed.length]??null:"backup",pending:m.pending!==null,needs:y?[]:[...h.connection?[]:["wallet"],...h.file?[]:["file"],...m.backupConfirmed&&!h.secret?["secret"]:[]],registered:m.completed.includes("register"),result:y?{fileId:y.fileId,url:y.url,expiresAt:y.expiresAt}:null};return structuredClone(b)},f=async l=>{let p=await d(l);for(let m of i.get(l)??[])try{m(structuredClone(p))}catch{}return p},u=l=>({id:l,view:()=>d(l),subscribe(p){let m=i.get(l)??new Set;return i.set(l,m),m.add(p),()=>{m.delete(p)}},async exportBackup(){let{job:p,saved:m}=await c(l);if(X(p.hosting).backupConfirmed||X(p.hosting).pending||X(p.hosting).lease)throw new S("invalid_arguments");let h=uc(),y=await gn(p,h);if((await r.hosted.load(l)).revision!==p.revision)throw new S("store_conflict");if(!await e.indexStore.compareAndSet(hd,m,{...m,revision:m.revision+1,backup:y}))throw new S("store_conflict");return s(l).secret=h,{filename:`annon-seller-${l.slice(2)}.json`,text:y,secret:Y(h).slice(2)}},async confirmBackup(){let{saved:p}=await c(l);if(!s(l).secret||!p.backup)throw new S("backup_secret_required");await r.hosted.confirmBackup(l),await f(l)},async attachWallet(p){let{job:m}=await c(l),h=e.wallet(p);if(p.kind!==m.terms.seller.kind||Q(ne(h.wallet.identity))!==Q(m.terms.seller))throw new S("wrong_identity");s(l).connection=p,await f(l)},async attachFile(p){await c(l),await r.hosted.verifySource(l,cc(p)),s(l).file=p,await f(l)},async unlock(p){try{if(!/^[0-9a-f]{64}$/.test(p))throw new Error;let{job:m,saved:h}=await c(l);if(!h.backup)throw new Error;let y=G(`0x${p}`,32),b=await K0(h.backup,y);if(Oa(m)!==Oa(b)||!m.published&&Ca(m)!==Ca(b)||(await r.hosted.load(l)).revision!==m.revision)throw new Error;s(l).secret=y}catch(m){throw new S("invalid_record",void 0,{cause:m})}await f(l)},async next(p={}){if(p.signal?.aborted)throw new S("cancelled");let{job:m,saved:h}=await c(l),y=s(l);if(!y.secret||!h.backup||!X(m.hosting).backupConfirmed)throw new S("backup_secret_required");if(X(m.hosting).result)return d(l);if(!y.connection)throw new S("signer_required");if(!y.file)throw new S("file_required");let{wallet:b,signUpload:x}=e.wallet(y.connection);if(Q(ne(b.identity))!==Q(m.terms.seller))throw new S("wrong_identity");let g=(v,E)=>{try{p.onProgress?.({phase:v,done:E,total:X(y.file).size})}catch{}};g("encrypting",0),await r.hosted.next(l,{expectedRevision:m.revision,...p.txHash?{txHash:p.txHash}:{},data:cc(y.file),seller:b,hosting:{origin:e.host,...x?{signUpload:x}:{},spool:X5,body:async v=>(g("encrypting",X(y.file).size),g("uploading",0),new Response(v.read()).blob())}}),g("uploading",y.file.size);let w=await f(l);return w.result&&delete y.approvedKeys,w},async discard(){let p=await a();if(!p||p.fileId!==l)throw new S("invalid_record");if(await e.rawStore.load(`annon/sell/${l}`))try{await c(l),await r.hosted.discard(l)}catch(m){if(!(m instanceof S)||m.code!=="invalid_record")throw m}if(!await e.indexStore.compareAndSet(hd,p,null))throw new S("store_conflict");s(l).secret?.fill(0),n.delete(l)}});return{kind:"sdk",live:!0,async active(){let l=await a();return l?u(l.fileId):null},async quote(l,p){let{wallet:m,signUpload:h}=e.wallet(l);if(l.kind!==m.identity.kind)throw new S("wrong_identity");let y={data:cc(p.file),name:p.file.name,mime:p.file.type||"application/octet-stream",seller:m,price:String(ky(p.priceUsdc,6)),title:p.title,description:p.description,hosting:{origin:e.host,...h?{signUpload:h}:{}},...m.identity.kind==="near"?{listingStorage:ky(p.listingStorageNear??"0.01",24),storageBudget:ky(p.storageBudgetNear??"0.05",24)}:{}},b=await r.hosted.quote(y),x=Y5({terms:b.terms,name:b.metadata.filename,storageBudget:b.storageBudget??void 0,hosting:{origin:e.host,metadata:b.metadata,fee:b.fee,steps:b.steps,listingStorage:b.listingStorage}});return o.set(b.quoteId,{quote:structuredClone(b),draft:{...p},connection:l,shown:x}),structuredClone({...x,quoteId:b.quoteId,description:b.metadata.description,byteSize:p.file.size,...e.fileLifetimeDays===void 0?{}:{hostedDays:e.fileLifetimeDays}})},async begin(l){let p=o.get(l);if(!p)throw new S("invalid_arguments");let m=await a();if(m&&!await e.rawStore.load(`annon/sell/${m.fileId}`)){if(!await e.indexStore.compareAndSet(hd,m,null))throw new S("store_conflict");m=null}if(m&&!(await r.hosted.load(m.fileId)).published)throw new S("sell_incomplete");let h={id:"browser-sale",revision:(m?.revision??-1)+1,fileId:p.quote.fileId,backup:null},y=await r.hosted.begin(l);if(!await e.indexStore.compareAndSet(hd,m,h))throw await r.hosted.discard(h.fileId),new S("sell_incomplete");return n.set(h.fileId,{approved:Oa(y),approvedKeys:Ca(y),file:p.draft.file,connection:p.connection}),o.delete(l),u(h.fileId)}}}var sn=class extends S{constructor(r,n,o){super(r,n,o);this.code=r;this.name="BrowserWalletError"}code};function Ee(e,t){throw new sn(e,t)}async function $n(e){try{return await e()}catch(t){if(t instanceof sn||t instanceof Vt)throw t;let r=t;for(let n=0;n<8&&r&&typeof r=="object";n++){let o=r;if(o.code===4001||o.code==="ACTION_REJECTED")throw new sn("rejected","The wallet request was rejected.",{cause:t});if(o.code===4901||o.code===4902)throw new sn("wrong_chain","Select Base in the wallet.",{cause:t});if(o.code===-32601||o.code===4200)throw new sn("missing_method","The wallet does not support this method.",{cause:t});r=o.cause}throw new sn("wallet_error","The wallet request failed.",{cause:t})}}function c_(e,t){let r=ne({kind:"evm",id:t}),n=a=>$n(async()=>{typeof e.request!="function"&&Ee("missing_method","EIP-1193 request is unavailable.");let c=await e.request(a);return a.method==="eth_accounts"&&(!Array.isArray(c)||!c.some(d=>typeof d=="string"&&d.toLowerCase()===r.id))&&Ee("wrong_identity","The wallet does not control the selected identity."),c}),o=z5({request:n},r.id),i=async()=>{let a=await n({method:"eth_chainId"});try{return typeof a!="string"||!/^0x[0-9a-f]+$/i.test(a)?!1:BigInt(a)===BigInt(mc)}catch{return!1}},s=async a=>{await i()||(a&&await n({method:"wallet_switchEthereumChain",params:[{chainId:"0x2105"}]}),(!a||!await i())&&Ee("wrong_chain","Select Base in the wallet.")),await n({method:"eth_accounts"})};return{identity:r,address:r.id,authorize:a=>$n(async()=>{await n({method:"eth_accounts"});let c;try{c=await o.authorize(a)}catch(d){throw d instanceof S&&d.code==="invalid_signature"&&Ee("invalid_signature","The wallet returned an invalid recovery signature."),d}return lt(r,a,c)||Ee("invalid_signature","The wallet returned an invalid recovery signature."),await n({method:"eth_accounts"}),c}),signTypedData:a=>$n(async()=>{a.domain.chainId!==mc&&Ee("wrong_chain","Payment authorization must name Base."),a.message.from.toLowerCase()!==r.id&&Ee("wrong_identity","Payment authorization names another identity."),await s(!0);let c=await o.signTypedData(a);return(typeof c!="string"||wf(gf(a.domain.verifyingContract,a.message),c)!==r.id)&&Ee("invalid_signature","The wallet returned an invalid payment signature."),await s(!1),c})}}function J5(e){try{return e?ne({kind:"solana",id:typeof e=="string"?e:Ct.encode(e instanceof Uint8Array?e:e.toBytes())}).id:Ee("wrong_identity","No Solana identity is selected.")}catch{return Ee("wrong_identity","The wallet returned another Solana identity.")}}function d_(e,t){let r=ne({kind:"solana",id:t}),n=()=>{J5(e.publicKey)!==r.id&&Ee("wrong_identity","Select the requested Solana identity.")};return{identity:r,authorize:o=>$n(async()=>{n();let i=e.signMessage?.bind(e);typeof i!="function"&&Ee("missing_method","Solana signMessage is unavailable.");let s=await i(new TextEncoder().encode(o)),a=s instanceof Uint8Array?s:s?.signature;!(s instanceof Uint8Array)&&s?.publicKey&&J5(s.publicKey)!==r.id&&Ee("wrong_identity","The signature names another Solana identity."),(!(a instanceof Uint8Array)||a.length!==64)&&Ee("invalid_signature","The wallet returned an invalid Solana signature.");let c={kind:"solana",sig:Y(a)};return lt(r,o,c)||Ee("invalid_signature","The wallet did not sign the exact recovery text."),n(),c})}}function f_(e,t){let r=ne({kind:"near",id:t}),n=async()=>{typeof e.getAccounts!="function"&&Ee("missing_method","NEAR getAccounts is unavailable.");let i=await e.getAccounts();return(!Array.isArray(i)||!i.some(s=>s?.accountId===r.id))&&Ee("wrong_identity","Select the requested NEAR identity."),i},o=$5({getAccounts:n,signAndSendTransaction:async i=>{typeof e.signAndSendTransaction!="function"&&Ee("missing_method","NEAR transaction signing is unavailable.");let s=await e.signAndSendTransaction({signerId:i.signerId,receiverId:i.receiverId,actions:i.actions.map(({params:a})=>({functionCall:{methodName:a.methodName,args:new TextEncoder().encode(JSON.stringify(a.args)),gas:BigInt(a.gas),deposit:BigInt(a.deposit)}}))});if(s&&typeof s=="object"&&"transaction"in s){let a=s.transaction;if(a?.signer_id!==r.id){if(a?.hash)throw new Vt(a.hash);Ee("wrong_identity","The transaction names another NEAR identity.")}}else Ee("invalid_response","The wallet returned no NEAR transaction.");return s}},r.id);return{identity:r,authorize:i=>$n(()=>o.authorize(i)),call:i=>$n(async()=>{let s=await o.call(i);try{await n()}catch{let a=s.transaction;throw new Vt(a.hash)}return s}),transferPurchase:(i,s)=>$n(()=>o.transferPurchase(i,s)),proveControl:(i,s)=>$n(async()=>{await n();let a=e.signMessage?.bind(e);typeof a!="function"&&Ee("missing_method","NEAR recovery requires NEP-413 signMessage.");try{await rf(r.id,i,s,async c=>{let d=await a(c);d||Ee("invalid_response","The wallet returned no NEP-413 signature."),d.accountId!==r.id&&Ee("wrong_identity","The signature names another NEAR identity.");try{(typeof d.publicKey!="string"||!d.publicKey.startsWith("ed25519:")||Ct.decode(d.publicKey.slice(8)).length!==32||typeof d.signature!="string"||wd.decode(d.signature).length!==64)&&Ee("invalid_signature","The wallet returned a malformed NEP-413 signature.")}catch{Ee("invalid_signature","The wallet returned a malformed NEP-413 signature.")}return d})}catch(c){throw c instanceof sn||c instanceof S&&c.code==="invalid_signature"&&Ee("invalid_signature","The wallet returned an invalid NEP-413 ownership proof."),c}await n()})}}async function u_(e,t,r){let n=sc(t);if(n.seller.kind!=="near")throw new S("wrong_identity");return $n(async()=>{let o=async()=>{(!e.getAccounts||!e.signMessage)&&Ee("missing_method","NEAR hosting requires NEP-413 signing."),(await e.getAccounts()).some(c=>c.accountId===n.seller.id)||Ee("wrong_identity","Select the requested NEAR identity.")};await o();let i={message:co(n),recipient:n.hostOrigin,nonce:G(n.nonce,32)},s=await X(e.signMessage,"invalid_response").call(e,{...i,nonce:i.nonce.slice()});return await oc(n.seller.id,i,s,r),await o(),{kind:"near",accountId:X(s,"invalid_response").accountId,publicKey:X(s,"invalid_response").publicKey,signature:X(s,"invalid_response").signature}})}export{$i as Annon,S as AnnonError,W6 as BASE_ELIGIBILITY_MAX_AGE_SECONDS,Ra as BROWSER_DOWNLOAD_LIMIT,vf as BaseRpcRateLimited,Ty as BrowserPurchaseController,sn as BrowserWalletError,af as CkdError,$e as DownloadError,zi as FileFundingRefused,df as HTTP_RETRY_MAX_WAIT_SECONDS,Dr as MAX_PAY2_BYTES,Lr as MAX_PLAINTEXT_BYTES,ts as NearError,rc as NearRpcRateLimited,Fn as OneClick,od as OneClickQuoteExpired,Ll as OneClickRefused,Re as Pay2Error,re as PayError,Ep as PurchaseLeaseBusy,Do as SellError,br as SourceChangedError,Vt as TransactionUncertain,ic as UploadClient,n_ as browserAnnon,xy as browserDownload,c_ as browserEvmWallet,f_ as browserNearWallet,Iy as browserPurchaseStorage,X5 as browserSellerSpool,s_ as browserSellerStorage,d_ as browserSolanaWallet,wp as canonicalManifestUrl,e_ as catalog,Kh as checkBaseSponsorship,a_ as createBrowserSeller,W0 as exportSellerKey,im as fileFundingText,RS as importSellerKey,Ua as isTransient,J4 as listShops,uc as newBackupSecret,m4 as originFromToken,u_ as signNearUpload,Ko as toPublicError,co as uploadText,Gh as validBaseSponsorship,qh as validateRefundAddress};
58
58
  /*! Bundled license information:
59
59
 
60
60
  @noble/hashes/esm/utils.js: