@wormhole-foundation/wormhole-connect 0.3.19-beta.3-development → 0.3.19-beta.5-development
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{ccip-B8sh0red.js → ccip-De5bB7ry.js} +1 -1
- package/dist/assets/{evm-B3YdeaCI.js → evm-DJTN7n-6.js} +4 -4
- package/dist/assets/{index-moDeJTxm.js → index-CdA027fm.js} +1 -1
- package/dist/assets/{index-1ZJmfQkw.js → index-D8xdfMo8.js} +2 -2
- package/dist/assets/{index.es-CXmj0UJy.js → index.es-DsPAzXeV.js} +2 -2
- package/dist/main.js +7 -7
- package/dist/src/components/ManualAddressInput.d.ts.map +1 -1
- package/dist/src/routes/cosmosGateway/cosmosGateway.d.ts +2 -0
- package/dist/src/routes/cosmosGateway/cosmosGateway.d.ts.map +1 -1
- package/dist/src/routes/porticoBridge/porticoBridge.d.ts +2 -0
- package/dist/src/routes/porticoBridge/porticoBridge.d.ts.map +1 -1
- package/dist/src/routes/sdkv2/route.d.ts +1 -1
- package/dist/src/routes/sdkv2/route.d.ts.map +1 -1
- package/dist/src/routes/tbtc/tbtc.d.ts +2 -0
- package/dist/src/routes/tbtc/tbtc.d.ts.map +1 -1
- package/lib/{algorand-BDR3KPTJ.js → algorand-BizCMnCe.js} +1 -1
- package/lib/{algorand-CNPRWbNB.mjs → algorand-CZC9cPKi.mjs} +4 -4
- package/lib/{aptos-BPs26BCC.mjs → aptos-B4ng1XsR.mjs} +1 -1
- package/lib/{aptos-t3uXFwih.mjs → aptos-CRkEBLid.mjs} +4 -4
- package/lib/{aptos-tCZHrDAP.js → aptos-CXyHqFt8.js} +2 -2
- package/lib/{aptos-Br9Q1n2N.js → aptos-i8WEm-Fe.js} +1 -1
- package/lib/{browser-33Nc32cs.mjs → browser-CIwNo6kY.mjs} +2 -2
- package/lib/{browser-Cz60hQ-L.js → browser-DEzmpMBm.js} +1 -1
- package/lib/{ccip-CtmuOQGX.js → ccip-6omn1tDF.js} +1 -1
- package/lib/{ccip-CE49B2YD.mjs → ccip-LzzuUWf7.mjs} +1 -1
- package/lib/{chain-BT07YJHt.js → chain-BteoJHpg.js} +1 -1
- package/lib/{chain-CbwtJlkc.mjs → chain-Cc-vL0Ji.mjs} +1 -1
- package/lib/{cosmos-LlwNYP69.mjs → cosmos-5NiZ8EbB.mjs} +3 -3
- package/lib/{cosmos-t65H2NQC.js → cosmos-DM4Lrmu1.js} +1 -1
- package/lib/{cosmwasm-CiJ3I3AY.js → cosmwasm-8FJsT7LT.js} +2 -2
- package/lib/{cosmwasm-CbTKetWD.mjs → cosmwasm-BHEBPmf7.mjs} +6 -6
- package/lib/{create-Chqnlpoq.js → create-48Wkagqs.js} +1 -1
- package/lib/{create-HNw0Emrd.mjs → create-BIAJIVSg.mjs} +1 -1
- package/lib/{ens-validation.es6-BaZUabxu.js → ens-validation.es6-Bw--s4Qc.js} +1 -1
- package/lib/{ens-validation.es6-CyEOHc9J.mjs → ens-validation.es6-DQFhqeC0.mjs} +2 -2
- package/lib/{evm-lHNM4jqm.mjs → evm-B5hnoH2O.mjs} +6 -6
- package/lib/{evm-CjvzIUCn.mjs → evm-Dd33ef5o.mjs} +6 -6
- package/lib/{evm-CNC7JHe1.js → evm-JNEgzI8_.js} +4 -4
- package/lib/{evm-3AGyBI-h.js → evm-OwiMOsDg.js} +2 -2
- package/lib/{index-BWsL77BI.mjs → index-10BWvX1N.mjs} +3 -3
- package/lib/{index-DPNt5r2L.js → index-670AMJe5.js} +1 -1
- package/lib/{index-C4kvGnSA.mjs → index-B03MiI2p.mjs} +2 -2
- package/lib/{index-BpuXk_6h.js → index-B9pFbfyU.js} +1 -1
- package/lib/{index-35qsyZLz.js → index-BDi5PNJc.js} +1 -1
- package/lib/{index-BCSt_UXY.js → index-BFIX3imu.js} +1 -1
- package/lib/{index-CACyup9A.js → index-BHUxBugG.js} +1 -1
- package/lib/{index-DVVJw5ml.js → index-BHWhOqWI.js} +1 -1
- package/lib/{index-ztQgUCWf.js → index-BJPmRnHn.js} +1 -1
- package/lib/{index-BCnyHegg.mjs → index-Bg59b-Bk.mjs} +4 -4
- package/lib/{index-CbCfazgA.mjs → index-By8Yxkcx.mjs} +5 -5
- package/lib/{index-Tl7zYqHL.js → index-C1oy9Lkm.js} +6 -6
- package/lib/{index-DJzhcNDU.mjs → index-CHqEmT8z.mjs} +6 -6
- package/lib/{index-Bk7wdRtH.mjs → index-CMKVJZ8E.mjs} +3 -3
- package/lib/{index-DRTx-Ru8.mjs → index-CNbmckF9.mjs} +4 -4
- package/lib/{index-D1dHZqit.mjs → index-CU3qSQjR.mjs} +4 -4
- package/lib/{index-CjyrCdi_.mjs → index-CVjCpWVm.mjs} +1 -1
- package/lib/{index-BBtf8VGl.js → index-CYRY8C8f.js} +1 -1
- package/lib/{index-DfJLd65b.mjs → index-Cx7DnGQ7.mjs} +4 -4
- package/lib/{index-CdSy2Lfd.mjs → index-D4oa5qLu.mjs} +85 -62
- package/lib/{index-zKUpU-3R.mjs → index-D7DR5q91.mjs} +4 -4
- package/lib/{index-BH5gBrJu.mjs → index-D83yFXT3.mjs} +3 -3
- package/lib/{index-B6m0ovID.mjs → index-D8SeaoGs.mjs} +2 -2
- package/lib/{index-DGRaAUXo.mjs → index-D8l7OdtE.mjs} +2 -2
- package/lib/{index-Dbwiqljw.js → index-DETB2K9l.js} +1 -1
- package/lib/{index-abvwfKBf.js → index-DGfMxIjQ.js} +1 -1
- package/lib/{index-l_e-RUun.js → index-DLpTO2U3.js} +1 -1
- package/lib/{index-CokIAiMa.mjs → index-DX18kVfL.mjs} +4 -4
- package/lib/{index-dJMYtBle.mjs → index-DX6w1JtB.mjs} +4 -4
- package/lib/{index-B9L2kltl.mjs → index-DbMbSuyg.mjs} +4 -4
- package/lib/{index-DCPwTd_i.js → index-DfYaeaDv.js} +1 -1
- package/lib/{index-0t31FGKV.js → index-DjmghqSr.js} +1 -1
- package/lib/{index-UOSBfEgg.js → index-DlRC-hs-.js} +1 -1
- package/lib/{index-Cp5np38p.mjs → index-G7Dlm7ed.mjs} +1 -1
- package/lib/{index-Bp0NhDcb.js → index-Hyeca4Ym.js} +1 -1
- package/lib/{index-DVH-ZIP6.mjs → index-ROBBwabT.mjs} +4 -4
- package/lib/{index-CO9tmWap.js → index-WhcobQtR.js} +1 -1
- package/lib/{index-DrncQYMG.js → index-X-BikqCf.js} +1 -1
- package/lib/{index-BqGvvv6N.js → index-ZCZHbA1F.js} +1 -1
- package/lib/{index-Cofatf_w.js → index-isN8Fo1n.js} +1 -1
- package/lib/{index-B9gw1I6s.js → index-j8isX5f9.js} +1 -1
- package/lib/{index-CGLAoOXl.mjs → index-jlt17KkN.mjs} +4 -4
- package/lib/{index-BS1tjK_Z.mjs → index-mtuCwj6Z.mjs} +5 -5
- package/lib/{index-Bfw-brA6.js → index-oVIYJXdI.js} +1 -1
- package/lib/{index-CYap2RXm.js → index-tvG-rfJZ.js} +1 -1
- package/lib/{index-DvUq-nIQ.mjs → index-ybRLAtD8.mjs} +5 -5
- package/lib/{index.es-494n2GDU.js → index.es-B33YjOZu.js} +2 -2
- package/lib/{index.es-DnXnnX-i.mjs → index.es-BON8c55F.mjs} +4 -4
- package/lib/index.js +1 -1
- package/lib/index.mjs +1 -1
- package/lib/{libsodium-wrappers-9p7NdjLu.mjs → libsodium-wrappers-DTuXKVrZ.mjs} +1 -1
- package/lib/{libsodium-wrappers-Dechaffz.js → libsodium-wrappers-VihnPAqR.js} +1 -1
- package/lib/{sei-SWKTnPTF.mjs → sei-C6N03jzv.mjs} +2 -2
- package/lib/{sei-DORxBQd-.js → sei-DTeCXpXl.js} +1 -1
- package/lib/{solana-Bd9eRY8E.js → solana--YauUjmQ.js} +2 -2
- package/lib/{solana-T2pgCVfU.mjs → solana-BMm013WW.mjs} +6 -6
- package/lib/{solana-DvbMa7B_.mjs → solana-DdaraOHp.mjs} +3 -3
- package/lib/{solana-KhBV5LOd.js → solana-T3yS-Q_9.js} +1 -1
- package/lib/{solanaEmbed.esm-CnKFJhsj.js → solanaEmbed.esm-DMwXbxXO.js} +1 -1
- package/lib/{solanaEmbed.esm-8eZSo5K2.mjs → solanaEmbed.esm-D_lKLzGu.mjs} +2 -2
- package/lib/src/components/ManualAddressInput.d.ts.map +1 -1
- package/lib/src/routes/cosmosGateway/cosmosGateway.d.ts +2 -0
- package/lib/src/routes/cosmosGateway/cosmosGateway.d.ts.map +1 -1
- package/lib/src/routes/porticoBridge/porticoBridge.d.ts +2 -0
- package/lib/src/routes/porticoBridge/porticoBridge.d.ts.map +1 -1
- package/lib/src/routes/sdkv2/route.d.ts +1 -1
- package/lib/src/routes/sdkv2/route.d.ts.map +1 -1
- package/lib/src/routes/tbtc/tbtc.d.ts +2 -0
- package/lib/src/routes/tbtc/tbtc.d.ts.map +1 -1
- package/lib/{sui-DDu4a1uc.mjs → sui-Btvc4SGv.mjs} +4 -4
- package/lib/{sui-CjRGl9Gg.mjs → sui-CXyWZ2Gp.mjs} +1 -1
- package/lib/{sui-B382sZz0.js → sui-DWLiZoeB.js} +1 -1
- package/lib/{sui-DwH1wYGH.js → sui-DbQOBpeH.js} +2 -2
- package/lib/{unsignedTransaction-BbAfXtog.mjs → unsignedTransaction-CtPR6znR.mjs} +2 -2
- package/lib/{unsignedTransaction-mu6HJcHt.js → unsignedTransaction-DZq5iThY.js} +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Bs=Object.defineProperty;var Ts=(i,e,t)=>e in i?Bs(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var W=(i,e,t)=>(Ts(i,typeof e!="symbol"?e+"":e,t),t);const a=require("./index-Tl7zYqHL.js"),vs=require("./index-DnneI5--.js"),se=require("./solana-Bd9eRY8E.js"),Ls=require("./create-Chqnlpoq.js"),Cs=require("./chain-BT07YJHt.js");function ge(i,e){return se.PublicKey.findProgramAddressSync(i,new se.PublicKey(e))[0]}function xs(i,e){return{pubkey:new se.PublicKey(i),isWritable:!0,isSigner:e}}function Ks(i,e){return{pubkey:new se.PublicKey(i),isWritable:!1,isSigner:e}}function Me(i){if(i===null)throw Error("account info is null");return i.data}class at{}W(at,"programId",new se.PublicKey("BPFLoaderUpgradeab1e11111111111111111111111"));function Rn(i){return ge([new se.PublicKey(i).toBuffer()],at.programId)}class zs extends Error{constructor(e){super(e),this.name="IdlError"}}function Kt(i,e){switch(e.type.kind){case"struct":return e.type.fields.map(t=>Pe(i,t.type)).reduce((t,n)=>t+n,0);case"enum":{const t=e.type.variants.map(n=>n.fields?n.fields.map(s=>typeof s=="object"&&"name"in s?Pe(i,s.type):Pe(i,s)).reduce((s,r)=>s+r,0):0);return Math.max(...t)+1}case"alias":return Pe(i,e.type.value)}}function Pe(i,e){var t;switch(e){case"bool":return 1;case"u8":return 1;case"i8":return 1;case"i16":return 2;case"u16":return 2;case"u32":return 4;case"i32":return 4;case"f32":return 4;case"u64":return 8;case"i64":return 8;case"f64":return 8;case"u128":return 16;case"i128":return 16;case"u256":return 32;case"i256":return 32;case"bytes":return 1;case"string":return 1;case"publicKey":return 32;default:if("vec"in e)return 1;if("option"in e)return 1+Pe(i,e.option);if("coption"in e)return 4+Pe(i,e.coption);if("defined"in e){const n=((t=i.types)==null?void 0:t.filter(r=>r.name===e.defined))??[];if(n.length!==1)throw new zs(`Type not found: ${JSON.stringify(e)}`);let s=n[0];return Kt(i,s)}if("array"in e){let n=e.array[0],s=e.array[1];return Pe(i,n)*s}throw new Error(`Invalid type ${JSON.stringify(e)}`)}}function Ve(i){return i.replace(/(?:^\w|[A-Z]|\b\w)/g,function(e,t){return t===0?e.toLowerCase():e.toUpperCase()}).replace(/[\s\-_]+/g,"")}function Ns(i){return i.charAt(0).toUpperCase()+i.slice(1)}class Ws extends TypeError{constructor(e,t){let n;const{message:s,...r}=e,{path:o}=e,c=o.length===0?s:"At path: "+o.join(".")+" -- "+s;super(c),Object.assign(this,r),this.name=this.constructor.name,this.failures=()=>{var u;return(u=n)!=null?u:n=[e,...t()]}}}function Os(i){return Se(i)&&typeof i[Symbol.iterator]=="function"}function Se(i){return typeof i=="object"&&i!=null}function oe(i){return typeof i=="string"?JSON.stringify(i):""+i}function Ms(i){const{done:e,value:t}=i.next();return e?void 0:t}function Us(i,e,t,n){if(i===!0)return;i===!1?i={}:typeof i=="string"&&(i={message:i});const{path:s,branch:r}=e,{type:o}=t,{refinement:c,message:u="Expected a value of type `"+o+"`"+(c?" with refinement `"+c+"`":"")+", but received: `"+oe(n)+"`"}=i;return{value:n,type:o,refinement:c,key:s[s.length-1],path:s,branch:r,...i,message:u}}function*an(i,e,t,n){Os(i)||(i=[i]);for(const s of i){const r=Us(s,e,t,n);r&&(yield r)}}function*zt(i,e,t={}){const{path:n=[],branch:s=[i],coerce:r=!1,mask:o=!1}=t,c={path:n,branch:s};if(r&&(i=e.coercer(i,c),o&&e.type!=="type"&&Se(e.schema)&&Se(i)&&!Array.isArray(i)))for(const d in i)e.schema[d]===void 0&&delete i[d];let u=!0;for(const d of e.validator(i,c))u=!1,yield[d,void 0];for(let[d,h,g]of e.entries(i,c)){const S=zt(h,g,{path:d===void 0?n:[...n,d],branch:d===void 0?s:[...s,h],coerce:r,mask:o});for(const f of S)f[0]?(u=!1,yield[f[0],void 0]):r&&(h=f[1],d===void 0?i=h:i instanceof Map?i.set(d,h):i instanceof Set?i.add(h):Se(i)&&(i[d]=h))}if(u)for(const d of e.refiner(i,c))u=!1,yield[d,void 0];u&&(yield[void 0,i])}let ye=class{constructor(e){const{type:t,schema:n,validator:s,refiner:r,coercer:o=u=>u,entries:c=function*(){}}=e;this.type=t,this.schema=n,this.entries=c,this.coercer=o,s?this.validator=(u,d)=>{const h=s(u,d);return an(h,d,this,u)}:this.validator=()=>[],r?this.refiner=(u,d)=>{const h=r(u,d);return an(h,d,this,u)}:this.refiner=()=>[]}assert(e){return En(e,this)}create(e){return w(e,this)}is(e){return Bn(e,this)}mask(e){return qs(e,this)}validate(e,t={}){return Xe(e,this,t)}};function En(i,e){const t=Xe(i,e);if(t[0])throw t[0]}function w(i,e){const t=Xe(i,e,{coerce:!0});if(t[0])throw t[0];return t[1]}function qs(i,e){const t=Xe(i,e,{coerce:!0,mask:!0});if(t[0])throw t[0];return t[1]}function Bn(i,e){return!Xe(i,e)[0]}function Xe(i,e,t={}){const n=zt(i,e,t),s=Ms(n);return s[0]?[new Ws(s[0],function*(){for(const o of n)o[0]&&(yield o[0])}),void 0]:[void 0,s[1]]}function Le(i,e){return new ye({type:i,schema:null,validator:e})}function Ds(){return Le("any",()=>!0)}function A(i){return new ye({type:"array",schema:i,*entries(e){if(i&&Array.isArray(e))for(const[t,n]of e.entries())yield[t,n,i]},coercer(e){return Array.isArray(e)?e.slice():e},validator(e){return Array.isArray(e)||"Expected an array value, but received: "+oe(e)}})}function fe(){return Le("boolean",i=>typeof i=="boolean")}function Nt(i){return Le("instance",e=>e instanceof i||"Expected a `"+i.name+"` instance, but received: "+oe(e))}function H(i){const e=oe(i),t=typeof i;return new ye({type:"literal",schema:t==="string"||t==="number"||t==="boolean"?i:null,validator(n){return n===i||"Expected the literal `"+e+"`, but received: "+oe(n)}})}function Fs(){return Le("never",()=>!1)}function I(i){return new ye({...i,validator:(e,t)=>e===null||i.validator(e,t),refiner:(e,t)=>e===null||i.refiner(e,t)})}function l(){return Le("number",i=>typeof i=="number"&&!isNaN(i)||"Expected a number, but received: "+oe(i))}function B(i){return new ye({...i,validator:(e,t)=>e===void 0||i.validator(e,t),refiner:(e,t)=>e===void 0||i.refiner(e,t)})}function Tn(i,e){return new ye({type:"record",schema:null,*entries(t){if(Se(t))for(const n in t){const s=t[n];yield[n,n,i],yield[n,s,e]}},validator(t){return Se(t)||"Expected an object, but received: "+oe(t)}})}function k(){return Le("string",i=>typeof i=="string"||"Expected a string, but received: "+oe(i))}function Wt(i){const e=Fs();return new ye({type:"tuple",schema:null,*entries(t){if(Array.isArray(t)){const n=Math.max(i.length,t.length);for(let s=0;s<n;s++)yield[s,t[s],i[s]||e]}},validator(t){return Array.isArray(t)||"Expected an array, but received: "+oe(t)}})}function p(i){const e=Object.keys(i);return new ye({type:"type",schema:i,*entries(t){if(Se(t))for(const n of e)yield[n,t[n],i[n]]},validator(t){return Se(t)||"Expected an object, but received: "+oe(t)}})}function ee(i){const e=i.map(t=>t.type).join(" | ");return new ye({type:"union",schema:null,validator(t,n){const s=[];for(const r of i){const[...o]=zt(t,r,n),[c]=o;if(c[0])for(const[u]of o)u&&s.push(u);else return[]}return["Expected the value to satisfy a union of `"+e+"`, but received: "+oe(t),...s]}})}function Ze(){return Le("unknown",()=>!0)}function Qe(i,e,t){return new ye({...i,coercer:(n,s)=>Bn(n,e)?i.coercer(t(n,s),s):i.coercer(n,s)})}const Vs=a.ed25519.utils.randomPrivateKey,cn=()=>{const i=a.ed25519.utils.randomPrivateKey(),e=rt(i),t=new Uint8Array(64);return t.set(i),t.set(e,32),{publicKey:e,secretKey:t}},rt=a.ed25519.getPublicKey;function un(i){try{return a.ed25519.ExtendedPoint.fromHex(i),!0}catch{return!1}}const Ot=(i,e)=>a.ed25519.sign(i,e.slice(0,32)),$s=a.ed25519.verify,x=i=>a.bufferPolyfill.Buffer.isBuffer(i)?i:i instanceof Uint8Array?a.bufferPolyfill.Buffer.from(i.buffer,i.byteOffset,i.byteLength):a.bufferPolyfill.Buffer.from(i);class Mt{constructor(e){Object.assign(this,e)}encode(){return a.bufferPolyfill.Buffer.from(a.serialize_1(He,this))}static decode(e){return a.deserialize_1(He,this,e)}static decodeUnchecked(e){return a.deserializeUnchecked_1(He,this,e)}}class Hs extends Mt{constructor(e){if(super(e),this.enum="",Object.keys(e).length!==1)throw new Error("Enum can only take single value");Object.keys(e).map(t=>{this.enum=t})}}const He=new Map;var vn;let Ln;const Cn=32,he=32;function Gs(i){return i._bn!==void 0}let ln=1;Ln=Symbol.toStringTag;class y extends Mt{constructor(e){if(super({}),this._bn=void 0,Gs(e))this._bn=e._bn;else{if(typeof e=="string"){const t=a.bs58.decode(e);if(t.length!=he)throw new Error("Invalid public key input");this._bn=new a.BN(t)}else this._bn=new a.BN(e);if(this._bn.byteLength()>he)throw new Error("Invalid public key input")}}static unique(){const e=new y(ln);return ln+=1,new y(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return a.bs58.encode(this.toBytes())}toJSON(){return this.toBase58()}toBytes(){const e=this.toBuffer();return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}toBuffer(){const e=this._bn.toArrayLike(a.bufferPolyfill.Buffer);if(e.length===he)return e;const t=a.bufferPolyfill.Buffer.alloc(32);return e.copy(t,32-e.length),t}get[Ln](){return`PublicKey(${this.toString()})`}toString(){return this.toBase58()}static async createWithSeed(e,t,n){const s=a.bufferPolyfill.Buffer.concat([e.toBuffer(),a.bufferPolyfill.Buffer.from(t),n.toBuffer()]),r=a.sha256(s);return new y(r)}static createProgramAddressSync(e,t){let n=a.bufferPolyfill.Buffer.alloc(0);e.forEach(function(r){if(r.length>Cn)throw new TypeError("Max seed length exceeded");n=a.bufferPolyfill.Buffer.concat([n,x(r)])}),n=a.bufferPolyfill.Buffer.concat([n,t.toBuffer(),a.bufferPolyfill.Buffer.from("ProgramDerivedAddress")]);const s=a.sha256(n);if(un(s))throw new Error("Invalid seeds, address must fall off the curve");return new y(s)}static async createProgramAddress(e,t){return this.createProgramAddressSync(e,t)}static findProgramAddressSync(e,t){let n=255,s;for(;n!=0;){try{const r=e.concat(a.bufferPolyfill.Buffer.from([n]));s=this.createProgramAddressSync(r,t)}catch(r){if(r instanceof TypeError)throw r;n--;continue}return[s,n]}throw new Error("Unable to find a viable program address nonce")}static async findProgramAddress(e,t){return this.findProgramAddressSync(e,t)}static isOnCurve(e){const t=new y(e);return un(t.toBytes())}}vn=y;y.default=new vn("11111111111111111111111111111111");He.set(y,{kind:"struct",fields:[["_bn","u256"]]});class js{constructor(e){if(this._publicKey=void 0,this._secretKey=void 0,e){const t=x(e);if(e.length!==64)throw new Error("bad secret key size");this._publicKey=t.slice(32,64),this._secretKey=t.slice(0,32)}else this._secretKey=x(Vs()),this._publicKey=x(rt(this._secretKey))}get publicKey(){return new y(this._publicKey)}get secretKey(){return a.bufferPolyfill.Buffer.concat([this._secretKey,this._publicKey],64)}}const Ys=new y("BPFLoader1111111111111111111111111111111111"),we=1232,ct=127,je=64;class Ut extends Error{constructor(e){super(`Signature ${e} has expired: block height exceeded.`),this.signature=void 0,this.signature=e}}Object.defineProperty(Ut.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class qt extends Error{constructor(e,t){super(`Transaction was not confirmed in ${t.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${e} using the Solana Explorer or CLI tools.`),this.signature=void 0,this.signature=e}}Object.defineProperty(qt.prototype,"name",{value:"TransactionExpiredTimeoutError"});class ze extends Error{constructor(e){super(`Signature ${e} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=e}}Object.defineProperty(ze.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class Ye{constructor(e,t){this.staticAccountKeys=void 0,this.accountKeysFromLookups=void 0,this.staticAccountKeys=e,this.accountKeysFromLookups=t}keySegments(){const e=[this.staticAccountKeys];return this.accountKeysFromLookups&&(e.push(this.accountKeysFromLookups.writable),e.push(this.accountKeysFromLookups.readonly)),e}get(e){for(const t of this.keySegments()){if(e<t.length)return t[e];e-=t.length}}get length(){return this.keySegments().flat().length}compileInstructions(e){if(this.length>256)throw new Error("Account index overflow encountered during compilation");const n=new Map;this.keySegments().flat().forEach((r,o)=>{n.set(r.toBase58(),o)});const s=r=>{const o=n.get(r.toBase58());if(o===void 0)throw new Error("Encountered an unknown instruction account key during compilation");return o};return e.map(r=>({programIdIndex:s(r.programId),accountKeyIndexes:r.keys.map(o=>s(o.pubkey)),data:r.data}))}}const K=(i="publicKey")=>a.blob(32,i),Js=(i="signature")=>a.blob(64,i),Re=(i="string")=>{const e=a.struct([a.u32("length"),a.u32("lengthPadding"),a.blob(a.offset(a.u32(),-8),"chars")],i),t=e.decode.bind(e),n=e.encode.bind(e),s=e;return s.decode=(r,o)=>t(r,o).chars.toString(),s.encode=(r,o,c)=>{const u={chars:a.bufferPolyfill.Buffer.from(r,"utf8")};return n(u,o,c)},s.alloc=r=>a.u32().span+a.u32().span+a.bufferPolyfill.Buffer.from(r,"utf8").length,s},Xs=(i="authorized")=>a.struct([K("staker"),K("withdrawer")],i),Zs=(i="lockup")=>a.struct([a.ns64("unixTimestamp"),a.ns64("epoch"),K("custodian")],i),Qs=(i="voteInit")=>a.struct([K("nodePubkey"),K("authorizedVoter"),K("authorizedWithdrawer"),a.u8("commission")],i),er=(i="voteAuthorizeWithSeedArgs")=>a.struct([a.u32("voteAuthorizationType"),K("currentAuthorityDerivedKeyOwnerPubkey"),Re("currentAuthorityDerivedKeySeed"),K("newAuthorized")],i);function xn(i,e){const t=s=>{if(s.span>=0)return s.span;if(typeof s.alloc=="function")return s.alloc(e[s.property]);if("count"in s&&"elementLayout"in s){const r=e[s.property];if(Array.isArray(r))return r.length*t(s.elementLayout)}else if("fields"in s)return xn({layout:s},e[s.property]);return 0};let n=0;return i.layout.fields.forEach(s=>{n+=t(s)}),n}function X(i){let e=0,t=0;for(;;){let n=i.shift();if(e|=(n&127)<<t*7,t+=1,!(n&128))break}return e}function ne(i,e){let t=e;for(;;){let n=t&127;if(t>>=7,t==0){i.push(n);break}else n|=128,i.push(n)}}function O(i,e){if(!i)throw new Error(e||"Assertion failed")}class ut{constructor(e,t){this.payer=void 0,this.keyMetaMap=void 0,this.payer=e,this.keyMetaMap=t}static compile(e,t){const n=new Map,s=o=>{const c=o.toBase58();let u=n.get(c);return u===void 0&&(u={isSigner:!1,isWritable:!1,isInvoked:!1},n.set(c,u)),u},r=s(t);r.isSigner=!0,r.isWritable=!0;for(const o of e){s(o.programId).isInvoked=!0;for(const c of o.keys){const u=s(c.pubkey);u.isSigner||(u.isSigner=c.isSigner),u.isWritable||(u.isWritable=c.isWritable)}}return new ut(t,n)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];O(e.length<=256,"Max static account keys length exceeded");const t=e.filter(([,u])=>u.isSigner&&u.isWritable),n=e.filter(([,u])=>u.isSigner&&!u.isWritable),s=e.filter(([,u])=>!u.isSigner&&u.isWritable),r=e.filter(([,u])=>!u.isSigner&&!u.isWritable),o={numRequiredSignatures:t.length+n.length,numReadonlySignedAccounts:n.length,numReadonlyUnsignedAccounts:r.length};{O(t.length>0,"Expected at least one writable signer key");const[u]=t[0];O(u===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}const c=[...t.map(([u])=>new y(u)),...n.map(([u])=>new y(u)),...s.map(([u])=>new y(u)),...r.map(([u])=>new y(u))];return[o,c]}extractTableLookup(e){const[t,n]=this.drainKeysFoundInLookupTable(e.state.addresses,o=>!o.isSigner&&!o.isInvoked&&o.isWritable),[s,r]=this.drainKeysFoundInLookupTable(e.state.addresses,o=>!o.isSigner&&!o.isInvoked&&!o.isWritable);if(!(t.length===0&&s.length===0))return[{accountKey:e.key,writableIndexes:t,readonlyIndexes:s},{writable:n,readonly:r}]}drainKeysFoundInLookupTable(e,t){const n=new Array,s=new Array;for(const[r,o]of this.keyMetaMap.entries())if(t(o)){const c=new y(r),u=e.findIndex(d=>d.equals(c));u>=0&&(O(u<256,"Max lookup table index exceeded"),n.push(u),s.push(c),this.keyMetaMap.delete(r))}return[n,s]}}const Kn="Reached end of buffer unexpectedly";function ue(i){if(i.length===0)throw new Error(Kn);return i.shift()}function Z(i,...e){const[t]=e;if(e.length===2?t+(e[1]??0)>i.length:t>=i.length)throw new Error(Kn);return i.splice(...e)}class ae{constructor(e){this.header=void 0,this.accountKeys=void 0,this.recentBlockhash=void 0,this.instructions=void 0,this.indexToProgramIds=new Map,this.header=e.header,this.accountKeys=e.accountKeys.map(t=>new y(t)),this.recentBlockhash=e.recentBlockhash,this.instructions=e.instructions,this.instructions.forEach(t=>this.indexToProgramIds.set(t.programIdIndex,this.accountKeys[t.programIdIndex]))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:a.bs58.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new Ye(this.staticAccountKeys)}static compile(e){const t=ut.compile(e.instructions,e.payerKey),[n,s]=t.getMessageComponents(),o=new Ye(s).compileInstructions(e.instructions).map(c=>({programIdIndex:c.programIdIndex,accounts:c.accountKeyIndexes,data:a.bs58.encode(c.data)}));return new ae({header:n,accountKeys:s,recentBlockhash:e.recentBlockhash,instructions:o})}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures;if(e>=this.header.numRequiredSignatures){const n=e-t,r=this.accountKeys.length-t-this.header.numReadonlyUnsignedAccounts;return n<r}else{const n=t-this.header.numReadonlySignedAccounts;return e<n}}isProgramId(e){return this.indexToProgramIds.has(e)}programIds(){return[...this.indexToProgramIds.values()]}nonProgramIds(){return this.accountKeys.filter((e,t)=>!this.isProgramId(t))}serialize(){const e=this.accountKeys.length;let t=[];ne(t,e);const n=this.instructions.map(g=>{const{accounts:S,programIdIndex:f}=g,b=Array.from(a.bs58.decode(g.data));let m=[];ne(m,S.length);let P=[];return ne(P,b.length),{programIdIndex:f,keyIndicesCount:a.bufferPolyfill.Buffer.from(m),keyIndices:S,dataLength:a.bufferPolyfill.Buffer.from(P),data:b}});let s=[];ne(s,n.length);let r=a.bufferPolyfill.Buffer.alloc(we);a.bufferPolyfill.Buffer.from(s).copy(r);let o=s.length;n.forEach(g=>{const f=a.struct([a.u8("programIdIndex"),a.blob(g.keyIndicesCount.length,"keyIndicesCount"),a.seq(a.u8("keyIndex"),g.keyIndices.length,"keyIndices"),a.blob(g.dataLength.length,"dataLength"),a.seq(a.u8("userdatum"),g.data.length,"data")]).encode(g,r,o);o+=f}),r=r.slice(0,o);const c=a.struct([a.blob(1,"numRequiredSignatures"),a.blob(1,"numReadonlySignedAccounts"),a.blob(1,"numReadonlyUnsignedAccounts"),a.blob(t.length,"keyCount"),a.seq(K("key"),e,"keys"),K("recentBlockhash")]),u={numRequiredSignatures:a.bufferPolyfill.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:a.bufferPolyfill.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:a.bufferPolyfill.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:a.bufferPolyfill.Buffer.from(t),keys:this.accountKeys.map(g=>x(g.toBytes())),recentBlockhash:a.bs58.decode(this.recentBlockhash)};let d=a.bufferPolyfill.Buffer.alloc(2048);const h=c.encode(u,d);return r.copy(d,h),d.slice(0,h+r.length)}static from(e){let t=[...e];const n=ue(t);if(n!==(n&ct))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const s=ue(t),r=ue(t),o=X(t);let c=[];for(let S=0;S<o;S++){const f=Z(t,0,he);c.push(new y(a.bufferPolyfill.Buffer.from(f)))}const u=Z(t,0,he),d=X(t);let h=[];for(let S=0;S<d;S++){const f=ue(t),b=X(t),m=Z(t,0,b),P=X(t),T=Z(t,0,P),U=a.bs58.encode(a.bufferPolyfill.Buffer.from(T));h.push({programIdIndex:f,accounts:m,data:U})}const g={header:{numRequiredSignatures:n,numReadonlySignedAccounts:s,numReadonlyUnsignedAccounts:r},recentBlockhash:a.bs58.encode(a.bufferPolyfill.Buffer.from(u)),accountKeys:c,instructions:h};return new ae(g)}}class Be{constructor(e){this.header=void 0,this.staticAccountKeys=void 0,this.recentBlockhash=void 0,this.compiledInstructions=void 0,this.addressTableLookups=void 0,this.header=e.header,this.staticAccountKeys=e.staticAccountKeys,this.recentBlockhash=e.recentBlockhash,this.compiledInstructions=e.compiledInstructions,this.addressTableLookups=e.addressTableLookups}get version(){return 0}get numAccountKeysFromLookups(){let e=0;for(const t of this.addressTableLookups)e+=t.readonlyIndexes.length+t.writableIndexes.length;return e}getAccountKeys(e){let t;if(e&&"accountKeysFromLookups"in e&&e.accountKeysFromLookups){if(this.numAccountKeysFromLookups!=e.accountKeysFromLookups.writable.length+e.accountKeysFromLookups.readonly.length)throw new Error("Failed to get account keys because of a mismatch in the number of account keys from lookups");t=e.accountKeysFromLookups}else if(e&&"addressLookupTableAccounts"in e&&e.addressLookupTableAccounts)t=this.resolveAddressTableLookups(e.addressLookupTableAccounts);else if(this.addressTableLookups.length>0)throw new Error("Failed to get account keys because address table lookups were not resolved");return new Ye(this.staticAccountKeys,t)}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures,n=this.staticAccountKeys.length;if(e>=n){const s=e-n,r=this.addressTableLookups.reduce((o,c)=>o+c.writableIndexes.length,0);return s<r}else if(e>=this.header.numRequiredSignatures){const s=e-t,o=n-t-this.header.numReadonlyUnsignedAccounts;return s<o}else{const s=t-this.header.numReadonlySignedAccounts;return e<s}}resolveAddressTableLookups(e){const t={writable:[],readonly:[]};for(const n of this.addressTableLookups){const s=e.find(r=>r.key.equals(n.accountKey));if(!s)throw new Error(`Failed to find address lookup table account for table key ${n.accountKey.toBase58()}`);for(const r of n.writableIndexes)if(r<s.state.addresses.length)t.writable.push(s.state.addresses[r]);else throw new Error(`Failed to find address for index ${r} in address lookup table ${n.accountKey.toBase58()}`);for(const r of n.readonlyIndexes)if(r<s.state.addresses.length)t.readonly.push(s.state.addresses[r]);else throw new Error(`Failed to find address for index ${r} in address lookup table ${n.accountKey.toBase58()}`)}return t}static compile(e){const t=ut.compile(e.instructions,e.payerKey),n=new Array,s={writable:new Array,readonly:new Array},r=e.addressLookupTableAccounts||[];for(const h of r){const g=t.extractTableLookup(h);if(g!==void 0){const[S,{writable:f,readonly:b}]=g;n.push(S),s.writable.push(...f),s.readonly.push(...b)}}const[o,c]=t.getMessageComponents(),d=new Ye(c,s).compileInstructions(e.instructions);return new Be({header:o,staticAccountKeys:c,recentBlockhash:e.recentBlockhash,compiledInstructions:d,addressTableLookups:n})}serialize(){const e=Array();ne(e,this.staticAccountKeys.length);const t=this.serializeInstructions(),n=Array();ne(n,this.compiledInstructions.length);const s=this.serializeAddressTableLookups(),r=Array();ne(r,this.addressTableLookups.length);const o=a.struct([a.u8("prefix"),a.struct([a.u8("numRequiredSignatures"),a.u8("numReadonlySignedAccounts"),a.u8("numReadonlyUnsignedAccounts")],"header"),a.blob(e.length,"staticAccountKeysLength"),a.seq(K(),this.staticAccountKeys.length,"staticAccountKeys"),K("recentBlockhash"),a.blob(n.length,"instructionsLength"),a.blob(t.length,"serializedInstructions"),a.blob(r.length,"addressTableLookupsLength"),a.blob(s.length,"serializedAddressTableLookups")]),c=new Uint8Array(we),d=o.encode({prefix:128,header:this.header,staticAccountKeysLength:new Uint8Array(e),staticAccountKeys:this.staticAccountKeys.map(h=>h.toBytes()),recentBlockhash:a.bs58.decode(this.recentBlockhash),instructionsLength:new Uint8Array(n),serializedInstructions:t,addressTableLookupsLength:new Uint8Array(r),serializedAddressTableLookups:s},c);return c.slice(0,d)}serializeInstructions(){let e=0;const t=new Uint8Array(we);for(const n of this.compiledInstructions){const s=Array();ne(s,n.accountKeyIndexes.length);const r=Array();ne(r,n.data.length);const o=a.struct([a.u8("programIdIndex"),a.blob(s.length,"encodedAccountKeyIndexesLength"),a.seq(a.u8(),n.accountKeyIndexes.length,"accountKeyIndexes"),a.blob(r.length,"encodedDataLength"),a.blob(n.data.length,"data")]);e+=o.encode({programIdIndex:n.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(s),accountKeyIndexes:n.accountKeyIndexes,encodedDataLength:new Uint8Array(r),data:n.data},t,e)}return t.slice(0,e)}serializeAddressTableLookups(){let e=0;const t=new Uint8Array(we);for(const n of this.addressTableLookups){const s=Array();ne(s,n.writableIndexes.length);const r=Array();ne(r,n.readonlyIndexes.length);const o=a.struct([K("accountKey"),a.blob(s.length,"encodedWritableIndexesLength"),a.seq(a.u8(),n.writableIndexes.length,"writableIndexes"),a.blob(r.length,"encodedReadonlyIndexesLength"),a.seq(a.u8(),n.readonlyIndexes.length,"readonlyIndexes")]);e+=o.encode({accountKey:n.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(s),writableIndexes:n.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(r),readonlyIndexes:n.readonlyIndexes},t,e)}return t.slice(0,e)}static deserialize(e){let t=[...e];const n=ue(t),s=n&ct;O(n!==s,"Expected versioned message but received legacy message");const r=s;O(r===0,`Expected versioned message with version 0 but found version ${r}`);const o={numRequiredSignatures:ue(t),numReadonlySignedAccounts:ue(t),numReadonlyUnsignedAccounts:ue(t)},c=[],u=X(t);for(let b=0;b<u;b++)c.push(new y(Z(t,0,he)));const d=a.bs58.encode(Z(t,0,he)),h=X(t),g=[];for(let b=0;b<h;b++){const m=ue(t),P=X(t),T=Z(t,0,P),U=X(t),te=new Uint8Array(Z(t,0,U));g.push({programIdIndex:m,accountKeyIndexes:T,data:te})}const S=X(t),f=[];for(let b=0;b<S;b++){const m=new y(Z(t,0,he)),P=X(t),T=Z(t,0,P),U=X(t),te=Z(t,0,U);f.push({accountKey:m,writableIndexes:T,readonlyIndexes:te})}return new Be({header:o,staticAccountKeys:c,recentBlockhash:d,compiledInstructions:g,addressTableLookups:f})}}const Dt={deserializeMessageVersion(i){const e=i[0],t=e&ct;return t===e?"legacy":t},deserialize:i=>{const e=Dt.deserializeMessageVersion(i);if(e==="legacy")return ae.from(i);if(e===0)return Be.deserialize(i);throw new Error(`Transaction message version ${e} deserialization is not supported`)}};let be=function(i){return i[i.BLOCKHEIGHT_EXCEEDED=0]="BLOCKHEIGHT_EXCEEDED",i[i.PROCESSED=1]="PROCESSED",i[i.TIMED_OUT=2]="TIMED_OUT",i[i.NONCE_INVALID=3]="NONCE_INVALID",i}({});const tr=a.bufferPolyfill.Buffer.alloc(je).fill(0);class q{constructor(e){this.keys=void 0,this.programId=void 0,this.data=a.bufferPolyfill.Buffer.alloc(0),this.programId=e.programId,this.keys=e.keys,e.data&&(this.data=e.data)}toJSON(){return{keys:this.keys.map(({pubkey:e,isSigner:t,isWritable:n})=>({pubkey:e.toJSON(),isSigner:t,isWritable:n})),programId:this.programId.toJSON(),data:[...this.data]}}}class N{get signature(){return this.signatures.length>0?this.signatures[0].signature:null}constructor(e){if(this.signatures=[],this.feePayer=void 0,this.instructions=[],this.recentBlockhash=void 0,this.lastValidBlockHeight=void 0,this.nonceInfo=void 0,this.minNonceContextSlot=void 0,this._message=void 0,this._json=void 0,!!e)if(e.feePayer&&(this.feePayer=e.feePayer),e.signatures&&(this.signatures=e.signatures),Object.prototype.hasOwnProperty.call(e,"nonceInfo")){const{minContextSlot:t,nonceInfo:n}=e;this.minNonceContextSlot=t,this.nonceInfo=n}else if(Object.prototype.hasOwnProperty.call(e,"lastValidBlockHeight")){const{blockhash:t,lastValidBlockHeight:n}=e;this.recentBlockhash=t,this.lastValidBlockHeight=n}else{const{recentBlockhash:t,nonceInfo:n}=e;n&&(this.nonceInfo=n),this.recentBlockhash=t}}toJSON(){return{recentBlockhash:this.recentBlockhash||null,feePayer:this.feePayer?this.feePayer.toJSON():null,nonceInfo:this.nonceInfo?{nonce:this.nonceInfo.nonce,nonceInstruction:this.nonceInfo.nonceInstruction.toJSON()}:null,instructions:this.instructions.map(e=>e.toJSON()),signers:this.signatures.map(({publicKey:e})=>e.toJSON())}}add(...e){if(e.length===0)throw new Error("No instructions");return e.forEach(t=>{"instructions"in t?this.instructions=this.instructions.concat(t.instructions):"data"in t&&"programId"in t&&"keys"in t?this.instructions.push(t):this.instructions.push(new q(t))}),this}compileMessage(){if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json))return this._message;let e,t;if(this.nonceInfo?(e=this.nonceInfo.nonce,this.instructions[0]!=this.nonceInfo.nonceInstruction?t=[this.nonceInfo.nonceInstruction,...this.instructions]:t=this.instructions):(e=this.recentBlockhash,t=this.instructions),!e)throw new Error("Transaction recentBlockhash required");t.length<1&&console.warn("No instructions provided");let n;if(this.feePayer)n=this.feePayer;else if(this.signatures.length>0&&this.signatures[0].publicKey)n=this.signatures[0].publicKey;else throw new Error("Transaction fee payer required");for(let m=0;m<t.length;m++)if(t[m].programId===void 0)throw new Error(`Transaction instruction index ${m} has undefined program id`);const s=[],r=[];t.forEach(m=>{m.keys.forEach(T=>{r.push({...T})});const P=m.programId.toString();s.includes(P)||s.push(P)}),s.forEach(m=>{r.push({pubkey:new y(m),isSigner:!1,isWritable:!1})});const o=[];r.forEach(m=>{const P=m.pubkey.toString(),T=o.findIndex(U=>U.pubkey.toString()===P);T>-1?(o[T].isWritable=o[T].isWritable||m.isWritable,o[T].isSigner=o[T].isSigner||m.isSigner):o.push(m)}),o.sort(function(m,P){if(m.isSigner!==P.isSigner)return m.isSigner?-1:1;if(m.isWritable!==P.isWritable)return m.isWritable?-1:1;const T={localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"};return m.pubkey.toBase58().localeCompare(P.pubkey.toBase58(),"en",T)});const c=o.findIndex(m=>m.pubkey.equals(n));if(c>-1){const[m]=o.splice(c,1);m.isSigner=!0,m.isWritable=!0,o.unshift(m)}else o.unshift({pubkey:n,isSigner:!0,isWritable:!0});for(const m of this.signatures){const P=o.findIndex(T=>T.pubkey.equals(m.publicKey));if(P>-1)o[P].isSigner||(o[P].isSigner=!0,console.warn("Transaction references a signature that is unnecessary, only the fee payer and instruction signer accounts should sign a transaction. This behavior is deprecated and will throw an error in the next major version release."));else throw new Error(`unknown signer: ${m.publicKey.toString()}`)}let u=0,d=0,h=0;const g=[],S=[];o.forEach(({pubkey:m,isSigner:P,isWritable:T})=>{P?(g.push(m.toString()),u+=1,T||(d+=1)):(S.push(m.toString()),T||(h+=1))});const f=g.concat(S),b=t.map(m=>{const{data:P,programId:T}=m;return{programIdIndex:f.indexOf(T.toString()),accounts:m.keys.map(U=>f.indexOf(U.pubkey.toString())),data:a.bs58.encode(P)}});return b.forEach(m=>{O(m.programIdIndex>=0),m.accounts.forEach(P=>O(P>=0))}),new ae({header:{numRequiredSignatures:u,numReadonlySignedAccounts:d,numReadonlyUnsignedAccounts:h},accountKeys:f,recentBlockhash:e,instructions:b})}_compile(){const e=this.compileMessage(),t=e.accountKeys.slice(0,e.header.numRequiredSignatures);return this.signatures.length===t.length&&this.signatures.every((s,r)=>t[r].equals(s.publicKey))||(this.signatures=t.map(n=>({signature:null,publicKey:n}))),e}serializeMessage(){return this._compile().serialize()}async getEstimatedFee(e){return(await e.getFeeForMessage(this.compileMessage())).value}setSigners(...e){if(e.length===0)throw new Error("No signers");const t=new Set;this.signatures=e.filter(n=>{const s=n.toString();return t.has(s)?!1:(t.add(s),!0)}).map(n=>({signature:null,publicKey:n}))}sign(...e){if(e.length===0)throw new Error("No signers");const t=new Set,n=[];for(const r of e){const o=r.publicKey.toString();t.has(o)||(t.add(o),n.push(r))}this.signatures=n.map(r=>({signature:null,publicKey:r.publicKey}));const s=this._compile();this._partialSign(s,...n)}partialSign(...e){if(e.length===0)throw new Error("No signers");const t=new Set,n=[];for(const r of e){const o=r.publicKey.toString();t.has(o)||(t.add(o),n.push(r))}const s=this._compile();this._partialSign(s,...n)}_partialSign(e,...t){const n=e.serialize();t.forEach(s=>{const r=Ot(n,s.secretKey);this._addSignature(s.publicKey,x(r))})}addSignature(e,t){this._compile(),this._addSignature(e,t)}_addSignature(e,t){O(t.length===64);const n=this.signatures.findIndex(s=>e.equals(s.publicKey));if(n<0)throw new Error(`unknown signer: ${e.toString()}`);this.signatures[n].signature=a.bufferPolyfill.Buffer.from(t)}verifySignatures(e=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),e)}_getMessageSignednessErrors(e,t){const n={};for(const{signature:s,publicKey:r}of this.signatures)s===null?t&&(n.missing||(n.missing=[])).push(r):$s(s,e,r.toBytes())||(n.invalid||(n.invalid=[])).push(r);return n.invalid||n.missing?n:void 0}serialize(e){const{requireAllSignatures:t,verifySignatures:n}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},e),s=this.serializeMessage();if(n){const r=this._getMessageSignednessErrors(s,t);if(r){let o="Signature verification failed.";throw r.invalid&&(o+=`
|
|
1
|
+
"use strict";var Bs=Object.defineProperty;var Ts=(i,e,t)=>e in i?Bs(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var W=(i,e,t)=>(Ts(i,typeof e!="symbol"?e+"":e,t),t);const a=require("./index-C1oy9Lkm.js"),vs=require("./index-DnneI5--.js"),se=require("./solana--YauUjmQ.js"),Ls=require("./create-48Wkagqs.js"),Cs=require("./chain-BteoJHpg.js");function ge(i,e){return se.PublicKey.findProgramAddressSync(i,new se.PublicKey(e))[0]}function xs(i,e){return{pubkey:new se.PublicKey(i),isWritable:!0,isSigner:e}}function Ks(i,e){return{pubkey:new se.PublicKey(i),isWritable:!1,isSigner:e}}function Me(i){if(i===null)throw Error("account info is null");return i.data}class at{}W(at,"programId",new se.PublicKey("BPFLoaderUpgradeab1e11111111111111111111111"));function Rn(i){return ge([new se.PublicKey(i).toBuffer()],at.programId)}class zs extends Error{constructor(e){super(e),this.name="IdlError"}}function Kt(i,e){switch(e.type.kind){case"struct":return e.type.fields.map(t=>Pe(i,t.type)).reduce((t,n)=>t+n,0);case"enum":{const t=e.type.variants.map(n=>n.fields?n.fields.map(s=>typeof s=="object"&&"name"in s?Pe(i,s.type):Pe(i,s)).reduce((s,r)=>s+r,0):0);return Math.max(...t)+1}case"alias":return Pe(i,e.type.value)}}function Pe(i,e){var t;switch(e){case"bool":return 1;case"u8":return 1;case"i8":return 1;case"i16":return 2;case"u16":return 2;case"u32":return 4;case"i32":return 4;case"f32":return 4;case"u64":return 8;case"i64":return 8;case"f64":return 8;case"u128":return 16;case"i128":return 16;case"u256":return 32;case"i256":return 32;case"bytes":return 1;case"string":return 1;case"publicKey":return 32;default:if("vec"in e)return 1;if("option"in e)return 1+Pe(i,e.option);if("coption"in e)return 4+Pe(i,e.coption);if("defined"in e){const n=((t=i.types)==null?void 0:t.filter(r=>r.name===e.defined))??[];if(n.length!==1)throw new zs(`Type not found: ${JSON.stringify(e)}`);let s=n[0];return Kt(i,s)}if("array"in e){let n=e.array[0],s=e.array[1];return Pe(i,n)*s}throw new Error(`Invalid type ${JSON.stringify(e)}`)}}function Ve(i){return i.replace(/(?:^\w|[A-Z]|\b\w)/g,function(e,t){return t===0?e.toLowerCase():e.toUpperCase()}).replace(/[\s\-_]+/g,"")}function Ns(i){return i.charAt(0).toUpperCase()+i.slice(1)}class Ws extends TypeError{constructor(e,t){let n;const{message:s,...r}=e,{path:o}=e,c=o.length===0?s:"At path: "+o.join(".")+" -- "+s;super(c),Object.assign(this,r),this.name=this.constructor.name,this.failures=()=>{var u;return(u=n)!=null?u:n=[e,...t()]}}}function Os(i){return Se(i)&&typeof i[Symbol.iterator]=="function"}function Se(i){return typeof i=="object"&&i!=null}function oe(i){return typeof i=="string"?JSON.stringify(i):""+i}function Ms(i){const{done:e,value:t}=i.next();return e?void 0:t}function Us(i,e,t,n){if(i===!0)return;i===!1?i={}:typeof i=="string"&&(i={message:i});const{path:s,branch:r}=e,{type:o}=t,{refinement:c,message:u="Expected a value of type `"+o+"`"+(c?" with refinement `"+c+"`":"")+", but received: `"+oe(n)+"`"}=i;return{value:n,type:o,refinement:c,key:s[s.length-1],path:s,branch:r,...i,message:u}}function*an(i,e,t,n){Os(i)||(i=[i]);for(const s of i){const r=Us(s,e,t,n);r&&(yield r)}}function*zt(i,e,t={}){const{path:n=[],branch:s=[i],coerce:r=!1,mask:o=!1}=t,c={path:n,branch:s};if(r&&(i=e.coercer(i,c),o&&e.type!=="type"&&Se(e.schema)&&Se(i)&&!Array.isArray(i)))for(const d in i)e.schema[d]===void 0&&delete i[d];let u=!0;for(const d of e.validator(i,c))u=!1,yield[d,void 0];for(let[d,h,g]of e.entries(i,c)){const S=zt(h,g,{path:d===void 0?n:[...n,d],branch:d===void 0?s:[...s,h],coerce:r,mask:o});for(const f of S)f[0]?(u=!1,yield[f[0],void 0]):r&&(h=f[1],d===void 0?i=h:i instanceof Map?i.set(d,h):i instanceof Set?i.add(h):Se(i)&&(i[d]=h))}if(u)for(const d of e.refiner(i,c))u=!1,yield[d,void 0];u&&(yield[void 0,i])}let ye=class{constructor(e){const{type:t,schema:n,validator:s,refiner:r,coercer:o=u=>u,entries:c=function*(){}}=e;this.type=t,this.schema=n,this.entries=c,this.coercer=o,s?this.validator=(u,d)=>{const h=s(u,d);return an(h,d,this,u)}:this.validator=()=>[],r?this.refiner=(u,d)=>{const h=r(u,d);return an(h,d,this,u)}:this.refiner=()=>[]}assert(e){return En(e,this)}create(e){return w(e,this)}is(e){return Bn(e,this)}mask(e){return qs(e,this)}validate(e,t={}){return Xe(e,this,t)}};function En(i,e){const t=Xe(i,e);if(t[0])throw t[0]}function w(i,e){const t=Xe(i,e,{coerce:!0});if(t[0])throw t[0];return t[1]}function qs(i,e){const t=Xe(i,e,{coerce:!0,mask:!0});if(t[0])throw t[0];return t[1]}function Bn(i,e){return!Xe(i,e)[0]}function Xe(i,e,t={}){const n=zt(i,e,t),s=Ms(n);return s[0]?[new Ws(s[0],function*(){for(const o of n)o[0]&&(yield o[0])}),void 0]:[void 0,s[1]]}function Le(i,e){return new ye({type:i,schema:null,validator:e})}function Ds(){return Le("any",()=>!0)}function A(i){return new ye({type:"array",schema:i,*entries(e){if(i&&Array.isArray(e))for(const[t,n]of e.entries())yield[t,n,i]},coercer(e){return Array.isArray(e)?e.slice():e},validator(e){return Array.isArray(e)||"Expected an array value, but received: "+oe(e)}})}function fe(){return Le("boolean",i=>typeof i=="boolean")}function Nt(i){return Le("instance",e=>e instanceof i||"Expected a `"+i.name+"` instance, but received: "+oe(e))}function H(i){const e=oe(i),t=typeof i;return new ye({type:"literal",schema:t==="string"||t==="number"||t==="boolean"?i:null,validator(n){return n===i||"Expected the literal `"+e+"`, but received: "+oe(n)}})}function Fs(){return Le("never",()=>!1)}function I(i){return new ye({...i,validator:(e,t)=>e===null||i.validator(e,t),refiner:(e,t)=>e===null||i.refiner(e,t)})}function l(){return Le("number",i=>typeof i=="number"&&!isNaN(i)||"Expected a number, but received: "+oe(i))}function B(i){return new ye({...i,validator:(e,t)=>e===void 0||i.validator(e,t),refiner:(e,t)=>e===void 0||i.refiner(e,t)})}function Tn(i,e){return new ye({type:"record",schema:null,*entries(t){if(Se(t))for(const n in t){const s=t[n];yield[n,n,i],yield[n,s,e]}},validator(t){return Se(t)||"Expected an object, but received: "+oe(t)}})}function k(){return Le("string",i=>typeof i=="string"||"Expected a string, but received: "+oe(i))}function Wt(i){const e=Fs();return new ye({type:"tuple",schema:null,*entries(t){if(Array.isArray(t)){const n=Math.max(i.length,t.length);for(let s=0;s<n;s++)yield[s,t[s],i[s]||e]}},validator(t){return Array.isArray(t)||"Expected an array, but received: "+oe(t)}})}function p(i){const e=Object.keys(i);return new ye({type:"type",schema:i,*entries(t){if(Se(t))for(const n of e)yield[n,t[n],i[n]]},validator(t){return Se(t)||"Expected an object, but received: "+oe(t)}})}function ee(i){const e=i.map(t=>t.type).join(" | ");return new ye({type:"union",schema:null,validator(t,n){const s=[];for(const r of i){const[...o]=zt(t,r,n),[c]=o;if(c[0])for(const[u]of o)u&&s.push(u);else return[]}return["Expected the value to satisfy a union of `"+e+"`, but received: "+oe(t),...s]}})}function Ze(){return Le("unknown",()=>!0)}function Qe(i,e,t){return new ye({...i,coercer:(n,s)=>Bn(n,e)?i.coercer(t(n,s),s):i.coercer(n,s)})}const Vs=a.ed25519.utils.randomPrivateKey,cn=()=>{const i=a.ed25519.utils.randomPrivateKey(),e=rt(i),t=new Uint8Array(64);return t.set(i),t.set(e,32),{publicKey:e,secretKey:t}},rt=a.ed25519.getPublicKey;function un(i){try{return a.ed25519.ExtendedPoint.fromHex(i),!0}catch{return!1}}const Ot=(i,e)=>a.ed25519.sign(i,e.slice(0,32)),$s=a.ed25519.verify,x=i=>a.bufferPolyfill.Buffer.isBuffer(i)?i:i instanceof Uint8Array?a.bufferPolyfill.Buffer.from(i.buffer,i.byteOffset,i.byteLength):a.bufferPolyfill.Buffer.from(i);class Mt{constructor(e){Object.assign(this,e)}encode(){return a.bufferPolyfill.Buffer.from(a.serialize_1(He,this))}static decode(e){return a.deserialize_1(He,this,e)}static decodeUnchecked(e){return a.deserializeUnchecked_1(He,this,e)}}class Hs extends Mt{constructor(e){if(super(e),this.enum="",Object.keys(e).length!==1)throw new Error("Enum can only take single value");Object.keys(e).map(t=>{this.enum=t})}}const He=new Map;var vn;let Ln;const Cn=32,he=32;function Gs(i){return i._bn!==void 0}let ln=1;Ln=Symbol.toStringTag;class y extends Mt{constructor(e){if(super({}),this._bn=void 0,Gs(e))this._bn=e._bn;else{if(typeof e=="string"){const t=a.bs58.decode(e);if(t.length!=he)throw new Error("Invalid public key input");this._bn=new a.BN(t)}else this._bn=new a.BN(e);if(this._bn.byteLength()>he)throw new Error("Invalid public key input")}}static unique(){const e=new y(ln);return ln+=1,new y(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return a.bs58.encode(this.toBytes())}toJSON(){return this.toBase58()}toBytes(){const e=this.toBuffer();return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}toBuffer(){const e=this._bn.toArrayLike(a.bufferPolyfill.Buffer);if(e.length===he)return e;const t=a.bufferPolyfill.Buffer.alloc(32);return e.copy(t,32-e.length),t}get[Ln](){return`PublicKey(${this.toString()})`}toString(){return this.toBase58()}static async createWithSeed(e,t,n){const s=a.bufferPolyfill.Buffer.concat([e.toBuffer(),a.bufferPolyfill.Buffer.from(t),n.toBuffer()]),r=a.sha256(s);return new y(r)}static createProgramAddressSync(e,t){let n=a.bufferPolyfill.Buffer.alloc(0);e.forEach(function(r){if(r.length>Cn)throw new TypeError("Max seed length exceeded");n=a.bufferPolyfill.Buffer.concat([n,x(r)])}),n=a.bufferPolyfill.Buffer.concat([n,t.toBuffer(),a.bufferPolyfill.Buffer.from("ProgramDerivedAddress")]);const s=a.sha256(n);if(un(s))throw new Error("Invalid seeds, address must fall off the curve");return new y(s)}static async createProgramAddress(e,t){return this.createProgramAddressSync(e,t)}static findProgramAddressSync(e,t){let n=255,s;for(;n!=0;){try{const r=e.concat(a.bufferPolyfill.Buffer.from([n]));s=this.createProgramAddressSync(r,t)}catch(r){if(r instanceof TypeError)throw r;n--;continue}return[s,n]}throw new Error("Unable to find a viable program address nonce")}static async findProgramAddress(e,t){return this.findProgramAddressSync(e,t)}static isOnCurve(e){const t=new y(e);return un(t.toBytes())}}vn=y;y.default=new vn("11111111111111111111111111111111");He.set(y,{kind:"struct",fields:[["_bn","u256"]]});class js{constructor(e){if(this._publicKey=void 0,this._secretKey=void 0,e){const t=x(e);if(e.length!==64)throw new Error("bad secret key size");this._publicKey=t.slice(32,64),this._secretKey=t.slice(0,32)}else this._secretKey=x(Vs()),this._publicKey=x(rt(this._secretKey))}get publicKey(){return new y(this._publicKey)}get secretKey(){return a.bufferPolyfill.Buffer.concat([this._secretKey,this._publicKey],64)}}const Ys=new y("BPFLoader1111111111111111111111111111111111"),we=1232,ct=127,je=64;class Ut extends Error{constructor(e){super(`Signature ${e} has expired: block height exceeded.`),this.signature=void 0,this.signature=e}}Object.defineProperty(Ut.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class qt extends Error{constructor(e,t){super(`Transaction was not confirmed in ${t.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${e} using the Solana Explorer or CLI tools.`),this.signature=void 0,this.signature=e}}Object.defineProperty(qt.prototype,"name",{value:"TransactionExpiredTimeoutError"});class ze extends Error{constructor(e){super(`Signature ${e} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=e}}Object.defineProperty(ze.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class Ye{constructor(e,t){this.staticAccountKeys=void 0,this.accountKeysFromLookups=void 0,this.staticAccountKeys=e,this.accountKeysFromLookups=t}keySegments(){const e=[this.staticAccountKeys];return this.accountKeysFromLookups&&(e.push(this.accountKeysFromLookups.writable),e.push(this.accountKeysFromLookups.readonly)),e}get(e){for(const t of this.keySegments()){if(e<t.length)return t[e];e-=t.length}}get length(){return this.keySegments().flat().length}compileInstructions(e){if(this.length>256)throw new Error("Account index overflow encountered during compilation");const n=new Map;this.keySegments().flat().forEach((r,o)=>{n.set(r.toBase58(),o)});const s=r=>{const o=n.get(r.toBase58());if(o===void 0)throw new Error("Encountered an unknown instruction account key during compilation");return o};return e.map(r=>({programIdIndex:s(r.programId),accountKeyIndexes:r.keys.map(o=>s(o.pubkey)),data:r.data}))}}const K=(i="publicKey")=>a.blob(32,i),Js=(i="signature")=>a.blob(64,i),Re=(i="string")=>{const e=a.struct([a.u32("length"),a.u32("lengthPadding"),a.blob(a.offset(a.u32(),-8),"chars")],i),t=e.decode.bind(e),n=e.encode.bind(e),s=e;return s.decode=(r,o)=>t(r,o).chars.toString(),s.encode=(r,o,c)=>{const u={chars:a.bufferPolyfill.Buffer.from(r,"utf8")};return n(u,o,c)},s.alloc=r=>a.u32().span+a.u32().span+a.bufferPolyfill.Buffer.from(r,"utf8").length,s},Xs=(i="authorized")=>a.struct([K("staker"),K("withdrawer")],i),Zs=(i="lockup")=>a.struct([a.ns64("unixTimestamp"),a.ns64("epoch"),K("custodian")],i),Qs=(i="voteInit")=>a.struct([K("nodePubkey"),K("authorizedVoter"),K("authorizedWithdrawer"),a.u8("commission")],i),er=(i="voteAuthorizeWithSeedArgs")=>a.struct([a.u32("voteAuthorizationType"),K("currentAuthorityDerivedKeyOwnerPubkey"),Re("currentAuthorityDerivedKeySeed"),K("newAuthorized")],i);function xn(i,e){const t=s=>{if(s.span>=0)return s.span;if(typeof s.alloc=="function")return s.alloc(e[s.property]);if("count"in s&&"elementLayout"in s){const r=e[s.property];if(Array.isArray(r))return r.length*t(s.elementLayout)}else if("fields"in s)return xn({layout:s},e[s.property]);return 0};let n=0;return i.layout.fields.forEach(s=>{n+=t(s)}),n}function X(i){let e=0,t=0;for(;;){let n=i.shift();if(e|=(n&127)<<t*7,t+=1,!(n&128))break}return e}function ne(i,e){let t=e;for(;;){let n=t&127;if(t>>=7,t==0){i.push(n);break}else n|=128,i.push(n)}}function O(i,e){if(!i)throw new Error(e||"Assertion failed")}class ut{constructor(e,t){this.payer=void 0,this.keyMetaMap=void 0,this.payer=e,this.keyMetaMap=t}static compile(e,t){const n=new Map,s=o=>{const c=o.toBase58();let u=n.get(c);return u===void 0&&(u={isSigner:!1,isWritable:!1,isInvoked:!1},n.set(c,u)),u},r=s(t);r.isSigner=!0,r.isWritable=!0;for(const o of e){s(o.programId).isInvoked=!0;for(const c of o.keys){const u=s(c.pubkey);u.isSigner||(u.isSigner=c.isSigner),u.isWritable||(u.isWritable=c.isWritable)}}return new ut(t,n)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];O(e.length<=256,"Max static account keys length exceeded");const t=e.filter(([,u])=>u.isSigner&&u.isWritable),n=e.filter(([,u])=>u.isSigner&&!u.isWritable),s=e.filter(([,u])=>!u.isSigner&&u.isWritable),r=e.filter(([,u])=>!u.isSigner&&!u.isWritable),o={numRequiredSignatures:t.length+n.length,numReadonlySignedAccounts:n.length,numReadonlyUnsignedAccounts:r.length};{O(t.length>0,"Expected at least one writable signer key");const[u]=t[0];O(u===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}const c=[...t.map(([u])=>new y(u)),...n.map(([u])=>new y(u)),...s.map(([u])=>new y(u)),...r.map(([u])=>new y(u))];return[o,c]}extractTableLookup(e){const[t,n]=this.drainKeysFoundInLookupTable(e.state.addresses,o=>!o.isSigner&&!o.isInvoked&&o.isWritable),[s,r]=this.drainKeysFoundInLookupTable(e.state.addresses,o=>!o.isSigner&&!o.isInvoked&&!o.isWritable);if(!(t.length===0&&s.length===0))return[{accountKey:e.key,writableIndexes:t,readonlyIndexes:s},{writable:n,readonly:r}]}drainKeysFoundInLookupTable(e,t){const n=new Array,s=new Array;for(const[r,o]of this.keyMetaMap.entries())if(t(o)){const c=new y(r),u=e.findIndex(d=>d.equals(c));u>=0&&(O(u<256,"Max lookup table index exceeded"),n.push(u),s.push(c),this.keyMetaMap.delete(r))}return[n,s]}}const Kn="Reached end of buffer unexpectedly";function ue(i){if(i.length===0)throw new Error(Kn);return i.shift()}function Z(i,...e){const[t]=e;if(e.length===2?t+(e[1]??0)>i.length:t>=i.length)throw new Error(Kn);return i.splice(...e)}class ae{constructor(e){this.header=void 0,this.accountKeys=void 0,this.recentBlockhash=void 0,this.instructions=void 0,this.indexToProgramIds=new Map,this.header=e.header,this.accountKeys=e.accountKeys.map(t=>new y(t)),this.recentBlockhash=e.recentBlockhash,this.instructions=e.instructions,this.instructions.forEach(t=>this.indexToProgramIds.set(t.programIdIndex,this.accountKeys[t.programIdIndex]))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:a.bs58.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new Ye(this.staticAccountKeys)}static compile(e){const t=ut.compile(e.instructions,e.payerKey),[n,s]=t.getMessageComponents(),o=new Ye(s).compileInstructions(e.instructions).map(c=>({programIdIndex:c.programIdIndex,accounts:c.accountKeyIndexes,data:a.bs58.encode(c.data)}));return new ae({header:n,accountKeys:s,recentBlockhash:e.recentBlockhash,instructions:o})}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures;if(e>=this.header.numRequiredSignatures){const n=e-t,r=this.accountKeys.length-t-this.header.numReadonlyUnsignedAccounts;return n<r}else{const n=t-this.header.numReadonlySignedAccounts;return e<n}}isProgramId(e){return this.indexToProgramIds.has(e)}programIds(){return[...this.indexToProgramIds.values()]}nonProgramIds(){return this.accountKeys.filter((e,t)=>!this.isProgramId(t))}serialize(){const e=this.accountKeys.length;let t=[];ne(t,e);const n=this.instructions.map(g=>{const{accounts:S,programIdIndex:f}=g,b=Array.from(a.bs58.decode(g.data));let m=[];ne(m,S.length);let P=[];return ne(P,b.length),{programIdIndex:f,keyIndicesCount:a.bufferPolyfill.Buffer.from(m),keyIndices:S,dataLength:a.bufferPolyfill.Buffer.from(P),data:b}});let s=[];ne(s,n.length);let r=a.bufferPolyfill.Buffer.alloc(we);a.bufferPolyfill.Buffer.from(s).copy(r);let o=s.length;n.forEach(g=>{const f=a.struct([a.u8("programIdIndex"),a.blob(g.keyIndicesCount.length,"keyIndicesCount"),a.seq(a.u8("keyIndex"),g.keyIndices.length,"keyIndices"),a.blob(g.dataLength.length,"dataLength"),a.seq(a.u8("userdatum"),g.data.length,"data")]).encode(g,r,o);o+=f}),r=r.slice(0,o);const c=a.struct([a.blob(1,"numRequiredSignatures"),a.blob(1,"numReadonlySignedAccounts"),a.blob(1,"numReadonlyUnsignedAccounts"),a.blob(t.length,"keyCount"),a.seq(K("key"),e,"keys"),K("recentBlockhash")]),u={numRequiredSignatures:a.bufferPolyfill.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:a.bufferPolyfill.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:a.bufferPolyfill.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:a.bufferPolyfill.Buffer.from(t),keys:this.accountKeys.map(g=>x(g.toBytes())),recentBlockhash:a.bs58.decode(this.recentBlockhash)};let d=a.bufferPolyfill.Buffer.alloc(2048);const h=c.encode(u,d);return r.copy(d,h),d.slice(0,h+r.length)}static from(e){let t=[...e];const n=ue(t);if(n!==(n&ct))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const s=ue(t),r=ue(t),o=X(t);let c=[];for(let S=0;S<o;S++){const f=Z(t,0,he);c.push(new y(a.bufferPolyfill.Buffer.from(f)))}const u=Z(t,0,he),d=X(t);let h=[];for(let S=0;S<d;S++){const f=ue(t),b=X(t),m=Z(t,0,b),P=X(t),T=Z(t,0,P),U=a.bs58.encode(a.bufferPolyfill.Buffer.from(T));h.push({programIdIndex:f,accounts:m,data:U})}const g={header:{numRequiredSignatures:n,numReadonlySignedAccounts:s,numReadonlyUnsignedAccounts:r},recentBlockhash:a.bs58.encode(a.bufferPolyfill.Buffer.from(u)),accountKeys:c,instructions:h};return new ae(g)}}class Be{constructor(e){this.header=void 0,this.staticAccountKeys=void 0,this.recentBlockhash=void 0,this.compiledInstructions=void 0,this.addressTableLookups=void 0,this.header=e.header,this.staticAccountKeys=e.staticAccountKeys,this.recentBlockhash=e.recentBlockhash,this.compiledInstructions=e.compiledInstructions,this.addressTableLookups=e.addressTableLookups}get version(){return 0}get numAccountKeysFromLookups(){let e=0;for(const t of this.addressTableLookups)e+=t.readonlyIndexes.length+t.writableIndexes.length;return e}getAccountKeys(e){let t;if(e&&"accountKeysFromLookups"in e&&e.accountKeysFromLookups){if(this.numAccountKeysFromLookups!=e.accountKeysFromLookups.writable.length+e.accountKeysFromLookups.readonly.length)throw new Error("Failed to get account keys because of a mismatch in the number of account keys from lookups");t=e.accountKeysFromLookups}else if(e&&"addressLookupTableAccounts"in e&&e.addressLookupTableAccounts)t=this.resolveAddressTableLookups(e.addressLookupTableAccounts);else if(this.addressTableLookups.length>0)throw new Error("Failed to get account keys because address table lookups were not resolved");return new Ye(this.staticAccountKeys,t)}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures,n=this.staticAccountKeys.length;if(e>=n){const s=e-n,r=this.addressTableLookups.reduce((o,c)=>o+c.writableIndexes.length,0);return s<r}else if(e>=this.header.numRequiredSignatures){const s=e-t,o=n-t-this.header.numReadonlyUnsignedAccounts;return s<o}else{const s=t-this.header.numReadonlySignedAccounts;return e<s}}resolveAddressTableLookups(e){const t={writable:[],readonly:[]};for(const n of this.addressTableLookups){const s=e.find(r=>r.key.equals(n.accountKey));if(!s)throw new Error(`Failed to find address lookup table account for table key ${n.accountKey.toBase58()}`);for(const r of n.writableIndexes)if(r<s.state.addresses.length)t.writable.push(s.state.addresses[r]);else throw new Error(`Failed to find address for index ${r} in address lookup table ${n.accountKey.toBase58()}`);for(const r of n.readonlyIndexes)if(r<s.state.addresses.length)t.readonly.push(s.state.addresses[r]);else throw new Error(`Failed to find address for index ${r} in address lookup table ${n.accountKey.toBase58()}`)}return t}static compile(e){const t=ut.compile(e.instructions,e.payerKey),n=new Array,s={writable:new Array,readonly:new Array},r=e.addressLookupTableAccounts||[];for(const h of r){const g=t.extractTableLookup(h);if(g!==void 0){const[S,{writable:f,readonly:b}]=g;n.push(S),s.writable.push(...f),s.readonly.push(...b)}}const[o,c]=t.getMessageComponents(),d=new Ye(c,s).compileInstructions(e.instructions);return new Be({header:o,staticAccountKeys:c,recentBlockhash:e.recentBlockhash,compiledInstructions:d,addressTableLookups:n})}serialize(){const e=Array();ne(e,this.staticAccountKeys.length);const t=this.serializeInstructions(),n=Array();ne(n,this.compiledInstructions.length);const s=this.serializeAddressTableLookups(),r=Array();ne(r,this.addressTableLookups.length);const o=a.struct([a.u8("prefix"),a.struct([a.u8("numRequiredSignatures"),a.u8("numReadonlySignedAccounts"),a.u8("numReadonlyUnsignedAccounts")],"header"),a.blob(e.length,"staticAccountKeysLength"),a.seq(K(),this.staticAccountKeys.length,"staticAccountKeys"),K("recentBlockhash"),a.blob(n.length,"instructionsLength"),a.blob(t.length,"serializedInstructions"),a.blob(r.length,"addressTableLookupsLength"),a.blob(s.length,"serializedAddressTableLookups")]),c=new Uint8Array(we),d=o.encode({prefix:128,header:this.header,staticAccountKeysLength:new Uint8Array(e),staticAccountKeys:this.staticAccountKeys.map(h=>h.toBytes()),recentBlockhash:a.bs58.decode(this.recentBlockhash),instructionsLength:new Uint8Array(n),serializedInstructions:t,addressTableLookupsLength:new Uint8Array(r),serializedAddressTableLookups:s},c);return c.slice(0,d)}serializeInstructions(){let e=0;const t=new Uint8Array(we);for(const n of this.compiledInstructions){const s=Array();ne(s,n.accountKeyIndexes.length);const r=Array();ne(r,n.data.length);const o=a.struct([a.u8("programIdIndex"),a.blob(s.length,"encodedAccountKeyIndexesLength"),a.seq(a.u8(),n.accountKeyIndexes.length,"accountKeyIndexes"),a.blob(r.length,"encodedDataLength"),a.blob(n.data.length,"data")]);e+=o.encode({programIdIndex:n.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(s),accountKeyIndexes:n.accountKeyIndexes,encodedDataLength:new Uint8Array(r),data:n.data},t,e)}return t.slice(0,e)}serializeAddressTableLookups(){let e=0;const t=new Uint8Array(we);for(const n of this.addressTableLookups){const s=Array();ne(s,n.writableIndexes.length);const r=Array();ne(r,n.readonlyIndexes.length);const o=a.struct([K("accountKey"),a.blob(s.length,"encodedWritableIndexesLength"),a.seq(a.u8(),n.writableIndexes.length,"writableIndexes"),a.blob(r.length,"encodedReadonlyIndexesLength"),a.seq(a.u8(),n.readonlyIndexes.length,"readonlyIndexes")]);e+=o.encode({accountKey:n.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(s),writableIndexes:n.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(r),readonlyIndexes:n.readonlyIndexes},t,e)}return t.slice(0,e)}static deserialize(e){let t=[...e];const n=ue(t),s=n&ct;O(n!==s,"Expected versioned message but received legacy message");const r=s;O(r===0,`Expected versioned message with version 0 but found version ${r}`);const o={numRequiredSignatures:ue(t),numReadonlySignedAccounts:ue(t),numReadonlyUnsignedAccounts:ue(t)},c=[],u=X(t);for(let b=0;b<u;b++)c.push(new y(Z(t,0,he)));const d=a.bs58.encode(Z(t,0,he)),h=X(t),g=[];for(let b=0;b<h;b++){const m=ue(t),P=X(t),T=Z(t,0,P),U=X(t),te=new Uint8Array(Z(t,0,U));g.push({programIdIndex:m,accountKeyIndexes:T,data:te})}const S=X(t),f=[];for(let b=0;b<S;b++){const m=new y(Z(t,0,he)),P=X(t),T=Z(t,0,P),U=X(t),te=Z(t,0,U);f.push({accountKey:m,writableIndexes:T,readonlyIndexes:te})}return new Be({header:o,staticAccountKeys:c,recentBlockhash:d,compiledInstructions:g,addressTableLookups:f})}}const Dt={deserializeMessageVersion(i){const e=i[0],t=e&ct;return t===e?"legacy":t},deserialize:i=>{const e=Dt.deserializeMessageVersion(i);if(e==="legacy")return ae.from(i);if(e===0)return Be.deserialize(i);throw new Error(`Transaction message version ${e} deserialization is not supported`)}};let be=function(i){return i[i.BLOCKHEIGHT_EXCEEDED=0]="BLOCKHEIGHT_EXCEEDED",i[i.PROCESSED=1]="PROCESSED",i[i.TIMED_OUT=2]="TIMED_OUT",i[i.NONCE_INVALID=3]="NONCE_INVALID",i}({});const tr=a.bufferPolyfill.Buffer.alloc(je).fill(0);class q{constructor(e){this.keys=void 0,this.programId=void 0,this.data=a.bufferPolyfill.Buffer.alloc(0),this.programId=e.programId,this.keys=e.keys,e.data&&(this.data=e.data)}toJSON(){return{keys:this.keys.map(({pubkey:e,isSigner:t,isWritable:n})=>({pubkey:e.toJSON(),isSigner:t,isWritable:n})),programId:this.programId.toJSON(),data:[...this.data]}}}class N{get signature(){return this.signatures.length>0?this.signatures[0].signature:null}constructor(e){if(this.signatures=[],this.feePayer=void 0,this.instructions=[],this.recentBlockhash=void 0,this.lastValidBlockHeight=void 0,this.nonceInfo=void 0,this.minNonceContextSlot=void 0,this._message=void 0,this._json=void 0,!!e)if(e.feePayer&&(this.feePayer=e.feePayer),e.signatures&&(this.signatures=e.signatures),Object.prototype.hasOwnProperty.call(e,"nonceInfo")){const{minContextSlot:t,nonceInfo:n}=e;this.minNonceContextSlot=t,this.nonceInfo=n}else if(Object.prototype.hasOwnProperty.call(e,"lastValidBlockHeight")){const{blockhash:t,lastValidBlockHeight:n}=e;this.recentBlockhash=t,this.lastValidBlockHeight=n}else{const{recentBlockhash:t,nonceInfo:n}=e;n&&(this.nonceInfo=n),this.recentBlockhash=t}}toJSON(){return{recentBlockhash:this.recentBlockhash||null,feePayer:this.feePayer?this.feePayer.toJSON():null,nonceInfo:this.nonceInfo?{nonce:this.nonceInfo.nonce,nonceInstruction:this.nonceInfo.nonceInstruction.toJSON()}:null,instructions:this.instructions.map(e=>e.toJSON()),signers:this.signatures.map(({publicKey:e})=>e.toJSON())}}add(...e){if(e.length===0)throw new Error("No instructions");return e.forEach(t=>{"instructions"in t?this.instructions=this.instructions.concat(t.instructions):"data"in t&&"programId"in t&&"keys"in t?this.instructions.push(t):this.instructions.push(new q(t))}),this}compileMessage(){if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json))return this._message;let e,t;if(this.nonceInfo?(e=this.nonceInfo.nonce,this.instructions[0]!=this.nonceInfo.nonceInstruction?t=[this.nonceInfo.nonceInstruction,...this.instructions]:t=this.instructions):(e=this.recentBlockhash,t=this.instructions),!e)throw new Error("Transaction recentBlockhash required");t.length<1&&console.warn("No instructions provided");let n;if(this.feePayer)n=this.feePayer;else if(this.signatures.length>0&&this.signatures[0].publicKey)n=this.signatures[0].publicKey;else throw new Error("Transaction fee payer required");for(let m=0;m<t.length;m++)if(t[m].programId===void 0)throw new Error(`Transaction instruction index ${m} has undefined program id`);const s=[],r=[];t.forEach(m=>{m.keys.forEach(T=>{r.push({...T})});const P=m.programId.toString();s.includes(P)||s.push(P)}),s.forEach(m=>{r.push({pubkey:new y(m),isSigner:!1,isWritable:!1})});const o=[];r.forEach(m=>{const P=m.pubkey.toString(),T=o.findIndex(U=>U.pubkey.toString()===P);T>-1?(o[T].isWritable=o[T].isWritable||m.isWritable,o[T].isSigner=o[T].isSigner||m.isSigner):o.push(m)}),o.sort(function(m,P){if(m.isSigner!==P.isSigner)return m.isSigner?-1:1;if(m.isWritable!==P.isWritable)return m.isWritable?-1:1;const T={localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"};return m.pubkey.toBase58().localeCompare(P.pubkey.toBase58(),"en",T)});const c=o.findIndex(m=>m.pubkey.equals(n));if(c>-1){const[m]=o.splice(c,1);m.isSigner=!0,m.isWritable=!0,o.unshift(m)}else o.unshift({pubkey:n,isSigner:!0,isWritable:!0});for(const m of this.signatures){const P=o.findIndex(T=>T.pubkey.equals(m.publicKey));if(P>-1)o[P].isSigner||(o[P].isSigner=!0,console.warn("Transaction references a signature that is unnecessary, only the fee payer and instruction signer accounts should sign a transaction. This behavior is deprecated and will throw an error in the next major version release."));else throw new Error(`unknown signer: ${m.publicKey.toString()}`)}let u=0,d=0,h=0;const g=[],S=[];o.forEach(({pubkey:m,isSigner:P,isWritable:T})=>{P?(g.push(m.toString()),u+=1,T||(d+=1)):(S.push(m.toString()),T||(h+=1))});const f=g.concat(S),b=t.map(m=>{const{data:P,programId:T}=m;return{programIdIndex:f.indexOf(T.toString()),accounts:m.keys.map(U=>f.indexOf(U.pubkey.toString())),data:a.bs58.encode(P)}});return b.forEach(m=>{O(m.programIdIndex>=0),m.accounts.forEach(P=>O(P>=0))}),new ae({header:{numRequiredSignatures:u,numReadonlySignedAccounts:d,numReadonlyUnsignedAccounts:h},accountKeys:f,recentBlockhash:e,instructions:b})}_compile(){const e=this.compileMessage(),t=e.accountKeys.slice(0,e.header.numRequiredSignatures);return this.signatures.length===t.length&&this.signatures.every((s,r)=>t[r].equals(s.publicKey))||(this.signatures=t.map(n=>({signature:null,publicKey:n}))),e}serializeMessage(){return this._compile().serialize()}async getEstimatedFee(e){return(await e.getFeeForMessage(this.compileMessage())).value}setSigners(...e){if(e.length===0)throw new Error("No signers");const t=new Set;this.signatures=e.filter(n=>{const s=n.toString();return t.has(s)?!1:(t.add(s),!0)}).map(n=>({signature:null,publicKey:n}))}sign(...e){if(e.length===0)throw new Error("No signers");const t=new Set,n=[];for(const r of e){const o=r.publicKey.toString();t.has(o)||(t.add(o),n.push(r))}this.signatures=n.map(r=>({signature:null,publicKey:r.publicKey}));const s=this._compile();this._partialSign(s,...n)}partialSign(...e){if(e.length===0)throw new Error("No signers");const t=new Set,n=[];for(const r of e){const o=r.publicKey.toString();t.has(o)||(t.add(o),n.push(r))}const s=this._compile();this._partialSign(s,...n)}_partialSign(e,...t){const n=e.serialize();t.forEach(s=>{const r=Ot(n,s.secretKey);this._addSignature(s.publicKey,x(r))})}addSignature(e,t){this._compile(),this._addSignature(e,t)}_addSignature(e,t){O(t.length===64);const n=this.signatures.findIndex(s=>e.equals(s.publicKey));if(n<0)throw new Error(`unknown signer: ${e.toString()}`);this.signatures[n].signature=a.bufferPolyfill.Buffer.from(t)}verifySignatures(e=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),e)}_getMessageSignednessErrors(e,t){const n={};for(const{signature:s,publicKey:r}of this.signatures)s===null?t&&(n.missing||(n.missing=[])).push(r):$s(s,e,r.toBytes())||(n.invalid||(n.invalid=[])).push(r);return n.invalid||n.missing?n:void 0}serialize(e){const{requireAllSignatures:t,verifySignatures:n}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},e),s=this.serializeMessage();if(n){const r=this._getMessageSignednessErrors(s,t);if(r){let o="Signature verification failed.";throw r.invalid&&(o+=`
|
|
2
2
|
Invalid signature for public key${r.invalid.length===1?"":"(s)"} [\`${r.invalid.map(c=>c.toBase58()).join("`, `")}\`].`),r.missing&&(o+=`
|
|
3
3
|
Missing signature for public key${r.missing.length===1?"":"(s)"} [\`${r.missing.map(c=>c.toBase58()).join("`, `")}\`].`),new Error(o)}}return this._serialize(s)}_serialize(e){const{signatures:t}=this,n=[];ne(n,t.length);const s=n.length+t.length*64+e.length,r=a.bufferPolyfill.Buffer.alloc(s);return O(t.length<256),a.bufferPolyfill.Buffer.from(n).copy(r,0),t.forEach(({signature:o},c)=>{o!==null&&(O(o.length===64,"signature has invalid length"),a.bufferPolyfill.Buffer.from(o).copy(r,n.length+c*64))}),e.copy(r,n.length+t.length*64),O(r.length<=we,`Transaction too large: ${r.length} > ${we}`),r}get keys(){return O(this.instructions.length===1),this.instructions[0].keys.map(e=>e.pubkey)}get programId(){return O(this.instructions.length===1),this.instructions[0].programId}get data(){return O(this.instructions.length===1),this.instructions[0].data}static from(e){let t=[...e];const n=X(t);let s=[];for(let r=0;r<n;r++){const o=Z(t,0,je);s.push(a.bs58.encode(a.bufferPolyfill.Buffer.from(o)))}return N.populate(ae.from(t),s)}static populate(e,t=[]){const n=new N;return n.recentBlockhash=e.recentBlockhash,e.header.numRequiredSignatures>0&&(n.feePayer=e.accountKeys[0]),t.forEach((s,r)=>{const o={signature:s==a.bs58.encode(tr)?null:a.bs58.decode(s),publicKey:e.accountKeys[r]};n.signatures.push(o)}),e.instructions.forEach(s=>{const r=s.accounts.map(o=>{const c=e.accountKeys[o];return{pubkey:c,isSigner:n.signatures.some(u=>u.publicKey.toString()===c.toString())||e.isAccountSigner(o),isWritable:e.isAccountWritable(o)}});n.instructions.push(new q({keys:r,programId:e.accountKeys[s.programIdIndex],data:a.bs58.decode(s.data)}))}),n._message=e,n._json=n.toJSON(),n}}class Ft{constructor(e){this.payerKey=void 0,this.instructions=void 0,this.recentBlockhash=void 0,this.payerKey=e.payerKey,this.instructions=e.instructions,this.recentBlockhash=e.recentBlockhash}static decompile(e,t){const{header:n,compiledInstructions:s,recentBlockhash:r}=e,{numRequiredSignatures:o,numReadonlySignedAccounts:c,numReadonlyUnsignedAccounts:u}=n,d=o-c;O(d>0,"Message header is invalid");const h=e.staticAccountKeys.length-o-u;O(h>=0,"Message header is invalid");const g=e.getAccountKeys(t),S=g.get(0);if(S===void 0)throw new Error("Failed to decompile message because no account keys were found");const f=[];for(const b of s){const m=[];for(const T of b.accountKeyIndexes){const U=g.get(T);if(U===void 0)throw new Error(`Failed to find key for account key index ${T}`);const te=T<o;let ce;te?ce=T<d:T<g.staticAccountKeys.length?ce=T-o<h:ce=T-g.staticAccountKeys.length<g.accountKeysFromLookups.writable.length,m.push({pubkey:U,isSigner:T<n.numRequiredSignatures,isWritable:ce})}const P=g.get(b.programIdIndex);if(P===void 0)throw new Error(`Failed to find program id for program id index ${b.programIdIndex}`);f.push(new q({programId:P,data:x(b.data),keys:m}))}return new Ft({payerKey:S,instructions:f,recentBlockhash:r})}compileToLegacyMessage(){return ae.compile({payerKey:this.payerKey,recentBlockhash:this.recentBlockhash,instructions:this.instructions})}compileToV0Message(e){return Be.compile({payerKey:this.payerKey,recentBlockhash:this.recentBlockhash,instructions:this.instructions,addressLookupTableAccounts:e})}}class Vt{get version(){return this.message.version}constructor(e,t){if(this.signatures=void 0,this.message=void 0,t!==void 0)O(t.length===e.header.numRequiredSignatures,"Expected signatures length to be equal to the number of required signatures"),this.signatures=t;else{const n=[];for(let s=0;s<e.header.numRequiredSignatures;s++)n.push(new Uint8Array(je));this.signatures=n}this.message=e}serialize(){const e=this.message.serialize(),t=Array();ne(t,this.signatures.length);const n=a.struct([a.blob(t.length,"encodedSignaturesLength"),a.seq(Js(),this.signatures.length,"signatures"),a.blob(e.length,"serializedMessage")]),s=new Uint8Array(2048),r=n.encode({encodedSignaturesLength:new Uint8Array(t),signatures:this.signatures,serializedMessage:e},s);return s.slice(0,r)}static deserialize(e){let t=[...e];const n=[],s=X(t);for(let o=0;o<s;o++)n.push(new Uint8Array(Z(t,0,je)));const r=Dt.deserialize(new Uint8Array(t));return new Vt(r,n)}sign(e){const t=this.message.serialize(),n=this.message.staticAccountKeys.slice(0,this.message.header.numRequiredSignatures);for(const s of e){const r=n.findIndex(o=>o.equals(s.publicKey));O(r>=0,`Cannot sign with non signer key ${s.publicKey.toBase58()}`),this.signatures[r]=Ot(t,s.secretKey)}}addSignature(e,t){O(t.byteLength===64,"Signature must be 64 bytes long");const s=this.message.staticAccountKeys.slice(0,this.message.header.numRequiredSignatures).findIndex(r=>r.equals(e));O(s>=0,`Can not add signature; \`${e.toBase58()}\` is not required to sign this transaction`),this.signatures[s]=t}}const nr=160,sr=64,rr=nr/sr,zn=1e3/rr,Q=new y("SysvarC1ock11111111111111111111111111111111"),ir=new y("SysvarEpochSchedu1e111111111111111111111111"),Nn=new y("Sysvar1nstructions1111111111111111111111111"),nt=new y("SysvarRecentB1ockHashes11111111111111111111"),ie=new y("SysvarRent111111111111111111111111111111111"),or=new y("SysvarRewards111111111111111111111111111111"),ar=new y("SysvarS1otHashes111111111111111111111111111"),cr=new y("SysvarS1otHistory11111111111111111111111111"),st=new y("SysvarStakeHistory1111111111111111111111111");async function Et(i,e,t,n){const s=n&&{skipPreflight:n.skipPreflight,preflightCommitment:n.preflightCommitment||n.commitment,maxRetries:n.maxRetries,minContextSlot:n.minContextSlot},r=await i.sendTransaction(e,t,s);let o;if(e.recentBlockhash!=null&&e.lastValidBlockHeight!=null)o=(await i.confirmTransaction({abortSignal:n==null?void 0:n.abortSignal,signature:r,blockhash:e.recentBlockhash,lastValidBlockHeight:e.lastValidBlockHeight},n&&n.commitment)).value;else if(e.minNonceContextSlot!=null&&e.nonceInfo!=null){const{nonceInstruction:c}=e.nonceInfo,u=c.keys[0].pubkey;o=(await i.confirmTransaction({abortSignal:n==null?void 0:n.abortSignal,minContextSlot:e.minNonceContextSlot,nonceAccountPubkey:u,nonceValue:e.nonceInfo.nonce,signature:r},n&&n.commitment)).value}else(n==null?void 0:n.abortSignal)!=null&&console.warn("sendAndConfirmTransaction(): A transaction with a deprecated confirmation strategy was supplied along with an `abortSignal`. Only transactions having `lastValidBlockHeight` or a combination of `nonceInfo` and `minNonceContextSlot` are abortable."),o=(await i.confirmTransaction(r,n&&n.commitment)).value;if(o.err)throw new Error(`Transaction ${r} failed (${JSON.stringify(o)})`);return r}function _e(i){return new Promise(e=>setTimeout(e,i))}function z(i,e){const t=i.layout.span>=0?i.layout.span:xn(i,e),n=a.bufferPolyfill.Buffer.alloc(t),s=Object.assign({instruction:i.index},e);return i.layout.encode(s,n),n}function M(i,e){let t;try{t=i.layout.decode(e)}catch(n){throw new Error("invalid instruction; "+n)}if(t.instruction!==i.index)throw new Error(`invalid instruction; instruction index mismatch ${t.instruction} != ${i.index}`);return t}const Wn=a.nu64("lamportsPerSignature"),On=a.struct([a.u32("version"),a.u32("state"),K("authorizedPubkey"),K("nonce"),a.struct([Wn],"feeCalculator")]),Bt=On.span;class lt{constructor(e){this.authorizedPubkey=void 0,this.nonce=void 0,this.feeCalculator=void 0,this.authorizedPubkey=e.authorizedPubkey,this.nonce=e.nonce,this.feeCalculator=e.feeCalculator}static fromAccountData(e){const t=On.decode(x(e),0);return new lt({authorizedPubkey:new y(t.authorizedPubkey),nonce:new y(t.nonce).toString(),feeCalculator:t.feeCalculator})}}const ur=i=>{const e=i.decode.bind(i),t=i.encode.bind(i);return{decode:e,encode:t}},lr=i=>e=>{const t=a.blob(i,e),{encode:n,decode:s}=ur(t),r=t;return r.decode=(o,c)=>{const u=s(o,c);return a.toBigIntLE_1(a.bufferPolyfill.Buffer.from(u))},r.encode=(o,c,u)=>{const d=a.toBufferLE_1(o,i);return n(d,c,u)},r},We=lr(8);class dr{constructor(){}static decodeInstructionType(e){this.checkProgramId(e.programId);const n=a.u32("instruction").decode(e.data);let s;for(const[r,o]of Object.entries(F))if(o.index==n){s=r;break}if(!s)throw new Error("Instruction type incorrect; not a SystemInstruction");return s}static decodeCreateAccount(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,2);const{lamports:t,space:n,programId:s}=M(F.Create,e.data);return{fromPubkey:e.keys[0].pubkey,newAccountPubkey:e.keys[1].pubkey,lamports:t,space:n,programId:new y(s)}}static decodeTransfer(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,2);const{lamports:t}=M(F.Transfer,e.data);return{fromPubkey:e.keys[0].pubkey,toPubkey:e.keys[1].pubkey,lamports:t}}static decodeTransferWithSeed(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,3);const{lamports:t,seed:n,programId:s}=M(F.TransferWithSeed,e.data);return{fromPubkey:e.keys[0].pubkey,basePubkey:e.keys[1].pubkey,toPubkey:e.keys[2].pubkey,lamports:t,seed:n,programId:new y(s)}}static decodeAllocate(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,1);const{space:t}=M(F.Allocate,e.data);return{accountPubkey:e.keys[0].pubkey,space:t}}static decodeAllocateWithSeed(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,1);const{base:t,seed:n,space:s,programId:r}=M(F.AllocateWithSeed,e.data);return{accountPubkey:e.keys[0].pubkey,basePubkey:new y(t),seed:n,space:s,programId:new y(r)}}static decodeAssign(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,1);const{programId:t}=M(F.Assign,e.data);return{accountPubkey:e.keys[0].pubkey,programId:new y(t)}}static decodeAssignWithSeed(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,1);const{base:t,seed:n,programId:s}=M(F.AssignWithSeed,e.data);return{accountPubkey:e.keys[0].pubkey,basePubkey:new y(t),seed:n,programId:new y(s)}}static decodeCreateWithSeed(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,2);const{base:t,seed:n,lamports:s,space:r,programId:o}=M(F.CreateWithSeed,e.data);return{fromPubkey:e.keys[0].pubkey,newAccountPubkey:e.keys[1].pubkey,basePubkey:new y(t),seed:n,lamports:s,space:r,programId:new y(o)}}static decodeNonceInitialize(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,3);const{authorized:t}=M(F.InitializeNonceAccount,e.data);return{noncePubkey:e.keys[0].pubkey,authorizedPubkey:new y(t)}}static decodeNonceAdvance(e){return this.checkProgramId(e.programId),this.checkKeyLength(e.keys,3),M(F.AdvanceNonceAccount,e.data),{noncePubkey:e.keys[0].pubkey,authorizedPubkey:e.keys[2].pubkey}}static decodeNonceWithdraw(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,5);const{lamports:t}=M(F.WithdrawNonceAccount,e.data);return{noncePubkey:e.keys[0].pubkey,toPubkey:e.keys[1].pubkey,authorizedPubkey:e.keys[4].pubkey,lamports:t}}static decodeNonceAuthorize(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,2);const{authorized:t}=M(F.AuthorizeNonceAccount,e.data);return{noncePubkey:e.keys[0].pubkey,authorizedPubkey:e.keys[1].pubkey,newAuthorizedPubkey:new y(t)}}static checkProgramId(e){if(!e.equals(D.programId))throw new Error("invalid instruction; programId is not SystemProgram")}static checkKeyLength(e,t){if(e.length<t)throw new Error(`invalid instruction; found ${e.length} keys, expected at least ${t}`)}}const F=Object.freeze({Create:{index:0,layout:a.struct([a.u32("instruction"),a.ns64("lamports"),a.ns64("space"),K("programId")])},Assign:{index:1,layout:a.struct([a.u32("instruction"),K("programId")])},Transfer:{index:2,layout:a.struct([a.u32("instruction"),We("lamports")])},CreateWithSeed:{index:3,layout:a.struct([a.u32("instruction"),K("base"),Re("seed"),a.ns64("lamports"),a.ns64("space"),K("programId")])},AdvanceNonceAccount:{index:4,layout:a.struct([a.u32("instruction")])},WithdrawNonceAccount:{index:5,layout:a.struct([a.u32("instruction"),a.ns64("lamports")])},InitializeNonceAccount:{index:6,layout:a.struct([a.u32("instruction"),K("authorized")])},AuthorizeNonceAccount:{index:7,layout:a.struct([a.u32("instruction"),K("authorized")])},Allocate:{index:8,layout:a.struct([a.u32("instruction"),a.ns64("space")])},AllocateWithSeed:{index:9,layout:a.struct([a.u32("instruction"),K("base"),Re("seed"),a.ns64("space"),K("programId")])},AssignWithSeed:{index:10,layout:a.struct([a.u32("instruction"),K("base"),Re("seed"),K("programId")])},TransferWithSeed:{index:11,layout:a.struct([a.u32("instruction"),We("lamports"),Re("seed"),K("programId")])},UpgradeNonceAccount:{index:12,layout:a.struct([a.u32("instruction")])}});class D{constructor(){}static createAccount(e){const t=F.Create,n=z(t,{lamports:e.lamports,space:e.space,programId:x(e.programId.toBuffer())});return new q({keys:[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!0,isWritable:!0}],programId:this.programId,data:n})}static transfer(e){let t,n;if("basePubkey"in e){const s=F.TransferWithSeed;t=z(s,{lamports:BigInt(e.lamports),seed:e.seed,programId:x(e.programId.toBuffer())}),n=[{pubkey:e.fromPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}else{const s=F.Transfer;t=z(s,{lamports:BigInt(e.lamports)}),n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}return new q({keys:n,programId:this.programId,data:t})}static assign(e){let t,n;if("basePubkey"in e){const s=F.AssignWithSeed;t=z(s,{base:x(e.basePubkey.toBuffer()),seed:e.seed,programId:x(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{const s=F.Assign;t=z(s,{programId:x(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new q({keys:n,programId:this.programId,data:t})}static createAccountWithSeed(e){const t=F.CreateWithSeed,n=z(t,{base:x(e.basePubkey.toBuffer()),seed:e.seed,lamports:e.lamports,space:e.space,programId:x(e.programId.toBuffer())});let s=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!1,isWritable:!0}];return e.basePubkey!=e.fromPubkey&&s.push({pubkey:e.basePubkey,isSigner:!0,isWritable:!1}),new q({keys:s,programId:this.programId,data:n})}static createNonceAccount(e){const t=new N;"basePubkey"in e&&"seed"in e?t.add(D.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:Bt,programId:this.programId})):t.add(D.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,lamports:e.lamports,space:Bt,programId:this.programId}));const n={noncePubkey:e.noncePubkey,authorizedPubkey:e.authorizedPubkey};return t.add(this.nonceInitialize(n)),t}static nonceInitialize(e){const t=F.InitializeNonceAccount,n=z(t,{authorized:x(e.authorizedPubkey.toBuffer())}),s={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:nt,isSigner:!1,isWritable:!1},{pubkey:ie,isSigner:!1,isWritable:!1}],programId:this.programId,data:n};return new q(s)}static nonceAdvance(e){const t=F.AdvanceNonceAccount,n=z(t),s={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:nt,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:n};return new q(s)}static nonceWithdraw(e){const t=F.WithdrawNonceAccount,n=z(t,{lamports:e.lamports});return new q({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0},{pubkey:nt,isSigner:!1,isWritable:!1},{pubkey:ie,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:n})}static nonceAuthorize(e){const t=F.AuthorizeNonceAccount,n=z(t,{authorized:x(e.newAuthorizedPubkey.toBuffer())});return new q({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:n})}static allocate(e){let t,n;if("basePubkey"in e){const s=F.AllocateWithSeed;t=z(s,{base:x(e.basePubkey.toBuffer()),seed:e.seed,space:e.space,programId:x(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{const s=F.Allocate;t=z(s,{space:e.space}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new q({keys:n,programId:this.programId,data:t})}}D.programId=new y("11111111111111111111111111111111");const hr=we-300;class Te{constructor(){}static getMinNumSignatures(e){return 2*(Math.ceil(e/Te.chunkSize)+1+1)}static async load(e,t,n,s,r){{const g=await e.getMinimumBalanceForRentExemption(r.length),S=await e.getAccountInfo(n.publicKey,"confirmed");let f=null;if(S!==null){if(S.executable)return console.error("Program load failed, account is already executable"),!1;S.data.length!==r.length&&(f=f||new N,f.add(D.allocate({accountPubkey:n.publicKey,space:r.length}))),S.owner.equals(s)||(f=f||new N,f.add(D.assign({accountPubkey:n.publicKey,programId:s}))),S.lamports<g&&(f=f||new N,f.add(D.transfer({fromPubkey:t.publicKey,toPubkey:n.publicKey,lamports:g-S.lamports})))}else f=new N().add(D.createAccount({fromPubkey:t.publicKey,newAccountPubkey:n.publicKey,lamports:g>0?g:1,space:r.length,programId:s}));f!==null&&await Et(e,f,[t,n],{commitment:"confirmed"})}const o=a.struct([a.u32("instruction"),a.u32("offset"),a.u32("bytesLength"),a.u32("bytesLengthPadding"),a.seq(a.u8("byte"),a.offset(a.u32(),-8),"bytes")]),c=Te.chunkSize;let u=0,d=r,h=[];for(;d.length>0;){const g=d.slice(0,c),S=a.bufferPolyfill.Buffer.alloc(c+16);o.encode({instruction:0,offset:u,bytes:g,bytesLength:0,bytesLengthPadding:0},S);const f=new N().add({keys:[{pubkey:n.publicKey,isSigner:!0,isWritable:!0}],programId:s,data:S});h.push(Et(e,f,[t,n],{commitment:"confirmed"})),e._rpcEndpoint.includes("solana.com")&&await _e(1e3/4),u+=c,d=d.slice(c)}await Promise.all(h);{const g=a.struct([a.u32("instruction")]),S=a.bufferPolyfill.Buffer.alloc(g.span);g.encode({instruction:1},S);const f=new N().add({keys:[{pubkey:n.publicKey,isSigner:!0,isWritable:!0},{pubkey:ie,isSigner:!1,isWritable:!1}],programId:s,data:S}),b="processed",m=await e.sendTransaction(f,[t,n],{preflightCommitment:b}),{context:P,value:T}=await e.confirmTransaction({signature:m,lastValidBlockHeight:f.lastValidBlockHeight,blockhash:f.recentBlockhash},b);if(T.err)throw new Error(`Transaction ${m} failed (${JSON.stringify(T)})`);for(;;){try{if(await e.getSlot({commitment:b})>P.slot)break}catch{}await new Promise(U=>setTimeout(U,Math.round(zn/2)))}}return!0}}Te.chunkSize=hr;const fr=new y("BPFLoader2111111111111111111111111111111111");class gr{static getMinNumSignatures(e){return Te.getMinNumSignatures(e)}static load(e,t,n,s,r){return Te.load(e,t,n,r,s)}}function yr(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var pr=Object.prototype.toString,mr=Object.keys||function(i){var e=[];for(var t in i)e.push(t);return e};function $e(i,e){var t,n,s,r,o,c,u;if(i===!0)return"true";if(i===!1)return"false";switch(typeof i){case"object":if(i===null)return null;if(i.toJSON&&typeof i.toJSON=="function")return $e(i.toJSON(),e);if(u=pr.call(i),u==="[object Array]"){for(s="[",n=i.length-1,t=0;t<n;t++)s+=$e(i[t],!0)+",";return n>-1&&(s+=$e(i[t],!0)),s+"]"}else if(u==="[object Object]"){for(r=mr(i).sort(),n=r.length,s="",t=0;t<n;)o=r[t],c=$e(i[o],!1),c!==void 0&&(s&&(s+=","),s+=JSON.stringify(o)+":"+c),t++;return"{"+s+"}"}else return JSON.stringify(i);case"function":case"undefined":return e?null:void 0;case"string":return JSON.stringify(i);default:return isFinite(i)?i:null}}var br=function(i){var e=$e(i,!1);if(e!==void 0)return""+e},dn=yr(br);const Fe=32;function It(i){let e=0;for(;i>1;)i/=2,e++;return e}function kr(i){return i===0?1:(i--,i|=i>>1,i|=i>>2,i|=i>>4,i|=i>>8,i|=i>>16,i|=i>>32,i+1)}class Mn{constructor(e,t,n,s,r){this.slotsPerEpoch=void 0,this.leaderScheduleSlotOffset=void 0,this.warmup=void 0,this.firstNormalEpoch=void 0,this.firstNormalSlot=void 0,this.slotsPerEpoch=e,this.leaderScheduleSlotOffset=t,this.warmup=n,this.firstNormalEpoch=s,this.firstNormalSlot=r}getEpoch(e){return this.getEpochAndSlotIndex(e)[0]}getEpochAndSlotIndex(e){if(e<this.firstNormalSlot){const t=It(kr(e+Fe+1))-It(Fe)-1,n=this.getSlotsInEpoch(t),s=e-(n-Fe);return[t,s]}else{const t=e-this.firstNormalSlot,n=Math.floor(t/this.slotsPerEpoch),s=this.firstNormalEpoch+n,r=t%this.slotsPerEpoch;return[s,r]}}getFirstSlotInEpoch(e){return e<=this.firstNormalEpoch?(Math.pow(2,e)-1)*Fe:(e-this.firstNormalEpoch)*this.slotsPerEpoch+this.firstNormalSlot}getLastSlotInEpoch(e){return this.getFirstSlotInEpoch(e)+this.getSlotsInEpoch(e)-1}getSlotsInEpoch(e){return e<this.firstNormalEpoch?Math.pow(2,e+It(Fe)):this.slotsPerEpoch}}class Tt extends Error{constructor(e,t){super(e),this.logs=void 0,this.logs=t}}const Sr={JSON_RPC_SERVER_ERROR_BLOCK_CLEANED_UP:-32001,JSON_RPC_SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE:-32002,JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE:-32003,JSON_RPC_SERVER_ERROR_BLOCK_NOT_AVAILABLE:-32004,JSON_RPC_SERVER_ERROR_NODE_UNHEALTHY:-32005,JSON_RPC_SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE:-32006,JSON_RPC_SERVER_ERROR_SLOT_SKIPPED:-32007,JSON_RPC_SERVER_ERROR_NO_SNAPSHOT:-32008,JSON_RPC_SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED:-32009,JSON_RPC_SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX:-32010,JSON_RPC_SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE:-32011,JSON_RPC_SCAN_ERROR:-32012,JSON_RPC_SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH:-32013,JSON_RPC_SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET:-32014,JSON_RPC_SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION:-32015,JSON_RPC_SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED:-32016};class R extends Error{constructor({code:e,message:t,data:n},s){super(s!=null?`${s}: ${t}`:t),this.code=void 0,this.data=void 0,this.code=e,this.data=n,this.name="SolanaJSONRPCError"}}var wr=globalThis.fetch;class Ir extends a._default{constructor(e,t,n){const s=r=>{const o=a._default$1(r,{autoconnect:!0,max_reconnects:5,reconnect:!0,reconnect_interval:1e3,...t});return"socket"in o?this.underlyingSocket=o.socket:this.underlyingSocket=o,o};super(s,e,t,n),this.underlyingSocket=void 0}call(...e){var n;const t=(n=this.underlyingSocket)==null?void 0:n.readyState;return t===1?super.call(...e):Promise.reject(new Error("Tried to call a JSON-RPC method `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+t+")"))}notify(...e){var n;const t=(n=this.underlyingSocket)==null?void 0:n.readyState;return t===1?super.notify(...e):Promise.reject(new Error("Tried to send a JSON-RPC notification `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+t+")"))}}function Ar(i,e){let t;try{t=i.layout.decode(e)}catch(n){throw new Error("invalid instruction; "+n)}if(t.typeIndex!==i.index)throw new Error(`invalid account data; account type mismatch ${t.typeIndex} != ${i.index}`);return t}const hn=56;class vt{constructor(e){this.key=void 0,this.state=void 0,this.key=e.key,this.state=e.state}isActive(){const e=BigInt("0xffffffffffffffff");return this.state.deactivationSlot===e}static deserialize(e){const t=Ar(_r,e),n=e.length-hn;O(n>=0,"lookup table is invalid"),O(n%32===0,"lookup table is invalid");const s=n/32,{addresses:r}=a.struct([a.seq(K(),s,"addresses")]).decode(e.slice(hn));return{deactivationSlot:t.deactivationSlot,lastExtendedSlot:t.lastExtendedSlot,lastExtendedSlotStartIndex:t.lastExtendedStartIndex,authority:t.authority.length!==0?new y(t.authority[0]):void 0,addresses:r.map(o=>new y(o))}}}const _r={index:1,layout:a.struct([a.u32("typeIndex"),We("deactivationSlot"),a.nu64("lastExtendedSlot"),a.u8("lastExtendedStartIndex"),a.u8(),a.seq(K(),a.offset(a.u8(),-1),"authority")])},Pr=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;function Rr(i){const e=i.match(Pr);if(e==null)throw TypeError(`Failed to validate endpoint URL \`${i}\``);const[t,n,s,r]=e,o=i.startsWith("https:")?"wss:":"ws:",c=s==null?null:parseInt(s.slice(1),10),u=c==null?"":`:${c+1}`;return`${o}//${n}${u}${r}`}const Y=Qe(Nt(y),k(),i=>new y(i)),Un=Wt([k(),H("base64")]),$t=Qe(Nt(a.bufferPolyfill.Buffer),Un,i=>a.bufferPolyfill.Buffer.from(i[0],"base64")),qn=30*1e3;function Er(i){if(/^https?:/.test(i)===!1)throw new TypeError("Endpoint URL must start with `http:` or `https:`.");return i}function V(i){let e,t;if(typeof i=="string")e=i;else if(i){const{commitment:n,...s}=i;e=n,t=s}return{commitment:e,config:t}}function Dn(i){return ee([p({jsonrpc:H("2.0"),id:k(),result:i}),p({jsonrpc:H("2.0"),id:k(),error:p({code:Ze(),message:k(),data:B(Ds())})})])}const Br=Dn(Ze());function C(i){return Qe(Dn(i),Br,e=>"error"in e?e:{...e,result:w(e.result,i)})}function G(i){return C(p({context:p({slot:l()}),value:i}))}function dt(i){return p({context:p({slot:l()}),value:i})}function At(i,e){return i===0?new Be({header:e.header,staticAccountKeys:e.accountKeys.map(t=>new y(t)),recentBlockhash:e.recentBlockhash,compiledInstructions:e.instructions.map(t=>({programIdIndex:t.programIdIndex,accountKeyIndexes:t.accounts,data:a.bs58.decode(t.data)})),addressTableLookups:e.addressTableLookups}):new ae(e)}const Tr=p({foundation:l(),foundationTerm:l(),initial:l(),taper:l(),terminal:l()}),vr=C(A(I(p({epoch:l(),effectiveSlot:l(),amount:l(),postBalance:l(),commission:B(I(l()))})))),Lr=A(p({slot:l(),prioritizationFee:l()})),Cr=p({total:l(),validator:l(),foundation:l(),epoch:l()}),xr=p({epoch:l(),slotIndex:l(),slotsInEpoch:l(),absoluteSlot:l(),blockHeight:B(l()),transactionCount:B(l())}),Kr=p({slotsPerEpoch:l(),leaderScheduleSlotOffset:l(),warmup:fe(),firstNormalEpoch:l(),firstNormalSlot:l()}),zr=Tn(k(),A(l())),Ce=I(ee([p({}),k()])),Nr=p({err:Ce}),Wr=H("receivedSignature"),Or=p({"solana-core":k(),"feature-set":B(l())}),fn=G(p({err:I(ee([p({}),k()])),logs:I(A(k())),accounts:B(I(A(I(p({executable:fe(),owner:k(),lamports:l(),data:A(k()),rentEpoch:B(l())}))))),unitsConsumed:B(l()),returnData:B(I(p({programId:k(),data:Wt([k(),H("base64")])})))})),Mr=G(p({byIdentity:Tn(k(),A(l())),range:p({firstSlot:l(),lastSlot:l()})}));function Ur(i,e,t,n,s,r){const o=t||wr;let c;r!=null&&console.warn("You have supplied an `httpAgent` when creating a `Connection` in a browser environment.It has been ignored; `httpAgent` is only used in Node environments.");let u;return n&&(u=async(h,g)=>{const S=await new Promise((f,b)=>{try{n(h,g,(m,P)=>f([m,P]))}catch(m){b(m)}});return await o(...S)}),new a.RpcClient(async(h,g)=>{const S={method:"POST",body:h,agent:c,headers:Object.assign({"Content-Type":"application/json"},e||{},qi)};try{let f=5,b,m=500;for(;u?b=await u(i,S):b=await o(i,S),!(b.status!==429||s===!0||(f-=1,f===0));)console.error(`Server responded with ${b.status} ${b.statusText}. Retrying after ${m}ms delay...`),await _e(m),m*=2;const P=await b.text();b.ok?g(null,P):g(new Error(`${b.status} ${b.statusText}: ${P}`))}catch(f){f instanceof Error&&g(f)}},{})}function qr(i){return(e,t)=>new Promise((n,s)=>{i.request(e,t,(r,o)=>{if(r){s(r);return}n(o)})})}function Dr(i){return e=>new Promise((t,n)=>{e.length===0&&t([]);const s=e.map(r=>i.request(r.methodName,r.args));i.request(s,(r,o)=>{if(r){n(r);return}t(o)})})}const Fr=C(Tr),Vr=C(Cr),$r=C(Lr),Hr=C(xr),Gr=C(Kr),jr=C(zr),Yr=C(l()),Jr=G(p({total:l(),circulating:l(),nonCirculating:l(),nonCirculatingAccounts:A(Y)})),Lt=p({amount:k(),uiAmount:I(l()),decimals:l(),uiAmountString:B(k())}),Xr=G(A(p({address:Y,amount:k(),uiAmount:I(l()),decimals:l(),uiAmountString:B(k())}))),Zr=G(A(p({pubkey:Y,account:p({executable:fe(),owner:Y,lamports:l(),data:$t,rentEpoch:l()})}))),Ct=p({program:k(),parsed:Ze(),space:l()}),Qr=G(A(p({pubkey:Y,account:p({executable:fe(),owner:Y,lamports:l(),data:Ct,rentEpoch:l()})}))),ei=G(A(p({lamports:l(),address:Y}))),Je=p({executable:fe(),owner:Y,lamports:l(),data:$t,rentEpoch:l()}),ti=p({pubkey:Y,account:Je}),ni=Qe(ee([Nt(a.bufferPolyfill.Buffer),Ct]),ee([Un,Ct]),i=>Array.isArray(i)?w(i,$t):i),xt=p({executable:fe(),owner:Y,lamports:l(),data:ni,rentEpoch:l()}),si=p({pubkey:Y,account:xt}),ri=p({state:ee([H("active"),H("inactive"),H("activating"),H("deactivating")]),active:l(),inactive:l()}),ii=C(A(p({signature:k(),slot:l(),err:Ce,memo:I(k()),blockTime:B(I(l()))}))),oi=C(A(p({signature:k(),slot:l(),err:Ce,memo:I(k()),blockTime:B(I(l()))}))),ai=p({subscription:l(),result:dt(Je)}),ci=p({pubkey:Y,account:Je}),ui=p({subscription:l(),result:dt(ci)}),li=p({parent:l(),slot:l(),root:l()}),di=p({subscription:l(),result:li}),hi=ee([p({type:ee([H("firstShredReceived"),H("completed"),H("optimisticConfirmation"),H("root")]),slot:l(),timestamp:l()}),p({type:H("createdBank"),parent:l(),slot:l(),timestamp:l()}),p({type:H("frozen"),slot:l(),timestamp:l(),stats:p({numTransactionEntries:l(),numSuccessfulTransactions:l(),numFailedTransactions:l(),maxTransactionsPerEntry:l()})}),p({type:H("dead"),slot:l(),timestamp:l(),err:k()})]),fi=p({subscription:l(),result:hi}),gi=p({subscription:l(),result:dt(ee([Nr,Wr]))}),yi=p({subscription:l(),result:l()}),pi=p({pubkey:k(),gossip:I(k()),tpu:I(k()),rpc:I(k()),version:I(k())}),gn=p({votePubkey:k(),nodePubkey:k(),activatedStake:l(),epochVoteAccount:fe(),epochCredits:A(Wt([l(),l(),l()])),commission:l(),lastVote:l(),rootSlot:I(l())}),mi=C(p({current:A(gn),delinquent:A(gn)})),bi=ee([H("processed"),H("confirmed"),H("finalized")]),ki=p({slot:l(),confirmations:I(l()),err:Ce,confirmationStatus:B(bi)}),Si=G(A(I(ki))),wi=C(l()),Fn=p({accountKey:Y,writableIndexes:A(l()),readonlyIndexes:A(l())}),Ht=p({signatures:A(k()),message:p({accountKeys:A(k()),header:p({numRequiredSignatures:l(),numReadonlySignedAccounts:l(),numReadonlyUnsignedAccounts:l()}),instructions:A(p({accounts:A(l()),data:k(),programIdIndex:l()})),recentBlockhash:k(),addressTableLookups:B(A(Fn))})}),Vn=p({pubkey:Y,signer:fe(),writable:fe(),source:B(ee([H("transaction"),H("lookupTable")]))}),$n=p({accountKeys:A(Vn),signatures:A(k())}),Hn=p({parsed:Ze(),program:k(),programId:Y}),Gn=p({accounts:A(Y),data:k(),programId:Y}),Ii=ee([Gn,Hn]),Ai=ee([p({parsed:Ze(),program:k(),programId:k()}),p({accounts:A(k()),data:k(),programId:k()})]),jn=Qe(Ii,Ai,i=>"accounts"in i?w(i,Gn):w(i,Hn)),Yn=p({signatures:A(k()),message:p({accountKeys:A(Vn),instructions:A(jn),recentBlockhash:k(),addressTableLookups:B(I(A(Fn)))})}),it=p({accountIndex:l(),mint:k(),owner:B(k()),uiTokenAmount:Lt}),Jn=p({writable:A(Y),readonly:A(Y)}),ht=p({err:Ce,fee:l(),innerInstructions:B(I(A(p({index:l(),instructions:A(p({accounts:A(l()),data:k(),programIdIndex:l()}))})))),preBalances:A(l()),postBalances:A(l()),logMessages:B(I(A(k()))),preTokenBalances:B(I(A(it))),postTokenBalances:B(I(A(it))),loadedAddresses:B(Jn),computeUnitsConsumed:B(l())}),Gt=p({err:Ce,fee:l(),innerInstructions:B(I(A(p({index:l(),instructions:A(jn)})))),preBalances:A(l()),postBalances:A(l()),logMessages:B(I(A(k()))),preTokenBalances:B(I(A(it))),postTokenBalances:B(I(A(it))),loadedAddresses:B(Jn),computeUnitsConsumed:B(l())}),Ue=ee([H(0),H("legacy")]),xe=p({pubkey:k(),lamports:l(),postBalance:I(l()),rewardType:I(k()),commission:B(I(l()))}),_i=C(I(p({blockhash:k(),previousBlockhash:k(),parentSlot:l(),transactions:A(p({transaction:Ht,meta:I(ht),version:B(Ue)})),rewards:B(A(xe)),blockTime:I(l()),blockHeight:I(l())}))),Pi=C(I(p({blockhash:k(),previousBlockhash:k(),parentSlot:l(),rewards:B(A(xe)),blockTime:I(l()),blockHeight:I(l())}))),Ri=C(I(p({blockhash:k(),previousBlockhash:k(),parentSlot:l(),transactions:A(p({transaction:$n,meta:I(ht),version:B(Ue)})),rewards:B(A(xe)),blockTime:I(l()),blockHeight:I(l())}))),Ei=C(I(p({blockhash:k(),previousBlockhash:k(),parentSlot:l(),transactions:A(p({transaction:Yn,meta:I(Gt),version:B(Ue)})),rewards:B(A(xe)),blockTime:I(l()),blockHeight:I(l())}))),Bi=C(I(p({blockhash:k(),previousBlockhash:k(),parentSlot:l(),transactions:A(p({transaction:$n,meta:I(Gt),version:B(Ue)})),rewards:B(A(xe)),blockTime:I(l()),blockHeight:I(l())}))),Ti=C(I(p({blockhash:k(),previousBlockhash:k(),parentSlot:l(),rewards:B(A(xe)),blockTime:I(l()),blockHeight:I(l())}))),vi=C(I(p({blockhash:k(),previousBlockhash:k(),parentSlot:l(),transactions:A(p({transaction:Ht,meta:I(ht)})),rewards:B(A(xe)),blockTime:I(l())}))),yn=C(I(p({blockhash:k(),previousBlockhash:k(),parentSlot:l(),signatures:A(k()),blockTime:I(l())}))),_t=C(I(p({slot:l(),meta:I(ht),blockTime:B(I(l())),transaction:Ht,version:B(Ue)}))),tt=C(I(p({slot:l(),transaction:Yn,meta:I(Gt),blockTime:B(I(l())),version:B(Ue)}))),Li=G(p({blockhash:k(),feeCalculator:p({lamportsPerSignature:l()})})),Ci=G(p({blockhash:k(),lastValidBlockHeight:l()})),xi=G(fe()),Ki=p({slot:l(),numTransactions:l(),numSlots:l(),samplePeriodSecs:l()}),zi=C(A(Ki)),Ni=G(I(p({feeCalculator:p({lamportsPerSignature:l()})}))),Wi=C(k()),Oi=C(k()),Mi=p({err:Ce,logs:A(k()),signature:k()}),Ui=p({result:dt(Mi),subscription:l()}),qi={"solana-client":"js/0.0.0-development"};class Di{constructor(e,t){this._commitment=void 0,this._confirmTransactionInitialTimeout=void 0,this._rpcEndpoint=void 0,this._rpcWsEndpoint=void 0,this._rpcClient=void 0,this._rpcRequest=void 0,this._rpcBatchRequest=void 0,this._rpcWebSocket=void 0,this._rpcWebSocketConnected=!1,this._rpcWebSocketHeartbeat=null,this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketGeneration=0,this._disableBlockhashCaching=!1,this._pollingBlockhash=!1,this._blockhashInfo={latestBlockhash:null,lastFetch:0,transactionSignatures:[],simulatedSignatures:[]},this._nextClientSubscriptionId=0,this._subscriptionDisposeFunctionsByClientSubscriptionId={},this._subscriptionHashByClientSubscriptionId={},this._subscriptionStateChangeCallbacksByHash={},this._subscriptionCallbacksByServerSubscriptionId={},this._subscriptionsByHash={},this._subscriptionsAutoDisposedByRpc=new Set,this.getBlockHeight=(()=>{const d={};return async h=>{const{commitment:g,config:S}=V(h),f=this._buildArgs([],g,void 0,S),b=dn(f);return d[b]=d[b]??(async()=>{try{const m=await this._rpcRequest("getBlockHeight",f),P=w(m,C(l()));if("error"in P)throw new R(P.error,"failed to get block height information");return P.result}finally{delete d[b]}})(),await d[b]}})();let n,s,r,o,c,u;t&&typeof t=="string"?this._commitment=t:t&&(this._commitment=t.commitment,this._confirmTransactionInitialTimeout=t.confirmTransactionInitialTimeout,n=t.wsEndpoint,s=t.httpHeaders,r=t.fetch,o=t.fetchMiddleware,c=t.disableRetryOnRateLimit,u=t.httpAgent),this._rpcEndpoint=Er(e),this._rpcWsEndpoint=n||Rr(e),this._rpcClient=Ur(e,s,r,o,c,u),this._rpcRequest=qr(this._rpcClient),this._rpcBatchRequest=Dr(this._rpcClient),this._rpcWebSocket=new Ir(this._rpcWsEndpoint,{autoconnect:!1,max_reconnects:1/0}),this._rpcWebSocket.on("open",this._wsOnOpen.bind(this)),this._rpcWebSocket.on("error",this._wsOnError.bind(this)),this._rpcWebSocket.on("close",this._wsOnClose.bind(this)),this._rpcWebSocket.on("accountNotification",this._wsOnAccountNotification.bind(this)),this._rpcWebSocket.on("programNotification",this._wsOnProgramAccountNotification.bind(this)),this._rpcWebSocket.on("slotNotification",this._wsOnSlotNotification.bind(this)),this._rpcWebSocket.on("slotsUpdatesNotification",this._wsOnSlotUpdatesNotification.bind(this)),this._rpcWebSocket.on("signatureNotification",this._wsOnSignatureNotification.bind(this)),this._rpcWebSocket.on("rootNotification",this._wsOnRootNotification.bind(this)),this._rpcWebSocket.on("logsNotification",this._wsOnLogsNotification.bind(this))}get commitment(){return this._commitment}get rpcEndpoint(){return this._rpcEndpoint}async getBalanceAndContext(e,t){const{commitment:n,config:s}=V(t),r=this._buildArgs([e.toBase58()],n,void 0,s),o=await this._rpcRequest("getBalance",r),c=w(o,G(l()));if("error"in c)throw new R(c.error,`failed to get balance for ${e.toBase58()}`);return c.result}async getBalance(e,t){return await this.getBalanceAndContext(e,t).then(n=>n.value).catch(n=>{throw new Error("failed to get balance of account "+e.toBase58()+": "+n)})}async getBlockTime(e){const t=await this._rpcRequest("getBlockTime",[e]),n=w(t,C(I(l())));if("error"in n)throw new R(n.error,`failed to get block time for slot ${e}`);return n.result}async getMinimumLedgerSlot(){const e=await this._rpcRequest("minimumLedgerSlot",[]),t=w(e,C(l()));if("error"in t)throw new R(t.error,"failed to get minimum ledger slot");return t.result}async getFirstAvailableBlock(){const e=await this._rpcRequest("getFirstAvailableBlock",[]),t=w(e,Yr);if("error"in t)throw new R(t.error,"failed to get first available block");return t.result}async getSupply(e){let t={};typeof e=="string"?t={commitment:e}:e?t={...e,commitment:e&&e.commitment||this.commitment}:t={commitment:this.commitment};const n=await this._rpcRequest("getSupply",[t]),s=w(n,Jr);if("error"in s)throw new R(s.error,"failed to get supply");return s.result}async getTokenSupply(e,t){const n=this._buildArgs([e.toBase58()],t),s=await this._rpcRequest("getTokenSupply",n),r=w(s,G(Lt));if("error"in r)throw new R(r.error,"failed to get token supply");return r.result}async getTokenAccountBalance(e,t){const n=this._buildArgs([e.toBase58()],t),s=await this._rpcRequest("getTokenAccountBalance",n),r=w(s,G(Lt));if("error"in r)throw new R(r.error,"failed to get token account balance");return r.result}async getTokenAccountsByOwner(e,t,n){const{commitment:s,config:r}=V(n);let o=[e.toBase58()];"mint"in t?o.push({mint:t.mint.toBase58()}):o.push({programId:t.programId.toBase58()});const c=this._buildArgs(o,s,"base64",r),u=await this._rpcRequest("getTokenAccountsByOwner",c),d=w(u,Zr);if("error"in d)throw new R(d.error,`failed to get token accounts owned by account ${e.toBase58()}`);return d.result}async getParsedTokenAccountsByOwner(e,t,n){let s=[e.toBase58()];"mint"in t?s.push({mint:t.mint.toBase58()}):s.push({programId:t.programId.toBase58()});const r=this._buildArgs(s,n,"jsonParsed"),o=await this._rpcRequest("getTokenAccountsByOwner",r),c=w(o,Qr);if("error"in c)throw new R(c.error,`failed to get token accounts owned by account ${e.toBase58()}`);return c.result}async getLargestAccounts(e){const t={...e,commitment:e&&e.commitment||this.commitment},n=t.filter||t.commitment?[t]:[],s=await this._rpcRequest("getLargestAccounts",n),r=w(s,ei);if("error"in r)throw new R(r.error,"failed to get largest accounts");return r.result}async getTokenLargestAccounts(e,t){const n=this._buildArgs([e.toBase58()],t),s=await this._rpcRequest("getTokenLargestAccounts",n),r=w(s,Xr);if("error"in r)throw new R(r.error,"failed to get token largest accounts");return r.result}async getAccountInfoAndContext(e,t){const{commitment:n,config:s}=V(t),r=this._buildArgs([e.toBase58()],n,"base64",s),o=await this._rpcRequest("getAccountInfo",r),c=w(o,G(I(Je)));if("error"in c)throw new R(c.error,`failed to get info about account ${e.toBase58()}`);return c.result}async getParsedAccountInfo(e,t){const{commitment:n,config:s}=V(t),r=this._buildArgs([e.toBase58()],n,"jsonParsed",s),o=await this._rpcRequest("getAccountInfo",r),c=w(o,G(I(xt)));if("error"in c)throw new R(c.error,`failed to get info about account ${e.toBase58()}`);return c.result}async getAccountInfo(e,t){try{return(await this.getAccountInfoAndContext(e,t)).value}catch(n){throw new Error("failed to get info about account "+e.toBase58()+": "+n)}}async getMultipleParsedAccounts(e,t){const{commitment:n,config:s}=V(t),r=e.map(d=>d.toBase58()),o=this._buildArgs([r],n,"jsonParsed",s),c=await this._rpcRequest("getMultipleAccounts",o),u=w(c,G(A(I(xt))));if("error"in u)throw new R(u.error,`failed to get info for accounts ${r}`);return u.result}async getMultipleAccountsInfoAndContext(e,t){const{commitment:n,config:s}=V(t),r=e.map(d=>d.toBase58()),o=this._buildArgs([r],n,"base64",s),c=await this._rpcRequest("getMultipleAccounts",o),u=w(c,G(A(I(Je))));if("error"in u)throw new R(u.error,`failed to get info for accounts ${r}`);return u.result}async getMultipleAccountsInfo(e,t){return(await this.getMultipleAccountsInfoAndContext(e,t)).value}async getStakeActivation(e,t,n){const{commitment:s,config:r}=V(t),o=this._buildArgs([e.toBase58()],s,void 0,{...r,epoch:n??(r==null?void 0:r.epoch)}),c=await this._rpcRequest("getStakeActivation",o),u=w(c,C(ri));if("error"in u)throw new R(u.error,`failed to get Stake Activation ${e.toBase58()}`);return u.result}async getProgramAccounts(e,t){const{commitment:n,config:s}=V(t),{encoding:r,...o}=s||{},c=this._buildArgs([e.toBase58()],n,r||"base64",o),u=await this._rpcRequest("getProgramAccounts",c),d=A(ti),h=o.withContext===!0?w(u,G(d)):w(u,C(d));if("error"in h)throw new R(h.error,`failed to get accounts owned by program ${e.toBase58()}`);return h.result}async getParsedProgramAccounts(e,t){const{commitment:n,config:s}=V(t),r=this._buildArgs([e.toBase58()],n,"jsonParsed",s),o=await this._rpcRequest("getProgramAccounts",r),c=w(o,C(A(si)));if("error"in c)throw new R(c.error,`failed to get accounts owned by program ${e.toBase58()}`);return c.result}async confirmTransaction(e,t){var r;let n;if(typeof e=="string")n=e;else{const o=e;if((r=o.abortSignal)!=null&&r.aborted)return Promise.reject(o.abortSignal.reason);n=o.signature}let s;try{s=a.bs58.decode(n)}catch{throw new Error("signature must be base58 encoded: "+n)}return O(s.length===64,"signature has invalid length"),typeof e=="string"?await this.confirmTransactionUsingLegacyTimeoutStrategy({commitment:t||this.commitment,signature:n}):"lastValidBlockHeight"in e?await this.confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:t||this.commitment,strategy:e}):await this.confirmTransactionUsingDurableNonceStrategy({commitment:t||this.commitment,strategy:e})}getCancellationPromise(e){return new Promise((t,n)=>{e!=null&&(e.aborted?n(e.reason):e.addEventListener("abort",()=>{n(e.reason)}))})}getTransactionConfirmationPromise({commitment:e,signature:t}){let n,s,r=!1;const o=new Promise((u,d)=>{try{n=this.onSignature(t,(g,S)=>{n=void 0;const f={context:S,value:g};u({__type:be.PROCESSED,response:f})},e);const h=new Promise(g=>{n==null?g():s=this._onSubscriptionStateChange(n,S=>{S==="subscribed"&&g()})});(async()=>{if(await h,r)return;const g=await this.getSignatureStatus(t);if(r||g==null)return;const{context:S,value:f}=g;if(f!=null)if(f!=null&&f.err)d(f.err);else{switch(e){case"confirmed":case"single":case"singleGossip":{if(f.confirmationStatus==="processed")return;break}case"finalized":case"max":case"root":{if(f.confirmationStatus==="processed"||f.confirmationStatus==="confirmed")return;break}case"processed":case"recent":}r=!0,u({__type:be.PROCESSED,response:{context:S,value:f}})}})()}catch(h){d(h)}});return{abortConfirmation:()=>{s&&(s(),s=void 0),n!=null&&(this.removeSignatureListener(n),n=void 0)},confirmationPromise:o}}async confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:e,strategy:{abortSignal:t,lastValidBlockHeight:n,signature:s}}){let r=!1;const o=new Promise(g=>{const S=async()=>{try{return await this.getBlockHeight(e)}catch{return-1}};(async()=>{let f=await S();if(!r){for(;f<=n;)if(await _e(1e3),r||(f=await S(),r))return;g({__type:be.BLOCKHEIGHT_EXCEEDED})}})()}),{abortConfirmation:c,confirmationPromise:u}=this.getTransactionConfirmationPromise({commitment:e,signature:s}),d=this.getCancellationPromise(t);let h;try{const g=await Promise.race([d,u,o]);if(g.__type===be.PROCESSED)h=g.response;else throw new Ut(s)}finally{r=!0,c()}return h}async confirmTransactionUsingDurableNonceStrategy({commitment:e,strategy:{abortSignal:t,minContextSlot:n,nonceAccountPubkey:s,nonceValue:r,signature:o}}){let c=!1;const u=new Promise(f=>{let b=r,m=null;const P=async()=>{try{const{context:T,value:U}=await this.getNonceAndContext(s,{commitment:e,minContextSlot:n});return m=T.slot,U==null?void 0:U.nonce}catch{return b}};(async()=>{if(b=await P(),!c)for(;;){if(r!==b){f({__type:be.NONCE_INVALID,slotInWhichNonceDidAdvance:m});return}if(await _e(2e3),c||(b=await P(),c))return}})()}),{abortConfirmation:d,confirmationPromise:h}=this.getTransactionConfirmationPromise({commitment:e,signature:o}),g=this.getCancellationPromise(t);let S;try{const f=await Promise.race([g,h,u]);if(f.__type===be.PROCESSED)S=f.response;else{let b;for(;;){const m=await this.getSignatureStatus(o);if(m==null)break;if(m.context.slot<(f.slotInWhichNonceDidAdvance??n)){await _e(400);continue}b=m;break}if(b!=null&&b.value){const m=e||"finalized",{confirmationStatus:P}=b.value;switch(m){case"processed":case"recent":if(P!=="processed"&&P!=="confirmed"&&P!=="finalized")throw new ze(o);break;case"confirmed":case"single":case"singleGossip":if(P!=="confirmed"&&P!=="finalized")throw new ze(o);break;case"finalized":case"max":case"root":if(P!=="finalized")throw new ze(o);break;default:}S={context:b.context,value:{err:b.value.err}}}else throw new ze(o)}}finally{c=!0,d()}return S}async confirmTransactionUsingLegacyTimeoutStrategy({commitment:e,signature:t}){let n;const s=new Promise(u=>{let d=this._confirmTransactionInitialTimeout||6e4;switch(e){case"processed":case"recent":case"single":case"confirmed":case"singleGossip":{d=this._confirmTransactionInitialTimeout||3e4;break}}n=setTimeout(()=>u({__type:be.TIMED_OUT,timeoutMs:d}),d)}),{abortConfirmation:r,confirmationPromise:o}=this.getTransactionConfirmationPromise({commitment:e,signature:t});let c;try{const u=await Promise.race([o,s]);if(u.__type===be.PROCESSED)c=u.response;else throw new qt(t,u.timeoutMs/1e3)}finally{clearTimeout(n),r()}return c}async getClusterNodes(){const e=await this._rpcRequest("getClusterNodes",[]),t=w(e,C(A(pi)));if("error"in t)throw new R(t.error,"failed to get cluster nodes");return t.result}async getVoteAccounts(e){const t=this._buildArgs([],e),n=await this._rpcRequest("getVoteAccounts",t),s=w(n,mi);if("error"in s)throw new R(s.error,"failed to get vote accounts");return s.result}async getSlot(e){const{commitment:t,config:n}=V(e),s=this._buildArgs([],t,void 0,n),r=await this._rpcRequest("getSlot",s),o=w(r,C(l()));if("error"in o)throw new R(o.error,"failed to get slot");return o.result}async getSlotLeader(e){const{commitment:t,config:n}=V(e),s=this._buildArgs([],t,void 0,n),r=await this._rpcRequest("getSlotLeader",s),o=w(r,C(k()));if("error"in o)throw new R(o.error,"failed to get slot leader");return o.result}async getSlotLeaders(e,t){const n=[e,t],s=await this._rpcRequest("getSlotLeaders",n),r=w(s,C(A(Y)));if("error"in r)throw new R(r.error,"failed to get slot leaders");return r.result}async getSignatureStatus(e,t){const{context:n,value:s}=await this.getSignatureStatuses([e],t);O(s.length===1);const r=s[0];return{context:n,value:r}}async getSignatureStatuses(e,t){const n=[e];t&&n.push(t);const s=await this._rpcRequest("getSignatureStatuses",n),r=w(s,Si);if("error"in r)throw new R(r.error,"failed to get signature status");return r.result}async getTransactionCount(e){const{commitment:t,config:n}=V(e),s=this._buildArgs([],t,void 0,n),r=await this._rpcRequest("getTransactionCount",s),o=w(r,C(l()));if("error"in o)throw new R(o.error,"failed to get transaction count");return o.result}async getTotalSupply(e){return(await this.getSupply({commitment:e,excludeNonCirculatingAccountsList:!0})).value.total}async getInflationGovernor(e){const t=this._buildArgs([],e),n=await this._rpcRequest("getInflationGovernor",t),s=w(n,Fr);if("error"in s)throw new R(s.error,"failed to get inflation");return s.result}async getInflationReward(e,t,n){const{commitment:s,config:r}=V(n),o=this._buildArgs([e.map(d=>d.toBase58())],s,void 0,{...r,epoch:t??(r==null?void 0:r.epoch)}),c=await this._rpcRequest("getInflationReward",o),u=w(c,vr);if("error"in u)throw new R(u.error,"failed to get inflation reward");return u.result}async getInflationRate(){const e=await this._rpcRequest("getInflationRate",[]),t=w(e,Vr);if("error"in t)throw new R(t.error,"failed to get inflation rate");return t.result}async getEpochInfo(e){const{commitment:t,config:n}=V(e),s=this._buildArgs([],t,void 0,n),r=await this._rpcRequest("getEpochInfo",s),o=w(r,Hr);if("error"in o)throw new R(o.error,"failed to get epoch info");return o.result}async getEpochSchedule(){const e=await this._rpcRequest("getEpochSchedule",[]),t=w(e,Gr);if("error"in t)throw new R(t.error,"failed to get epoch schedule");const n=t.result;return new Mn(n.slotsPerEpoch,n.leaderScheduleSlotOffset,n.warmup,n.firstNormalEpoch,n.firstNormalSlot)}async getLeaderSchedule(){const e=await this._rpcRequest("getLeaderSchedule",[]),t=w(e,jr);if("error"in t)throw new R(t.error,"failed to get leader schedule");return t.result}async getMinimumBalanceForRentExemption(e,t){const n=this._buildArgs([e],t),s=await this._rpcRequest("getMinimumBalanceForRentExemption",n),r=w(s,wi);return"error"in r?(console.warn("Unable to fetch minimum balance for rent exemption"),0):r.result}async getRecentBlockhashAndContext(e){const t=this._buildArgs([],e),n=await this._rpcRequest("getRecentBlockhash",t),s=w(n,Li);if("error"in s)throw new R(s.error,"failed to get recent blockhash");return s.result}async getRecentPerformanceSamples(e){const t=await this._rpcRequest("getRecentPerformanceSamples",e?[e]:[]),n=w(t,zi);if("error"in n)throw new R(n.error,"failed to get recent performance samples");return n.result}async getFeeCalculatorForBlockhash(e,t){const n=this._buildArgs([e],t),s=await this._rpcRequest("getFeeCalculatorForBlockhash",n),r=w(s,Ni);if("error"in r)throw new R(r.error,"failed to get fee calculator");const{context:o,value:c}=r.result;return{context:o,value:c!==null?c.feeCalculator:null}}async getFeeForMessage(e,t){const n=x(e.serialize()).toString("base64"),s=this._buildArgs([n],t),r=await this._rpcRequest("getFeeForMessage",s),o=w(r,G(I(l())));if("error"in o)throw new R(o.error,"failed to get fee for message");if(o.result===null)throw new Error("invalid blockhash");return o.result}async getRecentPrioritizationFees(e){var o;const t=(o=e==null?void 0:e.lockedWritableAccounts)==null?void 0:o.map(c=>c.toBase58()),n=t!=null&&t.length?[t]:[],s=await this._rpcRequest("getRecentPrioritizationFees",n),r=w(s,$r);if("error"in r)throw new R(r.error,"failed to get recent prioritization fees");return r.result}async getRecentBlockhash(e){try{return(await this.getRecentBlockhashAndContext(e)).value}catch(t){throw new Error("failed to get recent blockhash: "+t)}}async getLatestBlockhash(e){try{return(await this.getLatestBlockhashAndContext(e)).value}catch(t){throw new Error("failed to get recent blockhash: "+t)}}async getLatestBlockhashAndContext(e){const{commitment:t,config:n}=V(e),s=this._buildArgs([],t,void 0,n),r=await this._rpcRequest("getLatestBlockhash",s),o=w(r,Ci);if("error"in o)throw new R(o.error,"failed to get latest blockhash");return o.result}async isBlockhashValid(e,t){const{commitment:n,config:s}=V(t),r=this._buildArgs([e],n,void 0,s),o=await this._rpcRequest("isBlockhashValid",r),c=w(o,xi);if("error"in c)throw new R(c.error,"failed to determine if the blockhash `"+e+"`is valid");return c.result}async getVersion(){const e=await this._rpcRequest("getVersion",[]),t=w(e,C(Or));if("error"in t)throw new R(t.error,"failed to get version");return t.result}async getGenesisHash(){const e=await this._rpcRequest("getGenesisHash",[]),t=w(e,C(k()));if("error"in t)throw new R(t.error,"failed to get genesis hash");return t.result}async getBlock(e,t){const{commitment:n,config:s}=V(t),r=this._buildArgsAtLeastConfirmed([e],n,void 0,s),o=await this._rpcRequest("getBlock",r);try{switch(s==null?void 0:s.transactionDetails){case"accounts":{const c=w(o,Ri);if("error"in c)throw c.error;return c.result}case"none":{const c=w(o,Pi);if("error"in c)throw c.error;return c.result}default:{const c=w(o,_i);if("error"in c)throw c.error;const{result:u}=c;return u?{...u,transactions:u.transactions.map(({transaction:d,meta:h,version:g})=>({meta:h,transaction:{...d,message:At(g,d.message)},version:g}))}:null}}}catch(c){throw new R(c,"failed to get confirmed block")}}async getParsedBlock(e,t){const{commitment:n,config:s}=V(t),r=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",s),o=await this._rpcRequest("getBlock",r);try{switch(s==null?void 0:s.transactionDetails){case"accounts":{const c=w(o,Bi);if("error"in c)throw c.error;return c.result}case"none":{const c=w(o,Ti);if("error"in c)throw c.error;return c.result}default:{const c=w(o,Ei);if("error"in c)throw c.error;return c.result}}}catch(c){throw new R(c,"failed to get block")}}async getBlockProduction(e){let t,n;if(typeof e=="string")n=e;else if(e){const{commitment:c,...u}=e;n=c,t=u}const s=this._buildArgs([],n,"base64",t),r=await this._rpcRequest("getBlockProduction",s),o=w(r,Mr);if("error"in o)throw new R(o.error,"failed to get block production information");return o.result}async getTransaction(e,t){const{commitment:n,config:s}=V(t),r=this._buildArgsAtLeastConfirmed([e],n,void 0,s),o=await this._rpcRequest("getTransaction",r),c=w(o,_t);if("error"in c)throw new R(c.error,"failed to get transaction");const u=c.result;return u&&{...u,transaction:{...u.transaction,message:At(u.version,u.transaction.message)}}}async getParsedTransaction(e,t){const{commitment:n,config:s}=V(t),r=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",s),o=await this._rpcRequest("getTransaction",r),c=w(o,tt);if("error"in c)throw new R(c.error,"failed to get transaction");return c.result}async getParsedTransactions(e,t){const{commitment:n,config:s}=V(t),r=e.map(u=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([u],n,"jsonParsed",s)}));return(await this._rpcBatchRequest(r)).map(u=>{const d=w(u,tt);if("error"in d)throw new R(d.error,"failed to get transactions");return d.result})}async getTransactions(e,t){const{commitment:n,config:s}=V(t),r=e.map(u=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([u],n,void 0,s)}));return(await this._rpcBatchRequest(r)).map(u=>{const d=w(u,_t);if("error"in d)throw new R(d.error,"failed to get transactions");const h=d.result;return h&&{...h,transaction:{...h.transaction,message:At(h.version,h.transaction.message)}}})}async getConfirmedBlock(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),s=await this._rpcRequest("getConfirmedBlock",n),r=w(s,vi);if("error"in r)throw new R(r.error,"failed to get confirmed block");const o=r.result;if(!o)throw new Error("Confirmed block "+e+" not found");const c={...o,transactions:o.transactions.map(({transaction:u,meta:d})=>{const h=new ae(u.message);return{meta:d,transaction:{...u,message:h}}})};return{...c,transactions:c.transactions.map(({transaction:u,meta:d})=>({meta:d,transaction:N.populate(u.message,u.signatures)}))}}async getBlocks(e,t,n){const s=this._buildArgsAtLeastConfirmed(t!==void 0?[e,t]:[e],n),r=await this._rpcRequest("getBlocks",s),o=w(r,C(A(l())));if("error"in o)throw new R(o.error,"failed to get blocks");return o.result}async getBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),s=await this._rpcRequest("getBlock",n),r=w(s,yn);if("error"in r)throw new R(r.error,"failed to get block");const o=r.result;if(!o)throw new Error("Block "+e+" not found");return o}async getConfirmedBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),s=await this._rpcRequest("getConfirmedBlock",n),r=w(s,yn);if("error"in r)throw new R(r.error,"failed to get confirmed block");const o=r.result;if(!o)throw new Error("Confirmed block "+e+" not found");return o}async getConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),s=await this._rpcRequest("getConfirmedTransaction",n),r=w(s,_t);if("error"in r)throw new R(r.error,"failed to get transaction");const o=r.result;if(!o)return o;const c=new ae(o.transaction.message),u=o.transaction.signatures;return{...o,transaction:N.populate(c,u)}}async getParsedConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,"jsonParsed"),s=await this._rpcRequest("getConfirmedTransaction",n),r=w(s,tt);if("error"in r)throw new R(r.error,"failed to get confirmed transaction");return r.result}async getParsedConfirmedTransactions(e,t){const n=e.map(o=>({methodName:"getConfirmedTransaction",args:this._buildArgsAtLeastConfirmed([o],t,"jsonParsed")}));return(await this._rpcBatchRequest(n)).map(o=>{const c=w(o,tt);if("error"in c)throw new R(c.error,"failed to get confirmed transactions");return c.result})}async getConfirmedSignaturesForAddress(e,t,n){let s={},r=await this.getFirstAvailableBlock();for(;!("until"in s)&&(t--,!(t<=0||t<r));)try{const u=await this.getConfirmedBlockSignatures(t,"finalized");u.signatures.length>0&&(s.until=u.signatures[u.signatures.length-1].toString())}catch(u){if(u instanceof Error&&u.message.includes("skipped"))continue;throw u}let o=await this.getSlot("finalized");for(;!("before"in s)&&(n++,!(n>o));)try{const u=await this.getConfirmedBlockSignatures(n);u.signatures.length>0&&(s.before=u.signatures[u.signatures.length-1].toString())}catch(u){if(u instanceof Error&&u.message.includes("skipped"))continue;throw u}return(await this.getConfirmedSignaturesForAddress2(e,s)).map(u=>u.signature)}async getConfirmedSignaturesForAddress2(e,t,n){const s=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),r=await this._rpcRequest("getConfirmedSignaturesForAddress2",s),o=w(r,ii);if("error"in o)throw new R(o.error,"failed to get confirmed signatures for address");return o.result}async getSignaturesForAddress(e,t,n){const s=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),r=await this._rpcRequest("getSignaturesForAddress",s),o=w(r,oi);if("error"in o)throw new R(o.error,"failed to get signatures for address");return o.result}async getAddressLookupTable(e,t){const{context:n,value:s}=await this.getAccountInfoAndContext(e,t);let r=null;return s!==null&&(r=new vt({key:e,state:vt.deserialize(s.data)})),{context:n,value:r}}async getNonceAndContext(e,t){const{context:n,value:s}=await this.getAccountInfoAndContext(e,t);let r=null;return s!==null&&(r=lt.fromAccountData(s.data)),{context:n,value:r}}async getNonce(e,t){return await this.getNonceAndContext(e,t).then(n=>n.value).catch(n=>{throw new Error("failed to get nonce for account "+e.toBase58()+": "+n)})}async requestAirdrop(e,t){const n=await this._rpcRequest("requestAirdrop",[e.toBase58(),t]),s=w(n,Wi);if("error"in s)throw new R(s.error,`airdrop to ${e.toBase58()} failed`);return s.result}async _blockhashWithExpiryBlockHeight(e){if(!e){for(;this._pollingBlockhash;)await _e(100);const n=Date.now()-this._blockhashInfo.lastFetch>=qn;if(this._blockhashInfo.latestBlockhash!==null&&!n)return this._blockhashInfo.latestBlockhash}return await this._pollNewBlockhash()}async _pollNewBlockhash(){this._pollingBlockhash=!0;try{const e=Date.now(),t=this._blockhashInfo.latestBlockhash,n=t?t.blockhash:null;for(let s=0;s<50;s++){const r=await this.getLatestBlockhash("finalized");if(n!==r.blockhash)return this._blockhashInfo={latestBlockhash:r,lastFetch:Date.now(),transactionSignatures:[],simulatedSignatures:[]},r;await _e(zn/2)}throw new Error(`Unable to obtain a new blockhash after ${Date.now()-e}ms`)}finally{this._pollingBlockhash=!1}}async getStakeMinimumDelegation(e){const{commitment:t,config:n}=V(e),s=this._buildArgs([],t,"base64",n),r=await this._rpcRequest("getStakeMinimumDelegation",s),o=w(r,G(l()));if("error"in o)throw new R(o.error,"failed to get stake minimum delegation");return o.result}async simulateTransaction(e,t,n){if("message"in e){const m=e.serialize(),P=a.bufferPolyfill.Buffer.from(m).toString("base64");if(Array.isArray(t)||n!==void 0)throw new Error("Invalid arguments");const T=t||{};T.encoding="base64","commitment"in T||(T.commitment=this.commitment);const U=[P,T],te=await this._rpcRequest("simulateTransaction",U),ce=w(te,fn);if("error"in ce)throw new Error("failed to simulate transaction: "+ce.error.message);return ce.result}let s;if(e instanceof N){let b=e;s=new N,s.feePayer=b.feePayer,s.instructions=e.instructions,s.nonceInfo=b.nonceInfo,s.signatures=b.signatures}else s=N.populate(e),s._message=s._json=void 0;if(t!==void 0&&!Array.isArray(t))throw new Error("Invalid arguments");const r=t;if(s.nonceInfo&&r)s.sign(...r);else{let b=this._disableBlockhashCaching;for(;;){const m=await this._blockhashWithExpiryBlockHeight(b);if(s.lastValidBlockHeight=m.lastValidBlockHeight,s.recentBlockhash=m.blockhash,!r)break;if(s.sign(...r),!s.signature)throw new Error("!signature");const P=s.signature.toString("base64");if(!this._blockhashInfo.simulatedSignatures.includes(P)&&!this._blockhashInfo.transactionSignatures.includes(P)){this._blockhashInfo.simulatedSignatures.push(P);break}else b=!0}}const o=s._compile(),c=o.serialize(),d=s._serialize(c).toString("base64"),h={encoding:"base64",commitment:this.commitment};if(n){const b=(Array.isArray(n)?n:o.nonProgramIds()).map(m=>m.toBase58());h.accounts={encoding:"base64",addresses:b}}r&&(h.sigVerify=!0);const g=[d,h],S=await this._rpcRequest("simulateTransaction",g),f=w(S,fn);if("error"in f){let b;if("data"in f.error&&(b=f.error.data.logs,b&&Array.isArray(b))){const m=`
|
|
4
4
|
`,P=m+b.join(m);console.error(f.error.message,P)}throw new Tt("failed to simulate transaction: "+f.error.message,b)}return f.result}async sendTransaction(e,t,n){if("version"in e){if(t&&Array.isArray(t))throw new Error("Invalid arguments");const o=e.serialize();return await this.sendRawTransaction(o,t)}if(t===void 0||!Array.isArray(t))throw new Error("Invalid arguments");const s=t;if(e.nonceInfo)e.sign(...s);else{let o=this._disableBlockhashCaching;for(;;){const c=await this._blockhashWithExpiryBlockHeight(o);if(e.lastValidBlockHeight=c.lastValidBlockHeight,e.recentBlockhash=c.blockhash,e.sign(...s),!e.signature)throw new Error("!signature");const u=e.signature.toString("base64");if(this._blockhashInfo.transactionSignatures.includes(u))o=!0;else{this._blockhashInfo.transactionSignatures.push(u);break}}}const r=e.serialize();return await this.sendRawTransaction(r,n)}async sendRawTransaction(e,t){const n=x(e).toString("base64");return await this.sendEncodedTransaction(n,t)}async sendEncodedTransaction(e,t){const n={encoding:"base64"},s=t&&t.skipPreflight,r=s===!0?"processed":t&&t.preflightCommitment||this.commitment;t&&t.maxRetries!=null&&(n.maxRetries=t.maxRetries),t&&t.minContextSlot!=null&&(n.minContextSlot=t.minContextSlot),s&&(n.skipPreflight=s),r&&(n.preflightCommitment=r);const o=[e,n],c=await this._rpcRequest("sendTransaction",o),u=w(c,Oi);if("error"in u){let d;throw"data"in u.error&&(d=u.error.data.logs),new Tt("failed to send transaction: "+u.error.message,d)}return u.result}_wsOnOpen(){this._rpcWebSocketConnected=!0,this._rpcWebSocketHeartbeat=setInterval(()=>{(async()=>{try{await this._rpcWebSocket.notify("ping")}catch{}})()},5e3),this._updateSubscriptions()}_wsOnError(e){this._rpcWebSocketConnected=!1,console.error("ws error:",e.message)}_wsOnClose(e){if(this._rpcWebSocketConnected=!1,this._rpcWebSocketGeneration=(this._rpcWebSocketGeneration+1)%Number.MAX_SAFE_INTEGER,this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null),this._rpcWebSocketHeartbeat&&(clearInterval(this._rpcWebSocketHeartbeat),this._rpcWebSocketHeartbeat=null),e===1e3){this._updateSubscriptions();return}this._subscriptionCallbacksByServerSubscriptionId={},Object.entries(this._subscriptionsByHash).forEach(([t,n])=>{this._setSubscription(t,{...n,state:"pending"})})}_setSubscription(e,t){var s;const n=(s=this._subscriptionsByHash[e])==null?void 0:s.state;if(this._subscriptionsByHash[e]=t,n!==t.state){const r=this._subscriptionStateChangeCallbacksByHash[e];r&&r.forEach(o=>{try{o(t.state)}catch{}})}}_onSubscriptionStateChange(e,t){var r;const n=this._subscriptionHashByClientSubscriptionId[e];if(n==null)return()=>{};const s=(r=this._subscriptionStateChangeCallbacksByHash)[n]||(r[n]=new Set);return s.add(t),()=>{s.delete(t),s.size===0&&delete this._subscriptionStateChangeCallbacksByHash[n]}}async _updateSubscriptions(){if(Object.keys(this._subscriptionsByHash).length===0){this._rpcWebSocketConnected&&(this._rpcWebSocketConnected=!1,this._rpcWebSocketIdleTimeout=setTimeout(()=>{this._rpcWebSocketIdleTimeout=null;try{this._rpcWebSocket.close()}catch(n){n instanceof Error&&console.log(`Error when closing socket connection: ${n.message}`)}},500));return}if(this._rpcWebSocketIdleTimeout!==null&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketConnected=!0),!this._rpcWebSocketConnected){this._rpcWebSocket.connect();return}const e=this._rpcWebSocketGeneration,t=()=>e===this._rpcWebSocketGeneration;await Promise.all(Object.keys(this._subscriptionsByHash).map(async n=>{const s=this._subscriptionsByHash[n];if(s!==void 0)switch(s.state){case"pending":case"unsubscribed":if(s.callbacks.size===0){delete this._subscriptionsByHash[n],s.state==="unsubscribed"&&delete this._subscriptionCallbacksByServerSubscriptionId[s.serverSubscriptionId],await this._updateSubscriptions();return}await(async()=>{const{args:r,method:o}=s;try{this._setSubscription(n,{...s,state:"subscribing"});const c=await this._rpcWebSocket.call(o,r);this._setSubscription(n,{...s,serverSubscriptionId:c,state:"subscribed"}),this._subscriptionCallbacksByServerSubscriptionId[c]=s.callbacks,await this._updateSubscriptions()}catch(c){if(c instanceof Error&&console.error(`${o} error for argument`,r,c.message),!t())return;this._setSubscription(n,{...s,state:"pending"}),await this._updateSubscriptions()}})();break;case"subscribed":s.callbacks.size===0&&await(async()=>{const{serverSubscriptionId:r,unsubscribeMethod:o}=s;if(this._subscriptionsAutoDisposedByRpc.has(r))this._subscriptionsAutoDisposedByRpc.delete(r);else{this._setSubscription(n,{...s,state:"unsubscribing"}),this._setSubscription(n,{...s,state:"unsubscribing"});try{await this._rpcWebSocket.call(o,[r])}catch(c){if(c instanceof Error&&console.error(`${o} error:`,c.message),!t())return;this._setSubscription(n,{...s,state:"subscribed"}),await this._updateSubscriptions();return}}this._setSubscription(n,{...s,state:"unsubscribed"}),await this._updateSubscriptions()})();break}}))}_handleServerNotification(e,t){const n=this._subscriptionCallbacksByServerSubscriptionId[e];n!==void 0&&n.forEach(s=>{try{s(...t)}catch(r){console.error(r)}})}_wsOnAccountNotification(e){const{result:t,subscription:n}=w(e,ai);this._handleServerNotification(n,[t.value,t.context])}_makeSubscription(e,t){const n=this._nextClientSubscriptionId++,s=dn([e.method,t]),r=this._subscriptionsByHash[s];return r===void 0?this._subscriptionsByHash[s]={...e,args:t,callbacks:new Set([e.callback]),state:"pending"}:r.callbacks.add(e.callback),this._subscriptionHashByClientSubscriptionId[n]=s,this._subscriptionDisposeFunctionsByClientSubscriptionId[n]=async()=>{delete this._subscriptionDisposeFunctionsByClientSubscriptionId[n],delete this._subscriptionHashByClientSubscriptionId[n];const o=this._subscriptionsByHash[s];O(o!==void 0,`Could not find a \`Subscription\` when tearing down client subscription #${n}`),o.callbacks.delete(e.callback),await this._updateSubscriptions()},this._updateSubscriptions(),n}onAccountChange(e,t,n){const s=this._buildArgs([e.toBase58()],n||this._commitment||"finalized","base64");return this._makeSubscription({callback:t,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},s)}async removeAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"account change")}_wsOnProgramAccountNotification(e){const{result:t,subscription:n}=w(e,ui);this._handleServerNotification(n,[{accountId:t.value.pubkey,accountInfo:t.value.account},t.context])}onProgramAccountChange(e,t,n,s){const r=this._buildArgs([e.toBase58()],n||this._commitment||"finalized","base64",s?{filters:s}:void 0);return this._makeSubscription({callback:t,method:"programSubscribe",unsubscribeMethod:"programUnsubscribe"},r)}async removeProgramAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"program account change")}onLogs(e,t,n){const s=this._buildArgs([typeof e=="object"?{mentions:[e.toString()]}:e],n||this._commitment||"finalized");return this._makeSubscription({callback:t,method:"logsSubscribe",unsubscribeMethod:"logsUnsubscribe"},s)}async removeOnLogsListener(e){await this._unsubscribeClientSubscription(e,"logs")}_wsOnLogsNotification(e){const{result:t,subscription:n}=w(e,Ui);this._handleServerNotification(n,[t.value,t.context])}_wsOnSlotNotification(e){const{result:t,subscription:n}=w(e,di);this._handleServerNotification(n,[t])}onSlotChange(e){return this._makeSubscription({callback:e,method:"slotSubscribe",unsubscribeMethod:"slotUnsubscribe"},[])}async removeSlotChangeListener(e){await this._unsubscribeClientSubscription(e,"slot change")}_wsOnSlotUpdatesNotification(e){const{result:t,subscription:n}=w(e,fi);this._handleServerNotification(n,[t])}onSlotUpdate(e){return this._makeSubscription({callback:e,method:"slotsUpdatesSubscribe",unsubscribeMethod:"slotsUpdatesUnsubscribe"},[])}async removeSlotUpdateListener(e){await this._unsubscribeClientSubscription(e,"slot update")}async _unsubscribeClientSubscription(e,t){const n=this._subscriptionDisposeFunctionsByClientSubscriptionId[e];n?await n():console.warn(`Ignored unsubscribe request because an active subscription with id \`${e}\` for '${t}' events could not be found.`)}_buildArgs(e,t,n,s){const r=t||this._commitment;if(r||n||s){let o={};n&&(o.encoding=n),r&&(o.commitment=r),s&&(o=Object.assign(o,s)),e.push(o)}return e}_buildArgsAtLeastConfirmed(e,t,n,s){const r=t||this._commitment;if(r&&!["confirmed","finalized"].includes(r))throw new Error("Using Connection with default commitment: `"+this._commitment+"`, but method requires at least `confirmed`");return this._buildArgs(e,t,n,s)}_wsOnSignatureNotification(e){const{result:t,subscription:n}=w(e,gi);t.value!=="receivedSignature"&&this._subscriptionsAutoDisposedByRpc.add(n),this._handleServerNotification(n,t.value==="receivedSignature"?[{type:"received"},t.context]:[{type:"status",result:t.value},t.context])}onSignature(e,t,n){const s=this._buildArgs([e],n||this._commitment||"finalized"),r=this._makeSubscription({callback:(o,c)=>{if(o.type==="status"){t(o.result,c);try{this.removeSignatureListener(r)}catch{}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},s);return r}onSignatureWithOptions(e,t,n){const{commitment:s,...r}={...n,commitment:n&&n.commitment||this._commitment||"finalized"},o=this._buildArgs([e],s,void 0,r),c=this._makeSubscription({callback:(u,d)=>{t(u,d);try{this.removeSignatureListener(c)}catch{}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},o);return c}async removeSignatureListener(e){await this._unsubscribeClientSubscription(e,"signature result")}_wsOnRootNotification(e){const{result:t,subscription:n}=w(e,yi);this._handleServerNotification(n,[t])}onRootChange(e){return this._makeSubscription({callback:e,method:"rootSubscribe",unsubscribeMethod:"rootUnsubscribe"},[])}async removeRootChangeListener(e){await this._unsubscribeClientSubscription(e,"root change")}}class Ie{constructor(e){this._keypair=void 0,this._keypair=e??cn()}static generate(){return new Ie(cn())}static fromSecretKey(e,t){if(e.byteLength!==64)throw new Error("bad secret key size");const n=e.slice(32,64);if(!t||!t.skipValidation){const s=e.slice(0,32),r=rt(s);for(let o=0;o<32;o++)if(n[o]!==r[o])throw new Error("provided secretKey is invalid")}return new Ie({publicKey:n,secretKey:e})}static fromSeed(e){const t=rt(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),new Ie({publicKey:t,secretKey:n})}get publicKey(){return new y(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}const ke=Object.freeze({CreateLookupTable:{index:0,layout:a.struct([a.u32("instruction"),We("recentSlot"),a.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:a.struct([a.u32("instruction")])},ExtendLookupTable:{index:2,layout:a.struct([a.u32("instruction"),We(),a.seq(K(),a.offset(a.u32(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:a.struct([a.u32("instruction")])},CloseLookupTable:{index:4,layout:a.struct([a.u32("instruction")])}});class Fi{constructor(){}static decodeInstructionType(e){this.checkProgramId(e.programId);const n=a.u32("instruction").decode(e.data);let s;for(const[r,o]of Object.entries(ke))if(o.index==n){s=r;break}if(!s)throw new Error("Invalid Instruction. Should be a LookupTable Instruction");return s}static decodeCreateLookupTable(e){this.checkProgramId(e.programId),this.checkKeysLength(e.keys,4);const{recentSlot:t}=M(ke.CreateLookupTable,e.data);return{authority:e.keys[1].pubkey,payer:e.keys[2].pubkey,recentSlot:Number(t)}}static decodeExtendLookupTable(e){if(this.checkProgramId(e.programId),e.keys.length<2)throw new Error(`invalid instruction; found ${e.keys.length} keys, expected at least 2`);const{addresses:t}=M(ke.ExtendLookupTable,e.data);return{lookupTable:e.keys[0].pubkey,authority:e.keys[1].pubkey,payer:e.keys.length>2?e.keys[2].pubkey:void 0,addresses:t.map(n=>new y(n))}}static decodeCloseLookupTable(e){return this.checkProgramId(e.programId),this.checkKeysLength(e.keys,3),{lookupTable:e.keys[0].pubkey,authority:e.keys[1].pubkey,recipient:e.keys[2].pubkey}}static decodeFreezeLookupTable(e){return this.checkProgramId(e.programId),this.checkKeysLength(e.keys,2),{lookupTable:e.keys[0].pubkey,authority:e.keys[1].pubkey}}static decodeDeactivateLookupTable(e){return this.checkProgramId(e.programId),this.checkKeysLength(e.keys,2),{lookupTable:e.keys[0].pubkey,authority:e.keys[1].pubkey}}static checkProgramId(e){if(!e.equals(jt.programId))throw new Error("invalid instruction; programId is not AddressLookupTable Program")}static checkKeysLength(e,t){if(e.length<t)throw new Error(`invalid instruction; found ${e.length} keys, expected at least ${t}`)}}class jt{constructor(){}static createLookupTable(e){const[t,n]=y.findProgramAddressSync([e.authority.toBuffer(),a.toBufferLE_1(BigInt(e.recentSlot),8)],this.programId),s=ke.CreateLookupTable,r=z(s,{recentSlot:BigInt(e.recentSlot),bumpSeed:n}),o=[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:e.authority,isSigner:!0,isWritable:!1},{pubkey:e.payer,isSigner:!0,isWritable:!0},{pubkey:D.programId,isSigner:!1,isWritable:!1}];return[new q({programId:this.programId,keys:o,data:r}),t]}static freezeLookupTable(e){const t=ke.FreezeLookupTable,n=z(t),s=[{pubkey:e.lookupTable,isSigner:!1,isWritable:!0},{pubkey:e.authority,isSigner:!0,isWritable:!1}];return new q({programId:this.programId,keys:s,data:n})}static extendLookupTable(e){const t=ke.ExtendLookupTable,n=z(t,{addresses:e.addresses.map(r=>r.toBytes())}),s=[{pubkey:e.lookupTable,isSigner:!1,isWritable:!0},{pubkey:e.authority,isSigner:!0,isWritable:!1}];return e.payer&&s.push({pubkey:e.payer,isSigner:!0,isWritable:!0},{pubkey:D.programId,isSigner:!1,isWritable:!1}),new q({programId:this.programId,keys:s,data:n})}static deactivateLookupTable(e){const t=ke.DeactivateLookupTable,n=z(t),s=[{pubkey:e.lookupTable,isSigner:!1,isWritable:!0},{pubkey:e.authority,isSigner:!0,isWritable:!1}];return new q({programId:this.programId,keys:s,data:n})}static closeLookupTable(e){const t=ke.CloseLookupTable,n=z(t),s=[{pubkey:e.lookupTable,isSigner:!1,isWritable:!0},{pubkey:e.authority,isSigner:!0,isWritable:!1},{pubkey:e.recipient,isSigner:!1,isWritable:!0}];return new q({programId:this.programId,keys:s,data:n})}}jt.programId=new y("AddressLookupTab1e1111111111111111111111111");class Vi{constructor(){}static decodeInstructionType(e){this.checkProgramId(e.programId);const n=a.u8("instruction").decode(e.data);let s;for(const[r,o]of Object.entries(le))if(o.index==n){s=r;break}if(!s)throw new Error("Instruction type incorrect; not a ComputeBudgetInstruction");return s}static decodeRequestUnits(e){this.checkProgramId(e.programId);const{units:t,additionalFee:n}=M(le.RequestUnits,e.data);return{units:t,additionalFee:n}}static decodeRequestHeapFrame(e){this.checkProgramId(e.programId);const{bytes:t}=M(le.RequestHeapFrame,e.data);return{bytes:t}}static decodeSetComputeUnitLimit(e){this.checkProgramId(e.programId);const{units:t}=M(le.SetComputeUnitLimit,e.data);return{units:t}}static decodeSetComputeUnitPrice(e){this.checkProgramId(e.programId);const{microLamports:t}=M(le.SetComputeUnitPrice,e.data);return{microLamports:t}}static checkProgramId(e){if(!e.equals(Yt.programId))throw new Error("invalid instruction; programId is not ComputeBudgetProgram")}}const le=Object.freeze({RequestUnits:{index:0,layout:a.struct([a.u8("instruction"),a.u32("units"),a.u32("additionalFee")])},RequestHeapFrame:{index:1,layout:a.struct([a.u8("instruction"),a.u32("bytes")])},SetComputeUnitLimit:{index:2,layout:a.struct([a.u8("instruction"),a.u32("units")])},SetComputeUnitPrice:{index:3,layout:a.struct([a.u8("instruction"),We("microLamports")])}});class Yt{constructor(){}static requestUnits(e){const t=le.RequestUnits,n=z(t,e);return new q({keys:[],programId:this.programId,data:n})}static requestHeapFrame(e){const t=le.RequestHeapFrame,n=z(t,e);return new q({keys:[],programId:this.programId,data:n})}static setComputeUnitLimit(e){const t=le.SetComputeUnitLimit,n=z(t,e);return new q({keys:[],programId:this.programId,data:n})}static setComputeUnitPrice(e){const t=le.SetComputeUnitPrice,n=z(t,{microLamports:BigInt(e.microLamports)});return new q({keys:[],programId:this.programId,data:n})}}Yt.programId=new y("ComputeBudget111111111111111111111111111111");const pn=64,mn=32,bn=64,kn=a.struct([a.u8("numSignatures"),a.u8("padding"),a.u16("signatureOffset"),a.u16("signatureInstructionIndex"),a.u16("publicKeyOffset"),a.u16("publicKeyInstructionIndex"),a.u16("messageDataOffset"),a.u16("messageDataSize"),a.u16("messageInstructionIndex")]);class ft{constructor(){}static createInstructionWithPublicKey(e){const{publicKey:t,message:n,signature:s,instructionIndex:r}=e;O(t.length===mn,`Public Key must be ${mn} bytes but received ${t.length} bytes`),O(s.length===bn,`Signature must be ${bn} bytes but received ${s.length} bytes`);const o=kn.span,c=o+t.length,u=c+s.length,d=1,h=a.bufferPolyfill.Buffer.alloc(u+n.length),g=r??65535;return kn.encode({numSignatures:d,padding:0,signatureOffset:c,signatureInstructionIndex:g,publicKeyOffset:o,publicKeyInstructionIndex:g,messageDataOffset:u,messageDataSize:n.length,messageInstructionIndex:g},h),h.fill(t,o),h.fill(s,c),h.fill(n,u),new q({keys:[],programId:ft.programId,data:h})}static createInstructionWithPrivateKey(e){const{privateKey:t,message:n,instructionIndex:s}=e;O(t.length===pn,`Private key must be ${pn} bytes but received ${t.length} bytes`);try{const r=Ie.fromSecretKey(t),o=r.publicKey.toBytes(),c=Ot(n,r.secretKey);return this.createInstructionWithPublicKey({publicKey:o,message:n,signature:c,instructionIndex:s})}catch(r){throw new Error(`Error creating instruction; ${r}`)}}}ft.programId=new y("Ed25519SigVerify111111111111111111111111111");const $i=(i,e)=>{const t=a.secp256k1.sign(i,e);return[t.toCompactRawBytes(),t.recovery]};a.secp256k1.utils.isValidPrivateKey;const Hi=a.secp256k1.getPublicKey,Sn=32,Pt=20,wn=64,Gi=11,Rt=a.struct([a.u8("numSignatures"),a.u16("signatureOffset"),a.u8("signatureInstructionIndex"),a.u16("ethAddressOffset"),a.u8("ethAddressInstructionIndex"),a.u16("messageDataOffset"),a.u16("messageDataSize"),a.u8("messageInstructionIndex"),a.blob(20,"ethAddress"),a.blob(64,"signature"),a.u8("recoveryId")]);class Ee{constructor(){}static publicKeyToEthAddress(e){O(e.length===wn,`Public key must be ${wn} bytes but received ${e.length} bytes`);try{return a.bufferPolyfill.Buffer.from(a.keccak_256(x(e))).slice(-Pt)}catch(t){throw new Error(`Error constructing Ethereum address: ${t}`)}}static createInstructionWithPublicKey(e){const{publicKey:t,message:n,signature:s,recoveryId:r,instructionIndex:o}=e;return Ee.createInstructionWithEthAddress({ethAddress:Ee.publicKeyToEthAddress(t),message:n,signature:s,recoveryId:r,instructionIndex:o})}static createInstructionWithEthAddress(e){const{ethAddress:t,message:n,signature:s,recoveryId:r,instructionIndex:o=0}=e;let c;typeof t=="string"?t.startsWith("0x")?c=a.bufferPolyfill.Buffer.from(t.substr(2),"hex"):c=a.bufferPolyfill.Buffer.from(t,"hex"):c=t,O(c.length===Pt,`Address must be ${Pt} bytes but received ${c.length} bytes`);const u=1+Gi,d=u,h=u+c.length,g=h+s.length+1,S=1,f=a.bufferPolyfill.Buffer.alloc(Rt.span+n.length);return Rt.encode({numSignatures:S,signatureOffset:h,signatureInstructionIndex:o,ethAddressOffset:d,ethAddressInstructionIndex:o,messageDataOffset:g,messageDataSize:n.length,messageInstructionIndex:o,signature:x(s),ethAddress:x(c),recoveryId:r},f),f.fill(x(n),Rt.span),new q({keys:[],programId:Ee.programId,data:f})}static createInstructionWithPrivateKey(e){const{privateKey:t,message:n,instructionIndex:s}=e;O(t.length===Sn,`Private key must be ${Sn} bytes but received ${t.length} bytes`);try{const r=x(t),o=Hi(r,!1).slice(1),c=a.bufferPolyfill.Buffer.from(a.keccak_256(x(n))),[u,d]=$i(c,r);return this.createInstructionWithPublicKey({publicKey:o,message:n,signature:u,recoveryId:d,instructionIndex:s})}catch(r){throw new Error(`Error creating instruction; ${r}`)}}}Ee.programId=new y("KeccakSecp256k11111111111111111111111111111");var Xn;const Zn=new y("StakeConfig11111111111111111111111111111111");class Qn{constructor(e,t){this.staker=void 0,this.withdrawer=void 0,this.staker=e,this.withdrawer=t}}class et{constructor(e,t,n){this.unixTimestamp=void 0,this.epoch=void 0,this.custodian=void 0,this.unixTimestamp=e,this.epoch=t,this.custodian=n}}Xn=et;et.default=new Xn(0,0,y.default);class ji{constructor(){}static decodeInstructionType(e){this.checkProgramId(e.programId);const n=a.u32("instruction").decode(e.data);let s;for(const[r,o]of Object.entries(J))if(o.index==n){s=r;break}if(!s)throw new Error("Instruction type incorrect; not a StakeInstruction");return s}static decodeInitialize(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,2);const{authorized:t,lockup:n}=M(J.Initialize,e.data);return{stakePubkey:e.keys[0].pubkey,authorized:new Qn(new y(t.staker),new y(t.withdrawer)),lockup:new et(n.unixTimestamp,n.epoch,new y(n.custodian))}}static decodeDelegate(e){return this.checkProgramId(e.programId),this.checkKeyLength(e.keys,6),M(J.Delegate,e.data),{stakePubkey:e.keys[0].pubkey,votePubkey:e.keys[1].pubkey,authorizedPubkey:e.keys[5].pubkey}}static decodeAuthorize(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,3);const{newAuthorized:t,stakeAuthorizationType:n}=M(J.Authorize,e.data),s={stakePubkey:e.keys[0].pubkey,authorizedPubkey:e.keys[2].pubkey,newAuthorizedPubkey:new y(t),stakeAuthorizationType:{index:n}};return e.keys.length>3&&(s.custodianPubkey=e.keys[3].pubkey),s}static decodeAuthorizeWithSeed(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,2);const{newAuthorized:t,stakeAuthorizationType:n,authoritySeed:s,authorityOwner:r}=M(J.AuthorizeWithSeed,e.data),o={stakePubkey:e.keys[0].pubkey,authorityBase:e.keys[1].pubkey,authoritySeed:s,authorityOwner:new y(r),newAuthorizedPubkey:new y(t),stakeAuthorizationType:{index:n}};return e.keys.length>3&&(o.custodianPubkey=e.keys[3].pubkey),o}static decodeSplit(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,3);const{lamports:t}=M(J.Split,e.data);return{stakePubkey:e.keys[0].pubkey,splitStakePubkey:e.keys[1].pubkey,authorizedPubkey:e.keys[2].pubkey,lamports:t}}static decodeMerge(e){return this.checkProgramId(e.programId),this.checkKeyLength(e.keys,3),M(J.Merge,e.data),{stakePubkey:e.keys[0].pubkey,sourceStakePubKey:e.keys[1].pubkey,authorizedPubkey:e.keys[4].pubkey}}static decodeWithdraw(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,5);const{lamports:t}=M(J.Withdraw,e.data),n={stakePubkey:e.keys[0].pubkey,toPubkey:e.keys[1].pubkey,authorizedPubkey:e.keys[4].pubkey,lamports:t};return e.keys.length>5&&(n.custodianPubkey=e.keys[5].pubkey),n}static decodeDeactivate(e){return this.checkProgramId(e.programId),this.checkKeyLength(e.keys,3),M(J.Deactivate,e.data),{stakePubkey:e.keys[0].pubkey,authorizedPubkey:e.keys[2].pubkey}}static checkProgramId(e){if(!e.equals(gt.programId))throw new Error("invalid instruction; programId is not StakeProgram")}static checkKeyLength(e,t){if(e.length<t)throw new Error(`invalid instruction; found ${e.length} keys, expected at least ${t}`)}}const J=Object.freeze({Initialize:{index:0,layout:a.struct([a.u32("instruction"),Xs(),Zs()])},Authorize:{index:1,layout:a.struct([a.u32("instruction"),K("newAuthorized"),a.u32("stakeAuthorizationType")])},Delegate:{index:2,layout:a.struct([a.u32("instruction")])},Split:{index:3,layout:a.struct([a.u32("instruction"),a.ns64("lamports")])},Withdraw:{index:4,layout:a.struct([a.u32("instruction"),a.ns64("lamports")])},Deactivate:{index:5,layout:a.struct([a.u32("instruction")])},Merge:{index:7,layout:a.struct([a.u32("instruction")])},AuthorizeWithSeed:{index:8,layout:a.struct([a.u32("instruction"),K("newAuthorized"),a.u32("stakeAuthorizationType"),Re("authoritySeed"),K("authorityOwner")])}}),Yi=Object.freeze({Staker:{index:0},Withdrawer:{index:1}});class gt{constructor(){}static initialize(e){const{stakePubkey:t,authorized:n,lockup:s}=e,r=s||et.default,o=J.Initialize,c=z(o,{authorized:{staker:x(n.staker.toBuffer()),withdrawer:x(n.withdrawer.toBuffer())},lockup:{unixTimestamp:r.unixTimestamp,epoch:r.epoch,custodian:x(r.custodian.toBuffer())}}),u={keys:[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:ie,isSigner:!1,isWritable:!1}],programId:this.programId,data:c};return new q(u)}static createAccountWithSeed(e){const t=new N;t.add(D.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.stakePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:this.space,programId:this.programId}));const{stakePubkey:n,authorized:s,lockup:r}=e;return t.add(this.initialize({stakePubkey:n,authorized:s,lockup:r}))}static createAccount(e){const t=new N;t.add(D.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.stakePubkey,lamports:e.lamports,space:this.space,programId:this.programId}));const{stakePubkey:n,authorized:s,lockup:r}=e;return t.add(this.initialize({stakePubkey:n,authorized:s,lockup:r}))}static delegate(e){const{stakePubkey:t,authorizedPubkey:n,votePubkey:s}=e,r=J.Delegate,o=z(r);return new N().add({keys:[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!1},{pubkey:Q,isSigner:!1,isWritable:!1},{pubkey:st,isSigner:!1,isWritable:!1},{pubkey:Zn,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!0,isWritable:!1}],programId:this.programId,data:o})}static authorize(e){const{stakePubkey:t,authorizedPubkey:n,newAuthorizedPubkey:s,stakeAuthorizationType:r,custodianPubkey:o}=e,c=J.Authorize,u=z(c,{newAuthorized:x(s.toBuffer()),stakeAuthorizationType:r.index}),d=[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:Q,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!0,isWritable:!1}];return o&&d.push({pubkey:o,isSigner:!0,isWritable:!1}),new N().add({keys:d,programId:this.programId,data:u})}static authorizeWithSeed(e){const{stakePubkey:t,authorityBase:n,authoritySeed:s,authorityOwner:r,newAuthorizedPubkey:o,stakeAuthorizationType:c,custodianPubkey:u}=e,d=J.AuthorizeWithSeed,h=z(d,{newAuthorized:x(o.toBuffer()),stakeAuthorizationType:c.index,authoritySeed:s,authorityOwner:x(r.toBuffer())}),g=[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!0,isWritable:!1},{pubkey:Q,isSigner:!1,isWritable:!1}];return u&&g.push({pubkey:u,isSigner:!0,isWritable:!1}),new N().add({keys:g,programId:this.programId,data:h})}static splitInstruction(e){const{stakePubkey:t,authorizedPubkey:n,splitStakePubkey:s,lamports:r}=e,o=J.Split,c=z(o,{lamports:r});return new q({keys:[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!0,isWritable:!1}],programId:this.programId,data:c})}static split(e,t){const n=new N;return n.add(D.createAccount({fromPubkey:e.authorizedPubkey,newAccountPubkey:e.splitStakePubkey,lamports:t,space:this.space,programId:this.programId})),n.add(this.splitInstruction(e))}static splitWithSeed(e,t){const{stakePubkey:n,authorizedPubkey:s,splitStakePubkey:r,basePubkey:o,seed:c,lamports:u}=e,d=new N;return d.add(D.allocate({accountPubkey:r,basePubkey:o,seed:c,space:this.space,programId:this.programId})),t&&t>0&&d.add(D.transfer({fromPubkey:e.authorizedPubkey,toPubkey:r,lamports:t})),d.add(this.splitInstruction({stakePubkey:n,authorizedPubkey:s,splitStakePubkey:r,lamports:u}))}static merge(e){const{stakePubkey:t,sourceStakePubKey:n,authorizedPubkey:s}=e,r=J.Merge,o=z(r);return new N().add({keys:[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:Q,isSigner:!1,isWritable:!1},{pubkey:st,isSigner:!1,isWritable:!1},{pubkey:s,isSigner:!0,isWritable:!1}],programId:this.programId,data:o})}static withdraw(e){const{stakePubkey:t,authorizedPubkey:n,toPubkey:s,lamports:r,custodianPubkey:o}=e,c=J.Withdraw,u=z(c,{lamports:r}),d=[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!1,isWritable:!0},{pubkey:Q,isSigner:!1,isWritable:!1},{pubkey:st,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!0,isWritable:!1}];return o&&d.push({pubkey:o,isSigner:!0,isWritable:!1}),new N().add({keys:d,programId:this.programId,data:u})}static deactivate(e){const{stakePubkey:t,authorizedPubkey:n}=e,s=J.Deactivate,r=z(s);return new N().add({keys:[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:Q,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!0,isWritable:!1}],programId:this.programId,data:r})}}gt.programId=new y("Stake11111111111111111111111111111111111111");gt.space=200;class es{constructor(e,t,n,s){this.nodePubkey=void 0,this.authorizedVoter=void 0,this.authorizedWithdrawer=void 0,this.commission=void 0,this.nodePubkey=e,this.authorizedVoter=t,this.authorizedWithdrawer=n,this.commission=s}}class Ji{constructor(){}static decodeInstructionType(e){this.checkProgramId(e.programId);const n=a.u32("instruction").decode(e.data);let s;for(const[r,o]of Object.entries(de))if(o.index==n){s=r;break}if(!s)throw new Error("Instruction type incorrect; not a VoteInstruction");return s}static decodeInitializeAccount(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,4);const{voteInit:t}=M(de.InitializeAccount,e.data);return{votePubkey:e.keys[0].pubkey,nodePubkey:e.keys[3].pubkey,voteInit:new es(new y(t.nodePubkey),new y(t.authorizedVoter),new y(t.authorizedWithdrawer),t.commission)}}static decodeAuthorize(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,3);const{newAuthorized:t,voteAuthorizationType:n}=M(de.Authorize,e.data);return{votePubkey:e.keys[0].pubkey,authorizedPubkey:e.keys[2].pubkey,newAuthorizedPubkey:new y(t),voteAuthorizationType:{index:n}}}static decodeAuthorizeWithSeed(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,3);const{voteAuthorizeWithSeedArgs:{currentAuthorityDerivedKeyOwnerPubkey:t,currentAuthorityDerivedKeySeed:n,newAuthorized:s,voteAuthorizationType:r}}=M(de.AuthorizeWithSeed,e.data);return{currentAuthorityDerivedKeyBasePubkey:e.keys[2].pubkey,currentAuthorityDerivedKeyOwnerPubkey:new y(t),currentAuthorityDerivedKeySeed:n,newAuthorizedPubkey:new y(s),voteAuthorizationType:{index:r},votePubkey:e.keys[0].pubkey}}static decodeWithdraw(e){this.checkProgramId(e.programId),this.checkKeyLength(e.keys,3);const{lamports:t}=M(de.Withdraw,e.data);return{votePubkey:e.keys[0].pubkey,authorizedWithdrawerPubkey:e.keys[2].pubkey,lamports:t,toPubkey:e.keys[1].pubkey}}static checkProgramId(e){if(!e.equals(qe.programId))throw new Error("invalid instruction; programId is not VoteProgram")}static checkKeyLength(e,t){if(e.length<t)throw new Error(`invalid instruction; found ${e.length} keys, expected at least ${t}`)}}const de=Object.freeze({InitializeAccount:{index:0,layout:a.struct([a.u32("instruction"),Qs()])},Authorize:{index:1,layout:a.struct([a.u32("instruction"),K("newAuthorized"),a.u32("voteAuthorizationType")])},Withdraw:{index:3,layout:a.struct([a.u32("instruction"),a.ns64("lamports")])},UpdateValidatorIdentity:{index:4,layout:a.struct([a.u32("instruction")])},AuthorizeWithSeed:{index:10,layout:a.struct([a.u32("instruction"),er()])}}),Xi=Object.freeze({Voter:{index:0},Withdrawer:{index:1}});class qe{constructor(){}static initializeAccount(e){const{votePubkey:t,nodePubkey:n,voteInit:s}=e,r=de.InitializeAccount,o=z(r,{voteInit:{nodePubkey:x(s.nodePubkey.toBuffer()),authorizedVoter:x(s.authorizedVoter.toBuffer()),authorizedWithdrawer:x(s.authorizedWithdrawer.toBuffer()),commission:s.commission}}),c={keys:[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:ie,isSigner:!1,isWritable:!1},{pubkey:Q,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!0,isWritable:!1}],programId:this.programId,data:o};return new q(c)}static createAccount(e){const t=new N;return t.add(D.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.votePubkey,lamports:e.lamports,space:this.space,programId:this.programId})),t.add(this.initializeAccount({votePubkey:e.votePubkey,nodePubkey:e.voteInit.nodePubkey,voteInit:e.voteInit}))}static authorize(e){const{votePubkey:t,authorizedPubkey:n,newAuthorizedPubkey:s,voteAuthorizationType:r}=e,o=de.Authorize,c=z(o,{newAuthorized:x(s.toBuffer()),voteAuthorizationType:r.index}),u=[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:Q,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!0,isWritable:!1}];return new N().add({keys:u,programId:this.programId,data:c})}static authorizeWithSeed(e){const{currentAuthorityDerivedKeyBasePubkey:t,currentAuthorityDerivedKeyOwnerPubkey:n,currentAuthorityDerivedKeySeed:s,newAuthorizedPubkey:r,voteAuthorizationType:o,votePubkey:c}=e,u=de.AuthorizeWithSeed,d=z(u,{voteAuthorizeWithSeedArgs:{currentAuthorityDerivedKeyOwnerPubkey:x(n.toBuffer()),currentAuthorityDerivedKeySeed:s,newAuthorized:x(r.toBuffer()),voteAuthorizationType:o.index}}),h=[{pubkey:c,isSigner:!1,isWritable:!0},{pubkey:Q,isSigner:!1,isWritable:!1},{pubkey:t,isSigner:!0,isWritable:!1}];return new N().add({keys:h,programId:this.programId,data:d})}static withdraw(e){const{votePubkey:t,authorizedWithdrawerPubkey:n,lamports:s,toPubkey:r}=e,o=de.Withdraw,c=z(o,{lamports:s}),u=[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!0,isWritable:!1}];return new N().add({keys:u,programId:this.programId,data:c})}static safeWithdraw(e,t,n){if(e.lamports>t-n)throw new Error("Withdraw will leave vote account with insufficient funds.");return qe.withdraw(e)}static updateValidatorIdentity(e){const{votePubkey:t,authorizedWithdrawerPubkey:n,nodePubkey:s}=e,r=de.UpdateValidatorIdentity,o=z(r),c=[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:s,isSigner:!0,isWritable:!1},{pubkey:n,isSigner:!0,isWritable:!1}];return new N().add({keys:c,programId:this.programId,data:o})}}qe.programId=new y("Vote111111111111111111111111111111111111111");qe.space=3762;const ts=new y("Va1idator1nfo111111111111111111111111111111"),Zi=p({name:k(),website:B(k()),details:B(k()),keybaseUsername:B(k())});class Jt{constructor(e,t){this.key=void 0,this.info=void 0,this.key=e,this.info=t}static fromConfigData(e){let t=[...e];if(X(t)!==2)return null;const s=[];for(let r=0;r<2;r++){const o=new y(Z(t,0,he)),c=ue(t)===1;s.push({publicKey:o,isSigner:c})}if(s[0].publicKey.equals(ts)&&s[1].isSigner){const r=Re().decode(a.bufferPolyfill.Buffer.from(t)),o=JSON.parse(r);return En(o,Zi),new Jt(s[1].publicKey,o)}return null}}const Qi=new y("Vote111111111111111111111111111111111111111"),eo=a.struct([K("nodePubkey"),K("authorizedWithdrawer"),a.u8("commission"),a.nu64(),a.seq(a.struct([a.nu64("slot"),a.u32("confirmationCount")]),a.offset(a.u32(),-8),"votes"),a.u8("rootSlotValid"),a.nu64("rootSlot"),a.nu64(),a.seq(a.struct([a.nu64("epoch"),K("authorizedVoter")]),a.offset(a.u32(),-8),"authorizedVoters"),a.struct([a.seq(a.struct([K("authorizedPubkey"),a.nu64("epochOfLastAuthorizedSwitch"),a.nu64("targetEpoch")]),32,"buf"),a.nu64("idx"),a.u8("isEmpty")],"priorVoters"),a.nu64(),a.seq(a.struct([a.nu64("epoch"),a.nu64("credits"),a.nu64("prevCredits")]),a.offset(a.u32(),-8),"epochCredits"),a.struct([a.nu64("slot"),a.nu64("timestamp")],"lastTimestamp")]);class Xt{constructor(e){this.nodePubkey=void 0,this.authorizedWithdrawer=void 0,this.commission=void 0,this.rootSlot=void 0,this.votes=void 0,this.authorizedVoters=void 0,this.priorVoters=void 0,this.epochCredits=void 0,this.lastTimestamp=void 0,this.nodePubkey=e.nodePubkey,this.authorizedWithdrawer=e.authorizedWithdrawer,this.commission=e.commission,this.rootSlot=e.rootSlot,this.votes=e.votes,this.authorizedVoters=e.authorizedVoters,this.priorVoters=e.priorVoters,this.epochCredits=e.epochCredits,this.lastTimestamp=e.lastTimestamp}static fromAccountData(e){const n=eo.decode(x(e),4);let s=n.rootSlot;return n.rootSlotValid||(s=null),new Xt({nodePubkey:new y(n.nodePubkey),authorizedWithdrawer:new y(n.authorizedWithdrawer),commission:n.commission,votes:n.votes,rootSlot:s,authorizedVoters:n.authorizedVoters.map(to),priorVoters:no(n.priorVoters),epochCredits:n.epochCredits,lastTimestamp:n.lastTimestamp})}}function to({authorizedVoter:i,epoch:e}){return{epoch:e,authorizedVoter:new y(i)}}function In({authorizedPubkey:i,epochOfLastAuthorizedSwitch:e,targetEpoch:t}){return{authorizedPubkey:new y(i),epochOfLastAuthorizedSwitch:e,targetEpoch:t}}function no({buf:i,idx:e,isEmpty:t}){return t?[]:[...i.slice(e+1).map(In),...i.slice(0,e).map(In)]}const An={http:{devnet:"http://api.devnet.solana.com",testnet:"http://api.testnet.solana.com","mainnet-beta":"http://api.mainnet-beta.solana.com/"},https:{devnet:"https://api.devnet.solana.com",testnet:"https://api.testnet.solana.com","mainnet-beta":"https://api.mainnet-beta.solana.com/"}};function so(i,e){const t=e===!1?"http":"https";if(!i)return An[t].devnet;const n=An[t][i];if(!n)throw new Error(`Unknown ${t} cluster: ${i}`);return n}async function ro(i,e,t,n){let s,r;t&&Object.prototype.hasOwnProperty.call(t,"lastValidBlockHeight")||t&&Object.prototype.hasOwnProperty.call(t,"nonceValue")?(s=t,r=n):r=t;const o=r&&{skipPreflight:r.skipPreflight,preflightCommitment:r.preflightCommitment||r.commitment,minContextSlot:r.minContextSlot},c=await i.sendRawTransaction(e,o),u=r&&r.commitment,h=(await(s?i.confirmTransaction(s,u):i.confirmTransaction(c,u))).value;if(h.err)throw new Error(`Raw transaction ${c} failed (${JSON.stringify(h)})`);return c}const io=1e9,oo=Object.freeze(Object.defineProperty({__proto__:null,Account:js,AddressLookupTableAccount:vt,AddressLookupTableInstruction:Fi,AddressLookupTableProgram:jt,Authorized:Qn,BLOCKHASH_CACHE_TIMEOUT_MS:qn,BPF_LOADER_DEPRECATED_PROGRAM_ID:Ys,BPF_LOADER_PROGRAM_ID:fr,BpfLoader:gr,COMPUTE_BUDGET_INSTRUCTION_LAYOUTS:le,ComputeBudgetInstruction:Vi,ComputeBudgetProgram:Yt,Connection:Di,Ed25519Program:ft,Enum:Hs,EpochSchedule:Mn,FeeCalculatorLayout:Wn,Keypair:Ie,LAMPORTS_PER_SOL:io,LOOKUP_TABLE_INSTRUCTION_LAYOUTS:ke,Loader:Te,Lockup:et,MAX_SEED_LENGTH:Cn,Message:ae,MessageAccountKeys:Ye,MessageV0:Be,NONCE_ACCOUNT_LENGTH:Bt,NonceAccount:lt,PACKET_DATA_SIZE:we,PUBLIC_KEY_LENGTH:he,PublicKey:y,SIGNATURE_LENGTH_IN_BYTES:je,SOLANA_SCHEMA:He,STAKE_CONFIG_ID:Zn,STAKE_INSTRUCTION_LAYOUTS:J,SYSTEM_INSTRUCTION_LAYOUTS:F,SYSVAR_CLOCK_PUBKEY:Q,SYSVAR_EPOCH_SCHEDULE_PUBKEY:ir,SYSVAR_INSTRUCTIONS_PUBKEY:Nn,SYSVAR_RECENT_BLOCKHASHES_PUBKEY:nt,SYSVAR_RENT_PUBKEY:ie,SYSVAR_REWARDS_PUBKEY:or,SYSVAR_SLOT_HASHES_PUBKEY:ar,SYSVAR_SLOT_HISTORY_PUBKEY:cr,SYSVAR_STAKE_HISTORY_PUBKEY:st,Secp256k1Program:Ee,SendTransactionError:Tt,SolanaJSONRPCError:R,SolanaJSONRPCErrorCode:Sr,StakeAuthorizationLayout:Yi,StakeInstruction:ji,StakeProgram:gt,Struct:Mt,SystemInstruction:dr,SystemProgram:D,Transaction:N,TransactionExpiredBlockheightExceededError:Ut,TransactionExpiredNonceInvalidError:ze,TransactionExpiredTimeoutError:qt,TransactionInstruction:q,TransactionMessage:Ft,TransactionStatus:be,VALIDATOR_INFO_KEY:ts,VERSION_PREFIX_MASK:ct,VOTE_PROGRAM_ID:Qi,ValidatorInfo:Jt,VersionedMessage:Dt,VersionedTransaction:Vt,VoteAccount:Xt,VoteAuthorizationLayout:Xi,VoteInit:es,VoteInstruction:Ji,VoteProgram:qe,clusterApiUrl:so,sendAndConfirmRawTransaction:ro,sendAndConfirmTransaction:Et},Symbol.toStringTag,{value:"Module"})),ns=[{name:"discriminator",binary:"bytes",size:4},{name:"consistencyLevel",binary:"uint",size:1,endianness:"little"},{name:"emitterAuthority",...a.universalAddressItem},{name:"messageStatus",binary:"uint",size:1,endianness:"little"},{name:"gap",binary:"uint",size:3},{name:"timestamp",binary:"uint",size:4,endianness:"little"},{name:"nonce",binary:"uint",size:4,endianness:"little"},{name:"sequence",binary:"uint",size:8,endianness:"little"},{name:"emitterChain",binary:"uint",size:2,endianness:"little"},{name:"emitterAddress",...a.universalAddressItem},{name:"payloadLength",binary:"uint",size:4,endianness:"little"},{name:"payload",binary:"bytes"}];function ss(i){return a.deserializeLayout(ns,i)}function Ke(i,e,t,n){const s=typeof e=="string"?a.dist.Buffer.from(e,"hex"):a.dist.Buffer.from(e);if(s.length!=32)throw Error("address.length != 32");const r=a.dist.Buffer.alloc(8);return r.writeBigUInt64BE(typeof n=="number"?BigInt(n):n),ge([s,(()=>{const o=a.dist.Buffer.alloc(2);return o.writeUInt16BE(t),o})(),r],i)}async function rs(i,e,t,n,s,r){return i.getAccountInfo(Ke(e,t,n,s),r).then(o=>!!Me(o)[0])}function pe(i){return ge([a.dist.Buffer.from("Bridge")],i)}async function is(i,e,t){return i.getAccountInfo(pe(e),t).then(n=>pt.deserialize(Me(n)))}class yt{constructor(e,t){W(this,"guardianSetExpirationTime");W(this,"fee");this.guardianSetExpirationTime=e,this.fee=t}static deserialize(e){if(e.length!=12)throw new Error("data.length != 12");const t=e.readUInt32LE(0),n=e.readBigUInt64LE(4);return new yt(t,n)}}class pt{constructor(e,t,n){W(this,"guardianSetIndex");W(this,"lastLamports");W(this,"config");this.guardianSetIndex=e,this.lastLamports=t,this.config=n}static deserialize(e){if(e.length!=24)throw new Error("data.length != 24");const t=e.readUInt32LE(0),n=e.readBigUInt64LE(4),s=yt.deserialize(e.subarray(12));return new pt(t,n,s)}}function mt(i,e){return ge([a.dist.Buffer.from("Sequence"),new y(i).toBytes()],e)}async function os(i,e,t,n){return i.getAccountInfo(mt(e,t),n).then(s=>bt.deserialize(Me(s)))}class bt{constructor(e,t,n){W(this,"sequence");W(this,"bump");W(this,"emitterType");this.sequence=e,this.bump=t,this.emitterType=n}static deserialize(e){if(e.length!==8&&e.length!==10)throw new Error("data.length != 8 or data.length != 10");let t,n;const s=e.readBigUInt64LE(0);return e.length===10&&(t=e[8],n=e[9]),new bt(s,t,n)}value(){return this.sequence}}function Zt(i){return ge([a.dist.Buffer.from("emitter")],i)}function Qt(i,e){const t=Zt(i);return{emitter:t,sequence:mt(t,e)}}async function ao(i,e,t,n){return os(i,Zt(e),t,n)}function De(i){return ge([a.dist.Buffer.from("fee_collector")],i)}const _n=65,Ge=20;function co(i,e,t){return new q({keys:[],programId:Ee.programId,data:uo.serialize(i,e,t)})}class uo{static serialize(e,t,n){if(e.length==0)throw Error("signatures.length == 0");if(e.length!=t.length)throw Error("signatures.length != keys.length");if(n.length!=32)throw Error("message.length != 32");const s=e.length,r=11,o=1+s*r,c=_n+Ge,u=o+s*c,d=32,h=a.dist.Buffer.alloc(u+d);h.writeUInt8(s,0),h.write(n.toString("hex"),u,"hex");for(let g=0;g<s;++g){const S=e.at(g);if((S==null?void 0:S.length)!=_n)throw Error(`signatures[${g}].length != 65`);const f=t.at(g);if((f==null?void 0:f.length)!=Ge)throw Error(`keys[${g}].length != 20`);const b=o+c*g,m=b+65;h.writeUInt16LE(b,1+g*r),h.writeUInt8(0,3+g*r),h.writeUInt16LE(m,4+g*r),h.writeUInt8(0,6+g*r),h.writeUInt16LE(u,7+g*r),h.writeUInt16LE(d,9+g*r),h.writeUInt8(0,10+g*r),h.write(S.toString("hex"),b,"hex"),h.write(f.toString("hex"),m,"hex")}return h}}function ve(i,e){return ge([a.dist.Buffer.from("GuardianSet"),(()=>{const t=a.dist.Buffer.alloc(4);return t.writeUInt32BE(e),t})()],i)}async function en(i,e,t,n){return i.getAccountInfo(ve(e,t),n).then(s=>kt.deserialize(Me(s)))}class kt{constructor(e,t,n,s){W(this,"index");W(this,"keys");W(this,"creationTime");W(this,"expirationTime");this.index=e,this.keys=t,this.creationTime=n,this.expirationTime=s}static deserialize(e){const t=e.readUInt32LE(0),n=e.readUInt32LE(4),s=8+n*Ge,r=e.readUInt32LE(s),o=e.readUInt32LE(4+s),c=[];for(let u=0;u<n;++u){const d=8+u*Ge;c.push(e.subarray(d,d+Ge))}return new kt(t,c,r,o)}}function Ae(i,e){return ge([a.dist.Buffer.from("PostedVAA"),e],i)}async function lo(i,e,t){return i.getAccountInfo(new y(e),t).then(n=>St.deserialize(Me(n)))}class St{constructor(e,t,n){W(this,"signatures");W(this,"hash");W(this,"guardianSetIndex");this.signatures=e,this.hash=t,this.guardianSetIndex=n}static deserialize(e){const t=e.readUInt32LE(0),n=[...e.subarray(4,4+t)].map(c=>c!=0),s=4+t,r=e.subarray(s,s+32),o=e.readUInt32LE(s+32);return new St(n,r,o)}}function tn(i){return ge([a.dist.Buffer.from("upgrade")],i)}function nn(i,e,t){return D.transfer({fromPubkey:new y(e),toPubkey:De(i),lamports:t})}class ho{constructor(e){W(this,"idl");this.idl=e}async encode(e,t){switch(e){default:throw new Error(`Invalid account name: ${e}`)}}decode(e,t){return this.decodeUnchecked(e,t)}decodeUnchecked(e,t){switch(e){default:throw new Error(`Invalid account name: ${e}`)}}memcmp(e,t){switch(e){case"postVaa":return{dataSize:56};default:throw new Error(`Invalid account name: ${e}`)}}size(e){return Kt(this.idl,e)??0}}class fo{constructor(e){}decode(e){throw new Error("Wormhole program does not have events")}}var $={};const go=a.getAugmentedNamespace(oo);(function(i){var e=a.commonjsGlobal&&a.commonjsGlobal.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(i,"__esModule",{value:!0}),i.map=i.array=i.rustEnum=i.str=i.vecU8=i.tagged=i.vec=i.bool=i.option=i.publicKey=i.i256=i.u256=i.i128=i.u128=i.i64=i.u64=i.struct=i.f64=i.f32=i.i32=i.u32=i.i16=i.u16=i.i8=i.u8=void 0;const t=a.Layout,n=go,s=e(a.bnExports);var r=a.Layout;Object.defineProperty(i,"u8",{enumerable:!0,get:function(){return r.u8}}),Object.defineProperty(i,"i8",{enumerable:!0,get:function(){return r.s8}}),Object.defineProperty(i,"u16",{enumerable:!0,get:function(){return r.u16}}),Object.defineProperty(i,"i16",{enumerable:!0,get:function(){return r.s16}}),Object.defineProperty(i,"u32",{enumerable:!0,get:function(){return r.u32}}),Object.defineProperty(i,"i32",{enumerable:!0,get:function(){return r.s32}}),Object.defineProperty(i,"f32",{enumerable:!0,get:function(){return r.f32}}),Object.defineProperty(i,"f64",{enumerable:!0,get:function(){return r.f64}}),Object.defineProperty(i,"struct",{enumerable:!0,get:function(){return r.struct}});class o extends t.Layout{constructor(_,E,L){super(_,L),this.blob=(0,t.blob)(_),this.signed=E}decode(_,E=0){const L=new s.default(this.blob.decode(_,E),10,"le");return this.signed?L.fromTwos(this.span*8).clone():L}encode(_,E,L=0){return this.signed&&(_=_.toTwos(this.span*8)),this.blob.encode(_.toArrayLike(a.dist.Buffer,"le",this.span),E,L)}}function c(v){return new o(8,!1,v)}i.u64=c;function u(v){return new o(8,!0,v)}i.i64=u;function d(v){return new o(16,!1,v)}i.u128=d;function h(v){return new o(16,!0,v)}i.i128=h;function g(v){return new o(32,!1,v)}i.u256=g;function S(v){return new o(32,!0,v)}i.i256=S;class f extends t.Layout{constructor(_,E,L,j){super(_.span,j),this.layout=_,this.decoder=E,this.encoder=L}decode(_,E){return this.decoder(this.layout.decode(_,E))}encode(_,E,L){return this.layout.encode(this.encoder(_),E,L)}getSpan(_,E){return this.layout.getSpan(_,E)}}function b(v){return new f((0,t.blob)(32),_=>new n.PublicKey(_),_=>_.toBuffer(),v)}i.publicKey=b;class m extends t.Layout{constructor(_,E){super(-1,E),this.layout=_,this.discriminator=(0,t.u8)()}encode(_,E,L=0){return _==null?this.discriminator.encode(0,E,L):(this.discriminator.encode(1,E,L),this.layout.encode(_,E,L+1)+1)}decode(_,E=0){const L=this.discriminator.decode(_,E);if(L===0)return null;if(L===1)return this.layout.decode(_,E+1);throw new Error("Invalid option "+this.property)}getSpan(_,E=0){const L=this.discriminator.decode(_,E);if(L===0)return 1;if(L===1)return this.layout.getSpan(_,E+1)+1;throw new Error("Invalid option "+this.property)}}function P(v,_){return new m(v,_)}i.option=P;function T(v){return new f((0,t.u8)(),U,te,v)}i.bool=T;function U(v){if(v===0)return!1;if(v===1)return!0;throw new Error("Invalid bool: "+v)}function te(v){return v?1:0}function ce(v,_){const E=(0,t.u32)("length"),L=(0,t.struct)([E,(0,t.seq)(v,(0,t.offset)(E,-E.span),"values")]);return new f(L,({values:j})=>j,j=>({values:j}),_)}i.vec=ce;function ws(v,_,E){const L=(0,t.struct)([c("tag"),_.replicate("data")]);function j({tag:re,data:Es}){if(!re.eq(v))throw new Error("Invalid tag, expected: "+v.toString("hex")+", got: "+re.toString("hex"));return Es}return new f(L,j,re=>({tag:v,data:re}),E)}i.tagged=ws;function on(v){const _=(0,t.u32)("length"),E=(0,t.struct)([_,(0,t.blob)((0,t.offset)(_,-_.span),"data")]);return new f(E,({data:L})=>L,L=>({data:L}),v)}i.vecU8=on;function Is(v){return new f(on(),_=>_.toString("utf-8"),_=>a.dist.Buffer.from(_,"utf-8"),v)}i.str=Is;function As(v,_,E){const L=(0,t.union)(E??(0,t.u8)(),_);return v.forEach((j,re)=>L.addVariant(re,j,j.property)),L}i.rustEnum=As;function _s(v,_,E){const L=(0,t.struct)([(0,t.seq)(v,_,"values")]);return new f(L,({values:j})=>j,j=>({values:j}),E)}i.array=_s;class Ps extends t.Layout{constructor(_,E,L){super(_.span+E.span,L),this.keyLayout=_,this.valueLayout=E}decode(_,E){E=E||0;const L=this.keyLayout.decode(_,E),j=this.valueLayout.decode(_,E+this.keyLayout.getSpan(_,E));return[L,j]}encode(_,E,L){L=L||0;const j=this.keyLayout.encode(_[0],E,L),re=this.valueLayout.encode(_[1],E,L+j);return j+re}getSpan(_,E){return this.keyLayout.getSpan(_,E)+this.valueLayout.getSpan(_,E)}}function Rs(v,_,E){const L=(0,t.u32)("length"),j=(0,t.struct)([L,(0,t.seq)(new Ps(v,_),(0,t.offset)(L,-L.span),"values")]);return new f(j,({values:re})=>new Map(re),re=>({values:Array.from(re.entries())}),E)}i.map=Rs})($);class Ne{static fieldLayout(e,t){const n=e.name!==void 0?Ve(e.name):void 0;switch(e.type){case"bool":return $.bool(n);case"u8":return $.u8(n);case"i8":return $.i8(n);case"u16":return $.u16(n);case"i16":return $.i16(n);case"u32":return $.u32(n);case"i32":return $.i32(n);case"f32":return $.f32(n);case"u64":return $.u64(n);case"i64":return $.i64(n);case"f64":return $.f64(n);case"u128":return $.u128(n);case"i128":return $.i128(n);case"u256":return $.u256(n);case"i256":return $.i256(n);case"bytes":return $.vecU8(n);case"string":return $.str(n);case"publicKey":return $.publicKey(n);default:{if("vec"in e.type)return $.vec(Ne.fieldLayout({name:void 0,type:e.type.vec},t),n);if("option"in e.type)return $.option(Ne.fieldLayout({name:void 0,type:e.type.option},t),n);if("array"in e.type){let s=e.type.array[0],r=e.type.array[1],o=Ne.fieldLayout({name:void 0,type:s},t);return $.array(o,r,n)}else throw new Error(`Not yet implemented: ${e}`)}}}}class sn{constructor(e){W(this,"ixLayout");this.ixLayout=sn.parseIxLayout(e)}static parseIxLayout(e){const n=(e.instructions?e.instructions:[]).map(s=>{let r=s.args.map(c=>Ne.fieldLayout(c,Array.from([...e.accounts??[],...e.types??[]])));const o=Ve(s.name);return[o,$.struct(r,o)]}).concat(e.instructions.map(s=>{let r=s.args.map(c=>Ne.fieldLayout(c,Array.from([...e.accounts??[],...e.types??[]])));const o=Ve(s.name);return[o,$.struct(r,o)]}));return new Map(n)}encode(e,t){const n=a.dist.Buffer.alloc(1e3),s=Ve(e),r=this.ixLayout.get(s);if(!r)throw new Error(`Unknown method: ${s}`);const o=r.encode(t,n),c=n.slice(0,o);return yo(ot[Ns(s)],c)}encodeState(e,t){throw new Error("Wormhole program does not have state")}decode(e,t="hex"){var c;typeof e=="string"&&(e=t==="hex"?a.dist.Buffer.from(e,"hex"):a.b58.decode(e));let n=a.dist.Buffer.from(e.slice(0,1)).readInt8(),s=a.dist.Buffer.from(e.slice(1)),r=Ve(ot[n]??"");return this.ixLayout.get(r)?{data:(c=this.ixLayout.get(r))==null?void 0:c.decode(s),name:r}:null}}var ot;(function(i){i[i.Initialize=0]="Initialize",i[i.PostMessage=1]="PostMessage",i[i.PostVaa=2]="PostVaa",i[i.SetFees=3]="SetFees",i[i.TransferFees=4]="TransferFees",i[i.UpgradeContract=5]="UpgradeContract",i[i.UpgradeGuardianSet=6]="UpgradeGuardianSet",i[i.VerifySignatures=7]="VerifySignatures",i[i.PostMessageUnreliable=8]="PostMessageUnreliable"})(ot||(ot={}));function yo(i,e){const t=a.dist.Buffer.alloc(1+(e===void 0?0:e.length));return t.writeUInt8(i,0),e!==void 0&&t.write(e.toString("hex"),1,"hex"),t}class po{constructor(e){}encode(e,t){throw new Error("Wormhole program does not have state")}decode(e){throw new Error("Wormhole program does not have state")}}class mo{constructor(e){}encode(e,t){throw new Error("Wormhole program does not have user-defined types")}decode(e,t){throw new Error("Wormhole program does not have user-defined types")}}class bo{constructor(e){W(this,"instruction");W(this,"accounts");W(this,"state");W(this,"events");W(this,"types");this.instruction=new sn(e),this.accounts=new ho(e),this.state=new po(e),this.events=new fo(e),this.types=new mo(e)}}const rn={version:"0.1.0",name:"wormhole",instructions:[{name:"initialize",accounts:[{name:"bridge",isMut:!0,isSigner:!1},{name:"guardianSet",isMut:!0,isSigner:!1},{name:"feeCollector",isMut:!0,isSigner:!1},{name:"payer",isMut:!0,isSigner:!0},{name:"clock",isMut:!1,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1}],args:[{name:"guardianSetExpirationTime",type:"u32"},{name:"fee",type:"u64"},{name:"initialGuardians",type:{vec:{array:["u8",20]}}}]},{name:"postMessage",accounts:[{name:"bridge",isMut:!0,isSigner:!1},{name:"message",isMut:!0,isSigner:!0},{name:"emitter",isMut:!1,isSigner:!0},{name:"sequence",isMut:!0,isSigner:!1},{name:"payer",isMut:!0,isSigner:!0},{name:"feeCollector",isMut:!0,isSigner:!1},{name:"clock",isMut:!1,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1}],args:[{name:"nonce",type:"u32"},{name:"payload",type:"bytes"},{name:"consistencyLevel",type:"u8"}]},{name:"postVaa",accounts:[{name:"guardianSet",isMut:!1,isSigner:!1},{name:"bridge",isMut:!1,isSigner:!1},{name:"signatureSet",isMut:!1,isSigner:!1},{name:"vaa",isMut:!0,isSigner:!1},{name:"payer",isMut:!0,isSigner:!0},{name:"clock",isMut:!1,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1}],args:[{name:"version",type:"u8"},{name:"guardianSetIndex",type:"u32"},{name:"timestamp",type:"u32"},{name:"nonce",type:"u32"},{name:"emitterChain",type:"u16"},{name:"emitterAddress",type:{array:["u8",32]}},{name:"sequence",type:"u64"},{name:"consistencyLevel",type:"u8"},{name:"payload",type:"bytes"}]},{name:"setFees",accounts:[{name:"payer",isMut:!0,isSigner:!0},{name:"bridge",isMut:!0,isSigner:!1},{name:"vaa",isMut:!1,isSigner:!1},{name:"claim",isMut:!0,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1}],args:[]},{name:"transferFees",accounts:[{name:"payer",isMut:!0,isSigner:!0},{name:"bridge",isMut:!0,isSigner:!1},{name:"vaa",isMut:!1,isSigner:!1},{name:"claim",isMut:!0,isSigner:!1},{name:"feeCollector",isMut:!0,isSigner:!1},{name:"recipient",isMut:!0,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1}],args:[]},{name:"upgradeContract",accounts:[{name:"payer",isMut:!0,isSigner:!0},{name:"bridge",isMut:!0,isSigner:!1},{name:"vaa",isMut:!1,isSigner:!1},{name:"claim",isMut:!0,isSigner:!1},{name:"upgradeAuthority",isMut:!1,isSigner:!1},{name:"spill",isMut:!0,isSigner:!1},{name:"implementation",isMut:!0,isSigner:!1},{name:"programData",isMut:!0,isSigner:!1},{name:"wormholeProgram",isMut:!0,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1},{name:"clock",isMut:!1,isSigner:!1},{name:"bpfLoaderUpgradeable",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1}],args:[]},{name:"upgradeGuardianSet",accounts:[{name:"payer",isMut:!0,isSigner:!0},{name:"bridge",isMut:!0,isSigner:!1},{name:"vaa",isMut:!1,isSigner:!1},{name:"claim",isMut:!0,isSigner:!1},{name:"guardianSetOld",isMut:!0,isSigner:!1},{name:"guardianSetNew",isMut:!0,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1}],args:[]},{name:"verifySignatures",accounts:[{name:"payer",isMut:!0,isSigner:!0},{name:"guardianSet",isMut:!1,isSigner:!1},{name:"signatureSet",isMut:!0,isSigner:!0},{name:"instructions",isMut:!1,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1}],args:[{name:"signatureStatus",type:{array:["i8",19]}}]},{name:"postMessageUnreliable",accounts:[{name:"bridge",isMut:!0,isSigner:!1},{name:"message",isMut:!0,isSigner:!0},{name:"emitter",isMut:!1,isSigner:!0},{name:"sequence",isMut:!0,isSigner:!1},{name:"payer",isMut:!0,isSigner:!0},{name:"feeCollector",isMut:!0,isSigner:!1},{name:"clock",isMut:!1,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1}],args:[{name:"nonce",type:"u32"},{name:"payload",type:"bytes"},{name:"consistencyLevel",type:"u8"}]}],accounts:[{name:"PostedMessage",type:{kind:"struct",fields:[{name:"vaaVersion",type:"u8"},{name:"consistencyLevel",type:"u8"},{name:"vaaTime",type:"u32"},{name:"vaaSignatureAccount",type:"publicKey"},{name:"submissionTime",type:"u32"},{name:"nonce",type:"u32"},{name:"sequence",type:"u64"},{name:"emitterChain",type:"u16"},{name:"emitterAddress",type:{array:["u8",32]}},{name:"payload",type:"bytes"}]}},{name:"PostedVAA",type:{kind:"struct",fields:[{name:"vaaVersion",type:"u8"},{name:"consistencyLevel",type:"u8"},{name:"vaaTime",type:"u32"},{name:"vaaSignatureAccount",type:"publicKey"},{name:"submissionTime",type:"u32"},{name:"nonce",type:"u32"},{name:"sequence",type:"u64"},{name:"emitterChain",type:"u16"},{name:"emitterAddress",type:{array:["u8",32]}},{name:"payload",type:"bytes"}]}}]};function as(i,e){return new a.Program(rn,new y(i),e===void 0?{connection:null}:e,cs())}function me(i,e){return as(i,vs.createReadOnlyProvider(e))}function cs(){return new bo(rn)}function ko(i,e,t,n){const s=me(e,i).methods.setFees();return s._ixFn(...s._args,{accounts:us(e,t,n),signers:void 0,remainingAccounts:void 0,preInstructions:void 0,postInstructions:void 0})}function us(i,e,t){return{payer:new y(e),bridge:pe(i),vaa:Ae(i,a.dist.Buffer.from(t.hash)),claim:Ke(i,t.emitterAddress.toString(),a.toChainId(t.emitterChain),t.sequence),systemProgram:D.programId}}function So(i,e,t,n,s){const r=me(e,i).methods.transferFees();return r._ixFn(...r._args,{accounts:ls(e,t,n,s),signers:void 0,remainingAccounts:void 0,preInstructions:void 0,postInstructions:void 0})}function ls(i,e,t,n){return{payer:new y(e),bridge:pe(i),vaa:Ae(i,a.dist.Buffer.from(n.hash)),claim:Ke(i,n.emitterAddress.toString(),a.toChainId(n.emitterChain),n.sequence),feeCollector:De(i),recipient:new y(t),rent:ie,systemProgram:D.programId}}function wo(i,e,t,n){const s=me(e,i).methods.upgradeGuardianSet();return s._ixFn(...s._args,{accounts:ds(e,t,n),signers:void 0,remainingAccounts:void 0,preInstructions:void 0,postInstructions:void 0})}function ds(i,e,t){return{payer:new y(e),bridge:pe(i),vaa:Ae(i,a.dist.Buffer.from(t.hash)),claim:Ke(i,t.emitterAddress.toString(),a.toChainId(t.emitterChain),t.sequence),guardianSetOld:ve(i,t.guardianSet),guardianSetNew:ve(i,t.guardianSet+1),systemProgram:D.programId}}function Io(i,e,t,n){const s=me(e,i).methods.upgradeContract();return s._ixFn(...s._args,{accounts:hs(e,t,n),signers:void 0,remainingAccounts:void 0,preInstructions:void 0,postInstructions:void 0})}function hs(i,e,t,n){const{newContract:s}=t.payload;return{payer:new y(e),bridge:pe(i),vaa:Ae(i,a.dist.Buffer.from(t.hash)),claim:Ke(i,t.emitterAddress.toString(),a.toChainId(t.emitterChain),t.sequence),upgradeAuthority:tn(i),spill:new y(n===void 0?e:n),implementation:new se.SolanaAddress(s).unwrap(),programData:Rn(i),wormholeProgram:new y(i),rent:ie,clock:Q,bpfLoaderUpgradeable:at.programId,systemProgram:D.programId}}function Ao(i,e,t,n,s,r){const o=me(e,i).methods.initialize(n,new a.BN(s.toString()),[...r.map(c=>[...new Uint8Array(c)])]);return o._ixFn(...o._args,{accounts:fs(e,t),signers:void 0,remainingAccounts:void 0,preInstructions:void 0,postInstructions:void 0})}function fs(i,e){return{bridge:pe(i),guardianSet:ve(i,0),feeCollector:De(i),payer:new y(e),clock:Q,rent:ie,systemProgram:D.programId}}function gs(i,e,t,n,s,r,o){const c=me(e,i).methods.postMessage(r,a.dist.Buffer.from(s),o);return c._ixFn(...c._args,{accounts:wt(e,t,n),signers:void 0,remainingAccounts:void 0,preInstructions:void 0,postInstructions:void 0})}function wt(i,e,t,n){let s;return n?{emitter:n,sequence:s}=Qt(n,i):(n=e,s=mt(n,i)),{bridge:pe(i),message:new y(t),emitter:new y(n),sequence:s,payer:new y(e),feeCollector:De(i),clock:Q,rent:ie,systemProgram:D.programId}}function ys(i,e,t,n,s){const r=me(e,i).methods.postVaa(1,n.guardianSet,n.timestamp,n.nonce,a.toChainId(n.emitterChain),[...n.emitterAddress.toUint8Array()],new a.BN(n.sequence.toString()),n.consistencyLevel,a.dist.Buffer.from(a.serializePayload(n.payloadLiteral,n.payload)));return r._ixFn(...r._args,{accounts:ps(e,t,s,n),signers:void 0,remainingAccounts:void 0,preInstructions:void 0,postInstructions:void 0})}function ps(i,e,t,n){return{guardianSet:ve(i,n.guardianSet),bridge:pe(i),signatureSet:new y(t),vaa:Ae(i,a.dist.Buffer.from(n.hash)),payer:new y(e),clock:Q,rent:ie,systemProgram:D.programId}}const _o=19;async function ms(i,e,t,n,s,r){const o=n.guardianSet,c=await en(i,e,o,r),u=n.signatures,d=c.keys,h=7,g=[];for(let S=0;S<Math.ceil(u.length/h);++S){const f=S*h,b=Math.min(u.length,(S+1)*h),m=new Array(_o).fill(-1),P=[],T=[];for(let U=0;U<b-f;++U){const te=u.at(U+f);P.push(a.dist.Buffer.from(te.signature.encode())),T.push(d.at(te.guardianIndex)),m[te.guardianIndex]=U}g.push(co(P,T,a.dist.Buffer.from(n.hash))),g.push(Po(i,e,t,n,s,m))}return g}function Po(i,e,t,n,s,r){const o=me(e,i).methods.verifySignatures(r);return o._ixFn(...o._args,{accounts:bs(e,t,s,n),signers:void 0,remainingAccounts:void 0,preInstructions:void 0,postInstructions:void 0})}function bs(i,e,t,n){return{payer:new y(e),guardianSet:ve(i,n.guardianSet),signatureSet:new y(t),instructions:Nn,rent:ie,systemProgram:D.programId}}function ks(i,e){const{emitter:t,sequence:n}=Qt(i,e);return{wormholeBridge:pe(e),wormholeEmitter:t,wormholeSequence:n,wormholeFeeCollector:De(e)}}function Ss(i,e,t,n){const s=wt(e,t,n,i);return{payer:s.payer,wormholeBridge:s.bridge,wormholeMessage:s.message,wormholeEmitter:s.emitter,wormholeSequence:s.sequence,wormholeFeeCollector:s.feeCollector,clock:s.clock,rent:s.rent,systemProgram:s.systemProgram}}const Ro=Object.freeze(Object.defineProperty({__proto__:null,BridgeConfig:yt,BridgeData:pt,GuardianSetData:kt,SequenceTracker:bt,SignatureSetData:St,coder:cs,createBridgeFeeTransferInstruction:nn,createInitializeInstruction:Ao,createPostMessageInstruction:gs,createPostVaaInstruction:ys,createReadOnlyWormholeProgramInterface:me,createSetFeesInstruction:ko,createTransferFeesInstruction:So,createUpgradeContractInstruction:Io,createUpgradeGuardianSetInstruction:wo,createVerifySignaturesInstructions:ms,createWormholeProgramInterface:as,deriveClaimKey:Ke,deriveEmitterSequenceKey:mt,deriveFeeCollectorKey:De,deriveGuardianSetKey:ve,derivePostedVaaKey:Ae,deriveUpgradeAuthorityKey:tn,deriveWormholeBridgeDataKey:pe,deriveWormholeEmitterKey:Zt,getClaim:rs,getEmitterKeys:Qt,getGuardianSet:en,getInitializeAccounts:fs,getPostMessageAccounts:wt,getPostMessageCpiAccounts:Ss,getPostVaaAccounts:ps,getProgramSequenceTracker:ao,getSequenceTracker:os,getSetFeesAccounts:us,getSignatureSetData:lo,getTransferFeesAccounts:ls,getUpgradeContractAccounts:hs,getUpgradeGuardianSetAccounts:ds,getVerifySignatureAccounts:bs,getWormholeBridgeData:is,getWormholeDerivedAccounts:ks},Symbol.toStringTag,{value:"Module"})),Pn="Program log: Sequence: ";class Oe{constructor(e,t,n,s){W(this,"network");W(this,"chain");W(this,"connection");W(this,"contracts");W(this,"chainId");W(this,"coreBridge");W(this,"address");W(this,"bridgeData");this.network=e,this.chain=t,this.connection=n,this.contracts=s,this.chainId=a.toChainId(t);const r=s.coreBridge;if(!r)throw new Error(`CoreBridge contract Address for chain ${t} not found`);this.address=r,this.coreBridge=me(r,n)}async getGuardianSet(e){const t=await en(this.connection,this.coreBridge.programId,e);return{index:t.index,keys:t.keys.map(n=>n.toString("hex")),expiry:BigInt(t.expirationTime)}}static async fromRpc(e,t){const[n,s]=await se.SolanaPlatform.chainFromRpc(e),r=t[s];if(r.network!==n)throw new Error(`Network mismatch for chain ${s}: ${r.network} != ${n}`);return new Oe(n,s,e,t[s].contracts)}async ensureBridgeConfig(){this.bridgeData||(this.bridgeData=await is(this.connection,this.coreBridge.programId))}async getMessageFee(){return await this.ensureBridgeConfig(),this.bridgeData.config.fee}async getGuardianSetIndex(){return await this.ensureBridgeConfig(),this.bridgeData.guardianSetIndex}async*publishMessage(e,t,n,s){const r=Ie.generate(),o=new se.SolanaAddress(e).unwrap(),c=gs(this.connection,this.coreBridge.programId,o,r.publicKey,t,n,s),u=await this.getMessageFee(),d=nn(this.coreBridge.programId,o,u),h=new N;h.feePayer=o,h.add(d,c),yield this.createUnsignedTx({transaction:h,signers:[r]},"Core.PublishMessage")}async*verifyMessage(e,t){yield*this.postVaa(e,t)}async*postVaa(e,t){const n=Ae(this.coreBridge.programId,a.dist.Buffer.from(t.hash));if(await this.connection.getAccountInfo(n))return;const r=new se.SolanaAddress(e).unwrap(),o=Ie.generate(),c=await ms(this.connection,this.coreBridge.programId,r,t,o.publicKey);for(let d=0;d<c.length;d+=2){const h=new N().add(...c.slice(d,d+2));h.feePayer=r,yield this.createUnsignedTx({transaction:h,signers:[o]},"Core.VerifySignature",!0)}const u=new N().add(ys(this.connection,this.coreBridge.programId,r,t,o.publicKey));u.feePayer=r,yield this.createUnsignedTx({transaction:u},"Core.PostVAA")}static parseSequenceFromLog(e,t){var u,d,h,g;const{meta:n,transaction:{message:s}}=t;if(!((u=n==null?void 0:n.innerInstructions)!=null&&u.length))return[];const r=s.staticAccountKeys;if(r.filter(S=>S.toString()===e).length===0)return[];const o=(g=(h=(d=n==null?void 0:n.logMessages)==null?void 0:d.filter(S=>S.startsWith(Pn)))==null?void 0:h[0])==null?void 0:g.replace(Pn,"");if(!o)return[];const c=[];for(const S of n==null?void 0:n.innerInstructions){const f=S.instructions;c.push(...f.filter(b=>b.programIdIndex in r&&r[b.programIdIndex].toString()===e))}return c.length<1?[]:r.length<3?[]:c.map(S=>[new se.SolanaAddress(r[S.accounts[2]]).toUniversalAddress(),BigInt(o)]).filter(S=>S!==null)}async getMessageAccountKeys(e){let t;if(typeof e.transaction.message.version!="string")if(e.meta.loadedAddresses)t=e.transaction.message.getAccountKeys({accountKeysFromLookups:e.meta.loadedAddresses});else{const n=await Promise.all(e.transaction.message.addressTableLookups.map(async s=>{const r=await this.connection.getAddressLookupTable(s.accountKey);if(!r||!r.value)throw new Error("Could not resolve lookup table: "+s.accountKey.toBase58());return r.value}));t=e.transaction.message.getAccountKeys({addressLookupTableAccounts:n})}else t=e.transaction.message.getAccountKeys();return t}async findInstructions(e,t){var u;const{meta:n,transaction:{message:s}}=t,r=this.coreBridge.programId,o=(u=n.innerInstructions)==null?void 0:u.flatMap(d=>d.instructions.filter(h=>r.toString()===e.get(h.programIdIndex).toString())).map(d=>({programIdIndex:d.programIdIndex,accountKeyIndexes:d.accounts})),c=s.compiledInstructions.filter(d=>r.toString()===e.get(d.programIdIndex).toString());return[...o,...c]}async parsePostMessageAccount(e){const t=await this.connection.getAccountInfo(e);if(!(t!=null&&t.data))throw new Error("No data found in message account");const{timestamp:n,emitterAddress:s,emitterChain:r,consistencyLevel:o,sequence:c,nonce:u,payload:d}=ss(new Uint8Array(t==null?void 0:t.data));return Ls.createVAA("Uint8Array",{guardianSet:await this.getGuardianSetIndex(),emitterChain:a.toChain(r),timestamp:n,emitterAddress:s,consistencyLevel:o,sequence:c,nonce:u,payload:d,signatures:[]})}async parseTransaction(e){const t=await this.connection.getTransaction(e,{maxSupportedTransactionVersion:0});if(!t||!t.meta||!t.meta.innerInstructions)throw new Error("transaction not found");try{const o=Oe.parseSequenceFromLog(this.coreBridge.programId.toBase58(),t);if(o.length>0){const[c,u]=o[0];return[{chain:this.chain,emitter:c,sequence:u}]}}catch{}const n=await this.getMessageAccountKeys(t),s=await this.findInstructions(n,t);if(!s||s.length===0)throw new Error("no bridge messages found");const r=s.map(async o=>{const c=n.get(o.accountKeyIndexes[1]),u=await this.parsePostMessageAccount(c);return{chain:u.emitterChain,emitter:u.emitterAddress,sequence:u.sequence}});return await Promise.all(r)}async parseMessages(e){const t=await this.connection.getTransaction(e,{maxSupportedTransactionVersion:0});if(!t||!t.meta||!t.meta.innerInstructions)throw new Error("transaction not found");const n=await this.getMessageAccountKeys(t),s=await this.findInstructions(n,t);if(!s||s.length===0)throw new Error("no bridge messages found");const r=s.map(async o=>{const c=n.get(o.accountKeyIndexes[1]);return await this.parsePostMessageAccount(c)});return await Promise.all(r)}createUnsignedTx(e,t,n=!1){return new se.SolanaUnsignedTransaction(e,this.network,this.chain,t,n)}}Cs.registerProtocol(se._platform,"WormholeCore",Oe);const Eo=Object.freeze(Object.defineProperty({__proto__:null,IDL:rn,SolanaWormholeCore:Oe,deserializePostMessage:ss,postMessageLayout:ns,utils:Ro},Symbol.toStringTag,{value:"Module"}));exports.BpfLoaderUpgradeable=at;exports.SolanaWormholeCore=Oe;exports.accountSize=Kt;exports.createBridgeFeeTransferInstruction=nn;exports.deriveAddress=ge;exports.deriveClaimKey=Ke;exports.derivePostedVaaKey=Ae;exports.deriveUpgradeAuthorityKey=tn;exports.deriveUpgradeableProgramKey=Rn;exports.getAccountData=Me;exports.getClaim=rs;exports.getPostMessageAccounts=wt;exports.getPostMessageCpiAccounts=Ss;exports.getWormholeDerivedAccounts=ks;exports.index=Eo;exports.newAccountMeta=xs;exports.newReadOnlyAccountMeta=Ks;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./solana
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./solana--YauUjmQ.js"),e=require("./index-C1oy9Lkm.js");class s extends Error{constructor(t){super(t)}}class n extends s{constructor(){super(...arguments),this.name="TokenOwnerOffCurveError"}}const u=e.struct([e.u32("mintAuthorityOption"),e.publicKey("mintAuthority"),e.u64("supply"),e.u8("decimals"),e.bool("isInitialized"),e.u32("freezeAuthorityOption"),e.publicKey("freezeAuthority")]);u.span;async function f(o,t,i=!1,O=r.TOKEN_PROGRAM_ID,c=r.ASSOCIATED_TOKEN_PROGRAM_ID){if(!i&&!r.PublicKey.isOnCurve(t.toBuffer()))throw new n;const[a]=await r.PublicKey.findProgramAddress([t.toBuffer(),O.toBuffer(),o.toBuffer()],c);return a}exports.ASSOCIATED_TOKEN_PROGRAM_ID=r.ASSOCIATED_TOKEN_PROGRAM_ID;exports.TOKEN_PROGRAM_ID=r.TOKEN_PROGRAM_ID;exports.MintLayout=u;exports.TokenError=s;exports.TokenOwnerOffCurveError=n;exports.getAssociatedTokenAddress=f;
|