1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[861],{9828:function(t,e,r){r.d(e,{$r:function(){return Program}});var n,o,i,s,a=r(48764),c=r(99161),u=r(13550),l=r.n(u),d=r(77191),h=r.n(d),_=r(84037),p=r.n(_),f=r(15970),R=(r(15702),r(27885)),y=r(26729),A=r.n(y),E=r(48764).Buffer;function chunks(t,e){return Array.apply(0,Array(Math.ceil(t.length/e))).map((r,n)=>t.slice(n*e,(n+1)*e))}let isVersionedTransaction=t=>"version"in t;function decode$2(t){let e=new TextDecoder("utf-8");return e.decode(t)}function encode$1(t){return h().encode(t)}function encode(t){return t.toString("base64")}function decode(t){return a.Buffer.from(t,"base64")}function isCompositeAccounts(t){return"accounts"in t}async function idlAddress(t){let e=(await c.PublicKey.findProgramAddress([],t))[0];return await c.PublicKey.createWithSeed(e,seed(),t)}function seed(){return"anchor:idl"}let m=f.struct([f.publicKey("authority"),f.vecU8("data")]);function decodeIdlAccount(t){return m.decode(t)}function convertIdlToCamelCase(t){let e=["name","path","account","relations","generic"],toCamelCase=t=>t.split(".").map(p()).join("."),recursivelyConvertNamesToCamelCase=t=>{for(let r in t){let n=t[r];e.includes(r)?t[r]=Array.isArray(n)?n.map(toCamelCase):toCamelCase(n):"object"==typeof n&&recursivelyConvertNamesToCamelCase(n)}},r=structuredClone(t);return recursivelyConvertNamesToCamelCase(r),r}function handleDefinedFields(t,e,r,n){return(null==t?void 0:t.length)?t[0].name?r(t):n(t):e()}function parseIdlErrors(t){let e=new Map;return t.errors&&t.errors.forEach(t=>{var r;let n=null!==(r=t.msg)&&void 0!==r?r:t.name;e.set(t.code,n)}),e}function toInstruction(t,...e){if(t.args.length!=e.length)throw Error("Invalid argument length");let r={},n=0;return t.args.forEach(t=>{r[t.name]=e[n],n+=1}),r}function validateAccounts(t,e={}){t.forEach(t=>{if(isCompositeAccounts(t))validateAccounts(t.accounts,e[t.name]);else if(!e[t.name])throw Error(`Account \`${t.name}\` not provided.`)})}function translateAddress(t){return t instanceof c.PublicKey?t:new c.PublicKey(t)}let StructError=class StructError extends TypeError{constructor(t,e){let r;let{message:n,...o}=t,{path:i}=t,s=0===i.length?n:"At path: "+i.join(".")+" -- "+n;super(s),this.value=void 0,this.key=void 0,this.type=void 0,this.refinement=void 0,this.path=void 0,this.branch=void 0,this.failures=void 0,Object.assign(this,o),this.name=this.constructor.name,this.failures=()=>{var n;return null!=(n=r)?n:r=[t,...e()]}}};function isIterable(t){return isObject(t)&&"function"==typeof t[Symbol.iterator]}function isObject(t){return"object"==typeof t&&null!=t}function print(t){return"string"==typeof t?JSON.stringify(t):""+t}function shiftIterator(t){let{done:e,value:r}=t.next();return e?void 0:r}function toFailure(t,e,r,n){if(!0===t)return;!1===t?t={}:"string"==typeof t&&(t={message:t});let{path:o,branch:i}=e,{type:s}=r,{refinement:a,message:c="Expected a value of type `"+s+"`"+(a?" with refinement `"+a+"`":"")+", but received: `"+print(n)+"`"}=t;return{value:n,type:s,refinement:a,key:o[o.length-1],path:o,branch:i,...t,message:c}}function*toFailures(t,e,r,n){for(let o of(isIterable(t)||(t=[t]),t)){let t=toFailure(o,e,r,n);t&&(yield t)}}function*run(t,e,r){void 0===r&&(r={});let{path:n=[],branch:o=[t],coerce:i=!1,mask:s=!1}=r,a={path:n,branch:o};if(i&&(t=e.coercer(t,a),s&&"type"!==e.type&&isObject(e.schema)&&isObject(t)&&!Array.isArray(t)))for(let r in t)void 0===e.schema[r]&&delete t[r];let c=!0;for(let r of e.validator(t,a))c=!1,yield[r,void 0];for(let[r,u,l]of e.entries(t,a)){let e=run(u,l,{path:void 0===r?n:[...n,r],branch:void 0===r?o:[...o,u],coerce:i,mask:s});for(let n of e)n[0]?(c=!1,yield[n[0],void 0]):i&&(u=n[1],void 0===r?t=u:t instanceof Map?t.set(r,u):t instanceof Set?t.add(u):isObject(t)&&(t[r]=u))}if(c)for(let r of e.refiner(t,a))c=!1,yield[r,void 0];c&&(yield[void 0,t])}let Struct=class Struct{constructor(t){this.TYPE=void 0,this.type=void 0,this.schema=void 0,this.coercer=void 0,this.validator=void 0,this.refiner=void 0,this.entries=void 0;let{type:e,schema:r,validator:n,refiner:o,coercer:i=t=>t,entries:s=function*(){}}=t;this.type=e,this.schema=r,this.entries=s,this.coercer=i,n?this.validator=(t,e)=>{let r=n(t,e);return toFailures(r,e,this,t)}:this.validator=()=>[],o?this.refiner=(t,e)=>{let r=o(t,e);return toFailures(r,e,this,t)}:this.refiner=()=>[]}assert(t){return assert(t,this)}create(t){return create(t,this)}is(t){return is(t,this)}mask(t){return mask(t,this)}validate(t,e){return void 0===e&&(e={}),validate(t,this,e)}};function assert(t,e){let r=validate(t,e);if(r[0])throw r[0]}function create(t,e){let r=validate(t,e,{coerce:!0});if(!r[0])return r[1];throw r[0]}function mask(t,e){let r=validate(t,e,{coerce:!0,mask:!0});if(!r[0])return r[1];throw r[0]}function is(t,e){let r=validate(t,e);return!r[0]}function validate(t,e,r){void 0===r&&(r={});let n=run(t,e,r),o=shiftIterator(n);if(o[0]){let t=new StructError(o[0],function*(){for(let t of n)t[0]&&(yield t[0])});return[t,void 0]}
1{let t=o[1];return[void 0,t]}}function define(t,e){return new Struct({type:t,schema:null,validator:e})}function any(){return define("any",()=>!0)}function array(t){return new Struct({type:"array",schema:t,*entries(e){if(t&&Array.isArray(e))for(let[r,n]of e.entries())yield[r,n,t]},coercer:t=>Array.isArray(t)?t.slice():t,validator:t=>Array.isArray(t)||"Expected an array value, but received: "+print(t)})}function boolean(){return define("boolean",t=>"boolean"==typeof t)}function literal(t){let e=print(t),r=typeof t;return new Struct({type:"literal",schema:"string"===r||"number"===r||"boolean"===r?t:null,validator:r=>r===t||"Expected the literal `"+e+"`, but received: "+print(r)})}function nullable(t){return new Struct({...t,validator:(e,r)=>null===e||t.validator(e,r),refiner:(e,r)=>null===e||t.refiner(e,r)})}function number(){return define("number",t=>"number"==typeof t&&!isNaN(t)||"Expected a number, but received: "+print(t))}function optional(t){return new Struct({...t,validator:(e,r)=>void 0===e||t.validator(e,r),refiner:(e,r)=>void 0===e||t.refiner(e,r)})}function string(){return define("string",t=>"string"==typeof t||"Expected a string, but received: "+print(t))}function type(t){let e=Object.keys(t);return new Struct({type:"type",schema:t,*entries(r){if(isObject(r))for(let n of e)yield[n,r[n],t[n]]},validator:t=>isObject(t)||"Expected an object, but received: "+print(t)})}function union$1(t){let e=t.map(t=>t.type).join(" | ");return new Struct({type:"union",schema:null,coercer(e,r){let n=t.find(t=>{let[r]=t.validate(e,{coerce:!0});return!r})||unknown();return n.coercer(e,r)},validator(r,n){let o=[];for(let e of t){let[...t]=run(r,e,n),[i]=t;if(!i[0])return[];for(let[e]of t)e&&o.push(e)}return["Expected the value to satisfy a union of `"+e+"`, but received: "+print(r),...o]}})}function unknown(){return define("unknown",()=>!0)}function coerce(t,e,r){return new Struct({...t,coercer:(n,o)=>is(n,e)?t.coercer(r(n,o),o):t.coercer(n,o)})}async function getMultipleAccountsAndContext(t,e,r){if(e.length<=99)return await getMultipleAccountsAndContextCore(t,e,r);{let n=chunks(e,99),o=await Promise.all(n.map(e=>getMultipleAccountsAndContextCore(t,e,r)));return o.flat()}}async function getMultipleAccountsAndContextCore(t,e,r){let n=null!=r?r:t.commitment,{value:o,context:i}=await t.getMultipleAccountsInfoAndContext(e,n),s=o.map((t,r)=>null===t?null:{publicKey:e[r],account:t,context:i});return s}async function simulateTransaction(t,e,r,n,o){var i;r&&r.length>0&&e.sign(...r);let s=e._compile(),a=s.serialize(),u=e._serialize(a),l=u.toString("base64"),d={encoding:"base64",commitment:null!=n?n:t.commitment};if(o){let t=(Array.isArray(o)?o:s.nonProgramIds()).map(t=>
1t.toBase58());d.accounts={encoding:"base64",addresses:t}}r&&r.length>0&&(d.sigVerify=!0);let h=[l,d],_=await t._rpcRequest("simulateTransaction",h),p=create(_,N);if("error"in p){let t;if("data"in p.error&&(t=null===(i=p.error.data)||void 0===i?void 0:i.logs)&&Array.isArray(t)){let e="\n ",r=e+t.join(e);console.error(p.error.message,r)}throw new c.SendTransactionError("failed to simulate transaction: "+p.error.message,t)}return p.result}function jsonRpcResult(t){return coerce(createRpcResult(t),O,e=>"error"in e?e:{...e,result:create(e.result,t)})}let O=createRpcResult(unknown());function createRpcResult(t){return union$1([type({jsonrpc:literal("2.0"),id:string(),result:t}),type({jsonrpc:literal("2.0"),id:string(),error:type({code:unknown(),message:string(),data:optional(any())})})])}function jsonRpcResultAndContext(t){return jsonRpcResult(type({context:type({slot:number()}),value:t}))}let N=jsonRpcResultAndContext(type({err:nullable(union$1([type({}),string()])),logs:nullable(array(string())),accounts:optional(nullable(array(nullable(type({executable:boolean(),owner:string(),lamports:number(),data:array(string()),rentEpoch:optional(number())}))))),unitsConsumed:optional(number())}));let AnchorProvider=class AnchorProvider{constructor(t,e,r=AnchorProvider.defaultOptions()){this.connection=t,this.wallet=e,this.opts=r,this.publicKey=null==e?void 0:e.publicKey}static defaultOptions(){return{preflightCommitment:"processed",commitment:"processed"}}static local(t,e=AnchorProvider.defaultOptions()){throw Error("Provider local is not available on browser.")}static env(){throw Error("Provider env is not available on browser.")}async sendAndConfirm(t,e,r){var n,o,i,s;if(void 0===r&&(r=this.opts),isVersionedTransaction(t))e&&t.sign(e);else if(t.feePayer=null!==(n=t.feePayer)&&void 0!==n?n:this.wallet.publicKey,t.recentBlockhash=(await this.connection.getLatestBlockhash(r.preflightCommitment)).blockhash,e)for(let r of e)t.partialSign(r);t=await this.wallet.signTransaction(t);let a=t.serialize();try{return await sendAndConfirmRawTransaction(this.connection,a,r)}catch(e){if(e instanceof ConfirmError){let r=encode$1(isVersionedTransaction(t)?(null===(o=t.signatures)||void 0===o?void 0:o[0])||new Uint8Array:null!==(i=t.signature)&&void 0!==i?i:new Uint8Array),n=isVersionedTransaction(t)?0:void 0,a=await this.connection.getTransaction(r,{commitment:"confirmed",maxSupportedTransactionVersion:n});if(a){let t=null===(s=a.meta)||void 0===s?void 0:s.logMessages;throw t?new c.SendTransactionError(e.message,t):e}}throw e}}async sendAll(t,e){var r,n,o;void 0===e&&(e=this.opts);let i=(await this.connection.getLatestBlockhash(e.preflightCommitment)).blockhash,s=t.map(t=>{var e,r;if(isVersionedTransaction(t.tx)){let e=t.tx;return t.signers&&e.sign(t.signers),e}{let n=t.tx,o=null!==(e=t.signers)&&void 0!==e?e:[];return n.feePayer=null!==(r=n.feePayer)&&void 0!==r?r:this.wallet.publicKey,n.recentBlockhash=i,o.forEach(t=>{n.partialSign(t)}),n}}),a=await this.wallet.signAllTransactions(s),u=[];for(let t=0;t<s.length;t+=1){let i=a[t],s=i.serialize();try{u.push(await sendAndConfirmRawTransaction(this.connection,s,e))}catch(t){if(t instanceof ConfirmError){let e=encode$1(isVersionedTransaction(i)?(null===(r=i.signatures)||void 0===r?void 0:r[0])||new Uint8Array:null!==(n=i.signature)&&void 0!==n?n:new Uint8Array),s=isVersionedTransaction(i)?0:void 0,a=await this.connection.getTransaction(e,{commitment:"confirmed",maxSupportedTransactionVersion:s});if(a){let e=null===(o=a.meta)||void 0===o?void 0:o.logMessages;throw e?new c.SendTransactionError(t.message,e):t}}throw t}}return u}async simulate(t,e,r,n){let o,i=(await this.connection.getLatestBlockhash(null!=r?r:this.connection.commitment)).blockhash;if(isVersionedTransaction(t)?(e&&e.length>0&&(t.sign(e),t=await this.wallet.signTransaction(t)),o=await this.connection.simulateTransaction(t,{commitment:r})):(t.feePayer=t.feePayer||this.wallet.publicKey,t.recentBlockhash=i,e&&e.length>0&&(t=await this.wallet.signTransaction(t)),o=await simulateTransaction(this.connection,t,e,r,n)),o.value.err)throw new SimulateError(o.value);return o.value}};
1let SimulateError=class SimulateError extends Error{constructor(t,e){super(e),this.simulationResponse=t}};async function sendAndConfirmRawTransaction(t,e,r){let n=r&&{skipPreflight:r.skipPreflight,preflightCommitment:r.preflightCommitment||r.commitment},o=await t.sendRawTransaction(e,n),i=(await t.confirmTransaction(o,r&&r.commitment)).value;if(i.err)throw new ConfirmError(`Raw transaction ${o} failed (${JSON.stringify(i)})`);return o}let ConfirmError=class ConfirmError extends Error{constructor(t){super(t)}};function getProvider(){return null===g?AnchorProvider.local():g}let g=null;var T="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==r.g?r.g:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var I={};Object.defineProperty(I,"__esModule",{value:!0});var C=I.ANCHOR_ERROR__REQUIRE_EQ_VIOLATED=tg=I.ANCHOR_ERROR__REQUIRE_VIOLATED=tN=I.ANCHOR_ERROR__CONSTRAINT_MINT_TRANSFER_HOOK_EXTENSION_PROGRAM_ID=tO
1=I.ANCHOR_ERROR__CONSTRAINT_MINT_TRANSFER_HOOK_EXTENSION_AUTHORITY=tm=I.ANCHOR_ERROR__CONSTRAINT_MINT_TRANSFER_HOOK_EXTENSION=tE=I.ANCHOR_ERROR__CONSTRAINT_MINT_PERMANENT_DELEGATE_EXTENSION_DELEGATE=tA=I.ANCHOR_ERROR__CONSTRAINT_MINT_PERMANENT_DELEGATE_EXTENSION=ty=I.ANCHOR_ERROR__CONSTRAINT_MINT_CLOSE_AUTHORITY_EXTENSION_AUTHORITY=tR=I.ANCHOR_ERROR__CONSTRAINT_MINT_CLOSE_AUTHORITY_EXTENSION=tf=I.ANCHOR_ERROR__CONSTRAINT_MINT_METADATA_POINTER_EXTENSION_METADATA_ADDRESS=tp=I.ANCHOR_ERROR__CONSTRAINT_MINT_METADATA_POINTER_EXTENSION_AUTHORITY=t_=I.ANCHOR_ERROR__CONSTRAINT_MINT_METADATA_POINTER_EXTENSION=th=I.ANCHOR_ERROR__CONSTRAINT_MINT_GROUP_MEMBER_POINTER_EXTENSION_MEMBER_ADDRESS=td=I.ANCHOR_ERROR__CONSTRAINT_MINT_GROUP_MEMBER_POINTER_EXTENSION_AUTHORITY=tl=I.ANCHOR_ERROR__CONSTRAINT_MINT_GROUP_MEMBER_POINTER_EXTENSION=tu=I.ANCHOR_ERROR__CONSTRAINT_MINT_GROUP_POINTER_EXTENSION_GROUP_ADDRESS=tc=I.ANCHOR_ERROR__CONSTRAINT_MINT_GROUP_POINTER_EXTENSION_AUTHORITY=ta=I.ANCHOR_ERROR__CONSTRAINT_MINT_GROUP_POINTER_EXTENSION=ts=I.ANCHOR_ERROR__CONSTRAINT_ASSOCIATED_TOKEN_TOKEN_PROGRAM=ti=I.ANCHOR_ERROR__CONSTRAINT_MINT_TOKEN_PROGRAM=to=I.ANCHOR_ERROR__CONSTRAINT_TOKEN_TOKEN_PROGRAM=tn=I.ANCHOR_ERROR__CONSTRAINT_ACCOUNT_IS_NONE=tr=I.ANCHOR_ERROR__CONSTRAINT_SPACE=te=I.ANCHOR_ERROR__CONSTRAINT_MINT_DECIMALS=tt=I.ANCHOR_ERROR__CONSTRAINT_MINT_FREEZE_AUTHORITY=J=I.ANCHOR_ERROR__CONSTRAINT_MINT_MINT_AUTHORITY=Z=I.ANCHOR_ERROR__CONSTRAINT_TOKEN_OWNER=Q=I.ANCHOR_ERROR__CONSTRAINT_TOKEN_MINT=W=I.ANCHOR_ERROR__CONSTRAINT_ZERO=Y=I.ANCHOR_ERROR__CONSTRAINT_ADDRESS=X=I.ANCHOR_ERROR__CONSTRAINT_CLOSE=q=I.ANCHOR_ERROR__CONSTRAINT_ASSOCIATED_INIT=j=I.ANCHOR_ERROR__CONSTRAINT_ASSOCIATED=z=I.ANCHOR_ERROR__CONSTRAINT_STATE=K=I.ANCHOR_ERROR__CONSTRAINT_EXECUTABLE=$=I.ANCHOR_ERROR__CONSTRAINT_SEEDS=G=I.ANCHOR_ERROR__CONSTRAINT_RENT_EXEMPT=V=I.ANCHOR_ERROR__CONSTRAINT_OWNER=B=I.ANCHOR_ERROR__CONSTRAINT_RAW=k=I.ANCHOR_ERROR__CONSTRAINT_SIGNER=U=I.ANCHOR_ERROR__CONSTRAINT_HAS_ONE=H=I.ANCHOR_ERROR__CONSTRAINT_MUT=L=I.ANCHOR_ERROR__EVENT_INSTRUCTION_STUB=D=I.ANCHOR_ERROR__IDL_ACCOUNT_NOT_EMPTY=x=I.ANCHOR_ERROR__IDL_INSTRUCTION_INVALID_PROGRAM=M=I.ANCHOR_ERROR__IDL_INSTRUCTION_STUB=P=I.ANCHOR_ERROR__INSTRUCTION_DID_NOT_SERIALIZE=S=I.ANCHOR_ERROR__INSTRUCTION_DID_NOT_DESERIALIZE=b=I.ANCHOR_ERROR__INSTRUCTION_FALLBACK_NOT_FOUND=w=I.ANCHOR_ERROR__INSTRUCTION_MISSING=void 0,v=I.ANCHOR_ERROR__DEPRECATED=tY=I.ANCHOR_ERROR__INVALID_NUMERIC_CONVERSION=tX=I.ANCHOR_ERROR__TRYING_TO_INIT_PAYER_AS_PROGRAM_ACCOUNT=tq=I.ANCHOR_ERROR__DECLARED_PROGRAM_ID_MISMATCH=tj=I.ANCHOR_ERROR__ACCOUNT_DUPLICATE_REALLOCS=tz=I.ANCHOR_ERROR__ACCOUNT_REALLOC_EXCEEDS_LIMIT=tK=I.ANCHOR_ERROR__ACCOUNT_SYSVAR_MISMATCH=t$=I.ANCHOR_ERROR__ACCOUNT_NOT_ASSOCIATED_TOKEN_ACCOUNT=tG=I.ANCHOR_ERROR__ACCOUNT_NOT_PROGRAM_DATA=tV=I.ANCHOR_ERROR__ACCOUNT_NOT_INITIALIZED=tF=I.ANCHOR_ERROR__ACCOUNT_NOT_SYSTEM_OWNED=tB=I.ANCHOR_ERROR__ACCOUNT_NOT_SIGNER=tk=I.ANCHOR_ERROR__INVALID_PROGRAM_EXECUTABLE=tU=I.ANCHOR_ERROR__INVALID_PROGRAM_ID=tH=I.ANCHOR_ERROR__ACCOUNT_OWNED_BY_WRONG_PROGRAM=tL=I.ANCHOR_ERROR__ACCOUNT_NOT_MUTABLE=tD=I.ANCHOR_ERROR__ACCOUNT_NOT_ENOUGH_KEYS=tx=I.ANCHOR_ERROR__ACCOUNT_DID_NOT_SERIALIZE=tM=I.ANCHOR_ERROR__ACCOUNT_DID_NOT_DESERIALIZE=tP=I.ANCHOR_ERROR__ACCOUNT_DISCRIMINATOR_MISMATCH=tS=I.ANCHOR_ERROR__ACCOUNT_DISCRIMINATOR_NOT_FOUND=tb=I.ANCHOR_ERROR__ACCOUNT_DISCRIMINATOR_ALREADY_SET=tw=I.ANCHOR_ERROR__REQUIRE_GTE_VIOLATED=tv=I.ANCHOR_ERROR__REQUIRE_GT_VIOLATED=tC=I.ANCHOR_ERROR__REQUIRE_KEYS_NEQ_VIOLATED=tI=I.ANCHOR_ERROR__REQUIRE_NEQ_VIOLATED=tT=I.ANCHOR_ERROR__REQUIRE_KEYS_EQ_VIOLATED=void 0,w=I.ANCHOR_ERROR__INSTRUCTION_MISSING=100,b=I.ANCHOR_ERROR__INSTRUCTION_FALLBACK_NOT_FOUND=101,S=I.ANCHOR_ERROR__INSTRUCTION_DID_NOT_DESERIALIZE=102,P=I.ANCHOR_ERROR__INSTRUCTION_DID_NOT_SERIALIZE=103,M=I.ANCHOR_ERROR__IDL_INSTRUCTION_STUB=1e3,x=I.ANCHOR_ERROR__IDL_INSTRUCTION_INVALID_PROGRAM=1001,D=I.ANCHOR_ERROR__IDL_ACCOUNT_NOT_EMPTY=1002,L=I.ANCHOR_ERROR__EVENT_INSTRUCTION_STUB=1500,H=I.ANCHOR_ERROR__CONSTRAINT_MUT=2e3,U=I.ANCHOR_ERROR__CONSTRAINT_HAS_ONE=2001,k=I.ANCHOR_ERROR__CONSTRAINT_SIGNER=2002,B=I.ANCHOR_ERROR__CONSTRAINT_RAW
1=2003,V=I.ANCHOR_ERROR__CONSTRAINT_OWNER=2004,G=I.ANCHOR_ERROR__CONSTRAINT_RENT_EXEMPT=2005,$=I.ANCHOR_ERROR__CONSTRAINT_SEEDS=2006,K=I.ANCHOR_ERROR__CONSTRAINT_EXECUTABLE=2007,z=I.ANCHOR_ERROR__CONSTRAINT_STATE=2008,j=I.ANCHOR_ERROR__CONSTRAINT_ASSOCIATED=2009,q=I.ANCHOR_ERROR__CONSTRAINT_ASSOCIATED_INIT=2010,X=I.ANCHOR_ERROR__CONSTRAINT_CLOSE=2011,Y=I.ANCHOR_ERROR__CONSTRAINT_ADDRESS=2012,W=I.ANCHOR_ERROR__CONSTRAINT_ZERO=2013,Q=I.ANCHOR_ERROR__CONSTRAINT_TOKEN_MINT=2014,Z=I.ANCHOR_ERROR__CONSTRAINT_TOKEN_OWNER=2015,J=I.ANCHOR_ERROR__CONSTRAINT_MINT_MINT_AUTHORITY=2016,tt=I.ANCHOR_ERROR__CONSTRAINT_MINT_FREEZE_AUTHORITY=2017,te=I.ANCHOR_ERROR__CONSTRAINT_MINT_DECIMALS=2018,tr=I.ANCHOR_ERROR__CONSTRAINT_SPACE=2019,tn=I.ANCHOR_ERROR__CONSTRAINT_ACCOUNT_IS_NONE=2020,to=I.ANCHOR_ERROR__CONSTRAINT_TOKEN_TOKEN_PROGRAM=2021,ti=I.ANCHOR_ERROR__CONSTRAINT_MINT_TOKEN_PROGRAM=2022,ts=I.ANCHOR_ERROR__CONSTRAINT_ASSOCIATED_TOKEN_TOKEN_PROGRAM=2023,ta=I.ANCHOR_ERROR__CONSTRAINT_MINT_GROUP_POINTER_EXTENSION=2024,tc=I.ANCHOR_ERROR__CONSTRAINT_MINT_GROUP_POINTER_EXTENSION_AUTHORITY=2025,tu=I.ANCHOR_ERROR__CONSTRAINT_MINT_GROUP_POINTER_EXTENSION_GROUP_ADDRESS=2026,tl=I.ANCHOR_ERROR__CONSTRAINT_MINT_GROUP_MEMBER_POINTER_EXTENSION=2027,td=I.ANCHOR_ERROR__CONSTRAINT_MINT_GROUP_MEMBER_POINTER_EXTENSION_AUTHORITY=2028,th=I.ANCHOR_ERROR__CONSTRAINT_MINT_GROUP_MEMBER_POINTER_EXTENSION_MEMBER_ADDRESS=2029,t_=I.ANCHOR_ERROR__CONSTRAINT_MINT_METADATA_POINTER_EXTENSION=2030,tp=I.ANCHOR_ERROR__CONSTRAINT_MINT_METADATA_POINTER_EXTENSION_AUTHORITY=2031,tf=I.ANCHOR_ERROR__CONSTRAINT_MINT_METADATA_POINTER_EXTENSION_METADATA_ADDRESS=2032,tR=I.ANCHOR_ERROR__CONSTRAINT_MINT_CLOSE_AUTHORITY_EXTENSION=2033,ty=I.ANCHOR_ERROR__CONSTRAINT_MINT_CLOSE_AUTHORITY_EXTENSION_AUTHORITY=2034,tA=I.ANCHOR_ERROR__CONSTRAINT_MINT_PERMANENT_DELEGATE_EXTENSION=2035,tE=I.ANCHOR_ERROR__CONSTRAINT_MINT_PERMANENT_DELEGATE_EXTENSION_DELEGATE=2036,tm=I.ANCHOR_ERROR__CONSTRAINT_MINT_TRANSFER_HOOK_EXTENSION=2037,tO=I.ANCHOR_ERROR__CONSTRAINT_MINT_TRANSFER_HOOK_EXTENSION_AUTHORITY=2038,tN=I.ANCHOR_ERROR__CONSTRAINT_MINT_TRANSFER_HOOK_EXTENSION_PROGRAM_ID=2039,tg=I.ANCHOR_ERROR__REQUIRE_VIOLATED=2500;C=I.ANCHOR_ERROR__REQUIRE_EQ_VIOLATED=2501;var tT=I.ANCHOR_ERROR__REQUIRE_KEYS_EQ_VIOLATED=2502,tI=I.ANCHOR_ERROR__REQUIRE_NEQ_VIOLATED=2503,tC=I.ANCHOR_ERROR__REQUIRE_KEYS_NEQ_VIOLATED=2504,tv=I.ANCHOR_ERROR__REQUIRE_GT_VIOLATED=2505,tw=I.ANCHOR_ERROR__REQUIRE_GTE_VIOLATED=2506,tb=I.ANCHOR_ERROR__ACCOUNT_DISCRIMINATOR_ALREADY_SET=3e3,tS=I.ANCHOR_ERROR__ACCOUNT_DISCRIMINATOR_NOT_FOUND=3001,tP=I.ANCHOR_ERROR__ACCOUNT_DISCRIMINATOR_MISMATCH=3002,tM=I.ANCHOR_ERROR__ACCOUNT_DID_NOT_DESERIALIZE=3003,tx=I.ANCHOR_ERROR__ACCOUNT_DID_NOT_SERIALIZE=3004,tD=I.ANCHOR_ERROR__ACCOUNT_NOT_ENOUGH_KEYS=3005,tL=I.ANCHOR_ERROR__ACCOUNT_NOT_MUTABLE=3006,tH=I.ANCHOR_ERROR__ACCOUNT_OWNED_BY_WRONG_PROGRAM=3007,tU=I.ANCHOR_ERROR__INVALID_PROGRAM_ID=3008,tk=I.ANCHOR_ERROR__INVALID_PROGRAM_EXECUTABLE=3009,tB=I.ANCHOR_ERROR__ACCOUNT_NOT_SIGNER=3010,tF=I.ANCHOR_ERROR__ACCOUNT_NOT_SYSTEM_OWNED=3011,tV=I.ANCHOR_ERROR__ACCOUNT_NOT_INITIALIZED=3012,tG=I.ANCHOR_ERROR__ACCOUNT_NOT_PROGRAM_DATA=3013,t$=I.ANCHOR_ERROR__ACCOUNT_NOT_ASSOCIATED_TOKEN_ACCOUNT=3014,tK=I.ANCHOR_ERROR__ACCOUNT_SYSVAR_MISMATCH=3015,tz=I.ANCHOR_ERROR__ACCOUNT_REALLOC_EXCEEDS_LIMIT=3016,tj=I.ANCHOR_ERROR__ACCOUNT_DUPLICATE_REALLOCS=3017,tq=I.ANCHOR_ERROR__DECLARED_PROGRAM_ID_MISMATCH=4100,tX=I.ANCHOR_ERROR__TRYING_TO_INIT_PAYER_AS_PROGRAM_ACCOUNT=4101,tY=I.ANCHOR_ERROR__INVALID_NUMERIC_CONVERSION=4102;v=I.ANCHOR_ERROR__DEPRECATED=5e3;let tW=new Map;function isSet(t){return void 0!==tW.get(t)}let IdlError=class IdlError extends Error{constructor(t){super(t),this.name="IdlError"}};let ProgramErrorStack=class ProgramErrorStack{constructor(t){this.stack=t}static parse(t){var e;
1let r=/^Program (\w*) invoke/,n=/^Program \w* success/,o=[];for(let i=0;i<t.length;i++){if(n.exec(t[i])){o.pop();continue}let s=null===(e=r.exec(t[i]))||void 0===e?void 0:e[1];s&&o.push(new c.PublicKey(s))}return new ProgramErrorStack(o)}};let AnchorError=class AnchorError extends Error{constructor(t,e,r,n,o,i){super(r.join("\n").replace("Program log: ","")),this.errorLogs=r,this.logs=n,this.error={errorCode:t,errorMessage:e,comparedValues:i,origin:o},this._programErrorStack=ProgramErrorStack.parse(n)}static parse(t){let e;if(!t)return null;let r=t.findIndex(t=>t.startsWith("Program log: AnchorError"));if(-1===r)return null;let n=t[r],o=[n];if(r+1<t.length){if("Program log: Left:"===t[r+1]){let n=/^Program log: (.*)$/,i=n.exec(t[r+2])[1],s=n.exec(t[r+4])[1];e=[new c.PublicKey(i),new c.PublicKey(s)],o.push(...t.slice(r+1,r+5))}else if(t[r+1].startsWith("Program log: Left:")){let n=/^Program log: (Left|Right): (.*)$/,i=n.exec(t[r+1])[2],s=n.exec(t[r+2])[2];o.push(...t.slice(r+1,r+3)),e=[i,s]}}let i=/^Program log: AnchorError occurred\. Error Code: (.*)\. Error Number: (\d*)\. Error Message: (.*)\./.exec(n),s=/^Program log: AnchorError thrown in (.*):(\d*)\. Error Code: (.*)\. Error Number: (\d*)\. Error Message: (.*)\./.exec(n),a=/^Program log: AnchorError caused by account: (.*)\. Error Code: (.*)\. Error Number: (\d*)\. Error Message: (.*)\./.exec(n);if(i){let[r,n,s]=i.slice(1,4),a={code:r,number:parseInt(n)};return new AnchorError(a,s,o,t,void 0,e)}if(s){let[r,n,i,a,c]=s.slice(1,6),u={code:i,number:parseInt(a)},l={file:r,line:parseInt(n)};return new AnchorError(u,c,o,t,l,e)}if(!a)return null;{let[r,n,i,s]=a.slice(1,5),c={code:n,number:parseInt(i)};return new AnchorError(c,s,o,t,r,e)}}get program(){return this._programErrorStack.stack[this._programErrorStack.stack.length-1]}get programErrorStack(){return this._programErrorStack.stack}toString(){return this.message}};let ProgramError=class ProgramError extends Error{constructor(t,e,r){super(),this.code=t,this.msg=e,this.logs=r,r&&(this._programErrorStack=ProgramErrorStack.parse(r))}static parse(t,e){let r,n;let o=t.toString();if(o.includes("custom program error:")){let t=o.split("custom program error: ");if(2!==t.length)return null;r=t[1]}else{let t=o.match(/"Custom":([0-9]+)}/g);if(!t||t.length>1)return null;r=t[0].match(/([0-9]+)/g)[0]}try{n=parseInt(r)}catch(t){return null}let i=e.get(n);return void 0!==i||void 0!==(i=tZ.get(n))?new ProgramError(n,i,t.logs):null}get program(){var t;return null===(t=this._programErrorStack)||void 0===t?void 0:t.stack[this._programErrorStack.stack.length-1]}get programErrorStack(){var t;return null===(t=this._programErrorStack)||void 0===t?void 0:t.stack}toString(){return this.msg}};function translateError(t,e){isSet("debug-logs")&&console.log("Translating error:",t);let r=AnchorError.parse(t.logs);if(r)return r;let n=ProgramError.parse(t,e);return n||(t.logs?(t.programErrorStack=ProgramErrorStack.parse(t.logs),new Proxy(t,{get:function(e,r){return"programErrorStack"===r?e.programErrorStack.stack:"program"===r?e.programErrorStack.stack[t.programErrorStack.stack.length-1]:Reflect.get(...arguments)}})):t)}let tQ={InstructionMissing:w,InstructionFallbackNotFound:b,InstructionDidNotDeserialize:S,InstructionDidNotSerialize:P,IdlInstructionStub:M,IdlInstructionInvalidProgram:x,IdlAccountNotEmpty:D,EventInstructionStub:L,ConstraintMut:H,ConstraintHasOne:U,ConstraintSigner:k,ConstraintRaw:B,ConstraintOwner:V,ConstraintRentExempt:G,ConstraintSeeds:$,ConstraintExecutable:K,ConstraintState:z,ConstraintAssociated:j,ConstraintAssociatedInit:q,ConstraintClose:X,ConstraintAddress:Y,ConstraintZero:W,ConstraintTokenMint:Q,ConstraintTokenOwner:Z,ConstraintMintMintAuthority:J,ConstraintMintFreezeAuthority:tt,ConstraintMintDecimals:te,ConstraintSpace:tr,ConstraintAccountIsNone:tn,ConstraintTokenTokenProgram:to,ConstraintMintTokenProgram:ti,ConstraintAssociatedTokenTokenProgram:ts,ConstraintMintGroupPointerExtension:ta,ConstraintMintGroupPointerExtensionAuthority:tc,ConstraintMintGroupPointerExtensionGroupAddress:tu,ConstraintMintGroupMemberPointerExtension:tl,ConstraintMintGroupMemberPointerExtensionAuthority:td,ConstraintMintGroupMemberPointerExtensionMemberAddress:th,ConstraintMintMetadataPointerExtension:t_,ConstraintMintMetadataPointerExtensionAuthority:tp,ConstraintMintMetadataPointerExtensionMetadataAddress:tf,ConstraintMintCloseAuthorityExtension:tR,ConstraintMintCloseAuthorityExtensionAuthority:ty,ConstraintMintPermanentDelegateExtension:tA,ConstraintMintPermanentDelegateExtensionDelegate:tE,ConstraintMintTransferHookExtension:tm,ConstraintMintTransferHookExtensionAuthority:tO,ConstraintMintTransferHookExtensionProgramId:tN,RequireViolated:tg,RequireEqViolated:C,RequireKeysEqViolated:tT,RequireNeqViolated:tI,RequireKeysNeqViolated:tC,RequireGtViolated:tv,RequireGteViolated:tw,AccountDiscriminatorAlreadySet:tb,AccountDiscriminatorNotFound:tS,AccountDiscriminatorMismatch:tP,AccountDidNotDeserialize:tM,AccountDidNotSerialize:tx,AccountNotEnoughKeys:tD,AccountNotMutable:tL,AccountOwnedByWrongProgram:tH,InvalidProgramId:tU,InvalidProgramExecutable:tk,AccountNotSigner:tB,AccountNotSystemOwned:tF,AccountNotInitialized:tV,AccountNotProgramData:tG,AccountNotAssociatedTokenAccount:t$,AccountSysvarMismatch:tK,AccountReallocExceedsLimit:tz,AccountDuplicateReallocs:tj,DeclaredProgramIdMismatch:tq,TryingToInitPayerAsProgramAccount:tX,InvalidNumericConversion:tY,Deprecated:v},tZ=new Map([[tQ.InstructionMissing,"8 byte instruction identifier not provided"],[tQ.InstructionFallbackNotFound,"Fallback functions are not supported"],[tQ.InstructionDidNotDeserialize,"The program could not deserialize the given instruction"],[tQ.InstructionDidNotSerialize,"The program could not serialize the given instruction"],[tQ.IdlInstructionStub,"The program was compiled without idl instructions"],[tQ.IdlInstructionInvalidProgram,"The transaction was given an invali
1d program for the IDL instruction"],[tQ.IdlAccountNotEmpty,"IDL account must be empty in order to resize, try closing first"],[tQ.EventInstructionStub,"The program was compiled without `event-cpi` feature"],[tQ.ConstraintMut,"A mut constraint was violated"],[tQ.ConstraintHasOne,"A has one constraint was violated"],[tQ.ConstraintSigner,"A signer constraint was violated"],[tQ.ConstraintRaw,"A raw constraint was violated"],[tQ.ConstraintOwner,"An owner constraint was violated"],[tQ.ConstraintRentExempt,"A rent exemption constraint was violated"],[tQ.ConstraintSeeds,"A seeds constraint was violated"],[tQ.ConstraintExecutable,"An executable constraint was violated"],[tQ.ConstraintState,"Deprecated Error, feel free to replace with something else"],[tQ.ConstraintAssociated,"An associated constraint was violated"],[tQ.ConstraintAssociatedInit,"An associated init constraint was violated"],[tQ.ConstraintClose,"A close constraint was violated"],[tQ.ConstraintAddress,"An address constraint was violated"],[tQ.ConstraintZero,"Expected zero account discriminant"],[tQ.ConstraintTokenMint,"A token mint constraint was violated"],[tQ.ConstraintTokenOwner,"A token owner constraint was violated"],[tQ.ConstraintMintMintAuthority,"A mint mint authority constraint was violated"],[tQ.ConstraintMintFreezeAuthority,"A mint freeze authority constraint was violated"],[tQ.ConstraintMintDecimals,"A mint decimals constraint was violated"],[tQ.ConstraintSpace,"A space constraint was violated"],[tQ.ConstraintAccountIsNone,"A required account for the constraint is None"],[tQ.ConstraintTokenTokenProgram,"A token account token program constraint was violated"],[tQ.ConstraintMintTokenProgram,"A mint token program constraint was violated"],[tQ.ConstraintAssociatedTokenTokenProgram,"An associated token account token program constraint was violated"],[tQ.ConstraintMintGroupPointerExtension,"A group pointer extension constraint was violated"],[tQ.ConstraintMintGroupPointerExtensionAuthority,"A group pointer extension authority constraint was violated"],[tQ.ConstraintMintGroupPointerExtensionGroupAddress,"A group pointer extension group address constraint was violated"],[tQ.ConstraintMintGroupMemberPointerExtension,"A group member pointer extension constraint was violated"],[tQ.ConstraintMintGroupMemberPointerExtensionAuthority,"A group member pointer extension authority constraint was violated"],[tQ.ConstraintMintGroupMemberPointerExtensionMemberAddress,"A group member pointer extension group address constraint was violated"],[tQ.ConstraintMintMetadataPointerExtension,"A metadata pointer extension constraint was violated"],[tQ.ConstraintMintMetadataPointerExtensionAuthority,"A metadata pointer extension authority constraint was violated"],[tQ.ConstraintMintMetadataPointerExtensionMetadataAddress,"A metadata pointer extension metadata address constraint was violated"],[tQ.ConstraintMintCloseAuthorityExtension,"A close authority constraint was violated"],[tQ.ConstraintMintCloseAuthorityExtensionAuthority,"A close authority extension authority constraint was violated"],[tQ.ConstraintMintPermanentDelegateExtension,"A permanent delegate extension constraint was violated"],[tQ.ConstraintMintPermanentDelegateExtensionDelegate,"A permanent delegate extension delegate constraint was violated"],[tQ.ConstraintMintTransferHookExtension,"A transfer hook extension constraint was violated"],[tQ.ConstraintMintTransferHookExtensionAuthority,"A transfer hook extension authority constraint was violated"],[tQ.ConstraintMintTransferHookExtensionProgramId,"A transfer hook extension transfer hook program id constraint was violated"],[tQ.RequireViolated,"A require expression was violated"],[tQ.RequireEqViolated,"A require_eq expression was violated"],[tQ.RequireKeysEqViolated,"A require_keys_eq expression was violated"],[tQ.RequireNeqViolated,"A require_neq expression was violated"],[tQ.RequireKeysNeqViolated,"A require_keys_neq expression was violated"],[tQ.RequireGtViolated,"A require_gt expression was violated"],[tQ.RequireGteViolated,"A require_gte expression was violated"],[tQ.AccountDiscriminatorAlreadySet,"The account discriminator was already set on this account"],[tQ.AccountDiscriminatorNotFound,"No 8 byte discriminator was found on the account"],[tQ.AccountDiscriminatorMismatch,"8 byte discriminator did not match what was expected"],[tQ.AccountDidNotDeserialize,"Failed to deserialize the account"],[tQ.AccountDidNotSerialize,"Failed to serialize the account"],[tQ.AccountNotEnoughKeys,"Not enough account keys given to the instruction"],[tQ.AccountNotMutable,"The given account is not mutable"],[tQ.AccountOwnedByWrongProgram,"The given account is owned by a different program than expected"],[tQ.InvalidProgramId,"Program ID was not as expected"],[tQ.InvalidProgramExecutable,"Program account is not executable"],[tQ.AccountNotSigner,"The given account did not sign"],[tQ.AccountNotSystemOwned,"The given account is not owned by the system program"],[tQ.AccountNotInitialized,"The program expected this account to be already initialized"],[tQ.AccountNotProgramData,"The given account is not a program data account"],[tQ.AccountNotAssociatedTokenAccount,"The given account is not the associated token account"],[tQ.AccountSysvarMismatch,"The given public key does not match the required sysvar"],[tQ.AccountReallocExceedsLimit,"The account reallocation exceeds the MAX_PERMITTED_DATA_INCREASE limit"],[tQ.AccountDuplicateReallocs,"The account was duplicated for more than one reallocation"],[tQ.DeclaredProgramIdMismatch,"The declared program id does not match the actual program id"],[tQ.TryingToInitPayerAsProgramAccount,"You cannot/should not initialize the payer account as a program account"],[tQ.InvalidNumericConversion,"The program could not perform the numeric conversion, out of range integral type conversion attempted"],[tQ.Deprecated,"The API being used is deprecated and should no longer be used"]]);let IdlCoder=class IdlCoder{static fieldLayout(t,e=[],r){let n=t.name;switch(t.type){case"bool":return f.bool(n);case"u8":return f.u8(n);case"i8":return f.i8(n);case"u16":return f.u16(n);case"i16":return f.i16(n);case"u32":return f.u32(n);case"i32":return f.i32(n);case"f32":return f.f32(n);case"u64":return f.u64(n);case"i64":return f.i64(n);case"f64":return f.f64(n);case"u128":return f.u128(n);case"i128":return f.i128(n);case"u256":return f.u256(n);case"i256":return f.i256(n);case"bytes":return f.vecU8(n);case"string":return f.str(n);case"pubkey":return f.publicKey(n);default:if("option"in t.type)return f.option(IdlCoder.fieldLayout({type:t.type.option},e,r),n);if("vec"in t.type)return f.vec(IdlCoder.fieldLayout({type:t.type.vec},e,r),n);if("array"in t.type){let[o,i]=t.type.array;
1return i=IdlCoder.resolveArrayLen(i,r),f.array(IdlCoder.fieldLayout({type:o},e,r),i,n)}if("defined"in t.type){if(!e)throw new IdlError("User defined types not provided");let o=t.type.defined.name,i=e.find(t=>t.name===o);if(!i)throw new IdlError(`Type not found: ${t.name}`);return IdlCoder.typeDefLayout({typeDef:i,types:e,genericArgs:null!=r?r:t.type.defined.generics,name:n})}if("generic"in t.type){let n=null==r?void 0:r.at(0);if((null==n?void 0:n.kind)!=="type")throw new IdlError(`Invalid generic field: ${t.name}`);return IdlCoder.fieldLayout({...t,type:n.type},e)}throw new IdlError(`Not yet implemented: ${JSON.stringify(t.type)}`)}}static typeDefLayout({typeDef:t,types:e,name:r,genericArgs:n}){switch(t.type.kind){case"struct":{let o=handleDefinedFields(t.type.fields,()=>[],r=>r.map(r=>{let o=n?IdlCoder.resolveGenericArgs({type:r.type,typeDef:t,genericArgs:n}):n;return IdlCoder.fieldLayout(r,e,o)}),r=>r.map((r,o)=>{let i=n?IdlCoder.resolveGenericArgs({type:r,typeDef:t,genericArgs:n}):n;return IdlCoder.fieldLayout({name:o.toString(),type:r},e,i)}));return f.struct(o,r)}case"enum":{let o=t.type.variants.map(r=>{let o=handleDefinedFields(r.fields,()=>[],r=>r.map(r=>{let o=n?IdlCoder.resolveGenericArgs({type:r.type,typeDef:t,genericArgs:n}):n;return IdlCoder.fieldLayout(r,e,o)}),r=>r.map((r,o)=>{let i=n?IdlCoder.resolveGenericArgs({type:r,typeDef:t,genericArgs:n}):n;return IdlCoder.fieldLayout({name:o.toString(),type:r},e,i)}));return f.struct(o,r.name)});if(void 0!==r)return f.rustEnum(o).replicate(r);return f.rustEnum(o,r)}case"type":return IdlCoder.fieldLayout({type:t.type.alias,name:r},e)}}static typeSize(t,e,r){var n;switch(t){case"bool":case"u8":case"i8":case"bytes":case"string":return 1;case"i16":case"u16":return 2;case"u32":case"i32":case"f32":return 4;case"u64":case"i64":case"f64":return 8;case"u128":case"i128":return 16;case"u256":case"i256":case"pubkey":return 32;default:if("option"in t)return 1+IdlCoder.typeSize(t.option,e,r);if("coption"in t)return 4+IdlCoder.typeSize(t.coption,e,r);if("vec"in t)return 1;if("array"in t){let[n,o]=t.array;return o=IdlCoder.resolveArrayLen(o,r),IdlCoder.typeSize(n,e,r)*o}if("defined"in t){let o=null===(n=e.types)||void 0===n?void 0:n.find(e=>e.name===t.defined.name);if(!o)throw new IdlError(`Type not found: ${JSON.stringify(t)}`);let typeSize=n=>{let i=null!=r?r:t.defined.generics,s=i?IdlCoder.resolveGenericArgs({type:n,typeDef:o,genericArgs:i}):i;return IdlCoder.typeSize(n,e,s)};switch(o.type.kind){case"struct":return handleDefinedFields(o.type.fields,()=>[0],t=>t.map(t=>typeSize(t.type)),t=>t.map(t=>typeSize(t))).reduce((t,e)=>t+e,0);case"enum":{let t=o.type.variants.map(t=>handleDefinedFields(t.fields,()=>[0],t=>t.map(t=>typeSize(t.type)),t=>t.map(t=>typeSize(t))).reduce((t,e)=>t+e,0));return Math.max(...t)+1}case"type":return IdlCoder.typeSize(o.type.alias,e,r)}}if("generic"in t){let n=null==r?void 0:r.at(0);if((null==n?void 0:n.kind)!=="type")throw new IdlError(`Invalid generic: ${t.generic}`);return IdlCoder.typeSize(n.type,e,r)}throw Error(`Invalid type ${JSON.stringify(t)}`)}}static resolveArrayLen(t,e){if("number"==typeof t)return t;if(e){let r=e.find(t=>"const"===t.kind);(null==r?void 0:r.kind)==="const"&&(t=+r.value)}if("number"!=typeof t)throw new IdlError("Generic array length did not resolve");return t}static resolveGenericArgs({type:t,typeDef:e,genericArgs:r,isDefined:n}){if("object"!=typeof t)return null;for(let o in e.generics){let i=e.generics[o];if("generic"in t&&i.name===t.generic)return[r[o]];if("option"in t){let o=IdlCoder.resolveGenericArgs({type:t.option,typeDef:e,genericArgs:r,isDefined:n});if(!o||!n)return o;if("type"===o[0].kind)return[{kind:"type",type:{option:o[0].type}}]}if("vec"in t){let o=IdlCoder.resolveGenericArgs({type:t.vec,typeDef:e,genericArgs:r,isDefined:n});if(!o||!n)return o;if("type"===o[0].kind)return[{kind:"type",type:{vec:o[0].type}}]}if("array"in t){let[s,a]=t.array,c="object"==typeof a,u=IdlCoder.resolveGenericArgs({type:s,typeDef:e,genericArgs:r,isDefined:n});if(u){for(let t in e.generics.slice(+o)){let n=+o+ +t;c&&e.generics[n].name===a.generic&&u.push(r[n])}if(!n)return u;if("type"===u[0].kind&&"const"===u[1].kind)return[{kind:"type",type:{array:[u[0].type,+u[1].value]}}]}if(c&&i.name===a.generic){let t=r[o];if(!n)return[t];return[{kind:"type",type:{array:[s,+t.value]}}]}break}if("defined"in t){if(!t.defined.generics)return null;return t.defined.generics.flatMap(t=>{switch(t.kind){case"type":return IdlCoder.resolveGenericArgs({type:t.type,typeDef:e,genericArgs:r,isDefined:!0});case"const":return[t]}}).filter(t=>null!==t)}}return null}};let BorshInstructionCoder=class BorshInstructionCoder{constructor(t){this.idl=t;let e=t.instructions.map(e=>{let r=e.name,n=e.args.map(e=>IdlCoder.fieldLayout(e,t.types)),o=f.struct(n,r);return[r,{discriminator:e.discriminator,layout:o}]});this.ixLayouts=new Map(e);let r=e.map(([t,{discriminator:e,layout:r}])=>[h().encode(e),{name:t,layout:r}]);this.sighashLayouts=new Map(r)}encode(t,e){let r=a.Buffer.alloc(1e3),n=this.ixLayouts.get(t);if(!n)throw Error(`Unknown method: ${t}`);let o=n.layout.encode(e,r),i=r.slice(0,o);return a.Buffer.concat([a.Buffer.from(n.discriminator),i])}decode(t,e="hex"){"string"==typeof t&&(t="hex"===e?a.Buffer.from(t,"hex"):h().decode(t));let r=t.slice(0,tJ),n=t.slice(tJ),o=this.sighashLayouts.get(h().encode(r));return o?{name:o.name,data:o.layout.decode(n)}:null}format(t,e){return InstructionFormatter.format(t,e,this.idl)}};
1let InstructionFormatter=class InstructionFormatter{static format(t,e,r){let n=r.instructions.find(e=>t.name===e.name);if(!n)return console.error("Invalid instruction given"),null;let o=n.args.map(e=>({name:e.name,type:InstructionFormatter.formatIdlType(e.type),data:InstructionFormatter.formatIdlData(e,t.data[e.name],r.types)})),i=InstructionFormatter.flattenIdlAccounts(n.accounts),s=e.map((t,e)=>e<i.length?{name:i[e].name,...t}:{name:void 0,...t});return{args:o,accounts:s}}static formatIdlType(t){if("string"==typeof t)return t;if("option"in t)return`Option<${this.formatIdlType(t.option)}>`;if("coption"in t)return`COption<${this.formatIdlType(t.coption)}>`;if("vec"in t)return`Vec<${this.formatIdlType(t.vec)}>`;if("array"in t)return`Array<${t.array[0]}; ${t.array[1]}>`;if("defined"in t){let e=t.defined.name;if(t.defined.generics){let r=t.defined.generics.map(t=>{switch(t.kind){case"type":return InstructionFormatter.formatIdlType(t.type);case"const":return t.value}}).join(", ");return`${e}<${r}>`}return e}throw Error(`Unknown IDL type: ${t}`)}static formatIdlData(t,e,r){if("string"==typeof t.type)return e.toString();if("vec"in t.type)return"["+e.map(e=>this.formatIdlData({name:"",type:t.type.vec},e,r)).join(", ")+"]";if("option"in t.type)return null===e?"null":this.formatIdlData({name:"",type:t.type.option},e,r);if("defined"in t.type){if(!r)throw Error("User defined types not provided");let n=t.type.defined.name,o=r.find(t=>t.name===n);if(!o)throw Error(`Type not found: ${n}`);return InstructionFormatter.formatIdlDataDefined(o,e,r)}return"unknown"}static formatIdlDataDefined(t,e,r){switch(t.type.kind){case"struct":return"{ "+handleDefinedFields(t.type.fields,()=>"",t=>Object.entries(e).map(([e,n])=>{let o=t.find(t=>t.name===e);if(!o)throw Error(`Field not found: ${e}`);return e+": "+InstructionFormatter.formatIdlData(o,n,r)}).join(", "),t=>Object.entries(e).map(([e,n])=>e+": "+InstructionFormatter.formatIdlData({name:"",type:t[e]},n,r)).join(", "))+" }";case"enum":{let n=Object.keys(e)[0],o=t.type.variants.find(t=>t.name===n);if(!o)throw Error(`Unable to find variant: ${n}`);let i=e[n];return handleDefinedFields(o.fields,()=>n,t=>{let e=Object.keys(i).map(e=>{let n=i[e],o=t.find(t=>t.name===e);if(!o)throw Error(`Field not found: ${e}`);return e+": "+InstructionFormatter.formatIdlData(o,n,r)}).join(", ");return`${n} { ${e} }`},t=>{let e=Object.entries(i).map(([e,n])=>e+": "+InstructionFormatter.formatIdlData({name:"",type:t[e]},n,r)).join(", ");return`${n} { ${e} }`})}case"type":return InstructionFormatter.formatIdlType(t.type.alias)}}static flattenIdlAccounts(t,e){return t.map(t=>{let r=sentenceCase(t.name);if(!t.hasOwnProperty("accounts"))return{...t,name:e?`${e} > ${r}`:r};{let n=e?`${e} > ${r}`:r;return InstructionFormatter.flattenIdlAccounts(t.accounts,n)}}).flat()}};function sentenceCase(t){let e=t.replace(/([A-Z])/g," $1");return e.charAt(0).toUpperCase()+e.slice(1)}let tJ=8;let BorshAccountsCoder=class BorshAccountsCoder{constructor(t){if(this.idl=t,!t.accounts){this.accountLayouts=new Map;return}let e=t.types;if(!e)throw Error("Accounts require `idl.types`");let r=t.accounts.map(t=>{let r=e.find(e=>e.name===t.name);if(!r)throw Error(`Account not found: ${t.name}`);return[t.name,IdlCoder.typeDefLayout({typeDef:r,types:e})]});this.accountLayouts=new Map(r)}async encode(t,e){let r=a.Buffer.alloc(1e3),n=this.accountLayouts.get(t);if(!n)throw Error(`Unknown account: ${t}`);let o=n.encode(e,r),i=r.slice(0,o),s=this.accountDiscriminator(t);return a.Buffer.concat([s,i])}decode(t,e){let r=this.accountDiscriminator(t);if(r.compare(e.slice(0,tJ)))throw Error("Invalid account discriminator");return this.decodeUnchecked(t,e)}decodeAny(t){let e=t.slice(0,tJ),r=Array.from(this.accountLayouts.keys()).find(t=>this.accountDiscriminator(t).equals(e));if(!r)throw Error("Account not found");return this.decodeUnchecked(r,t)}decodeUnchecked(t,e){let r=e.subarray(tJ),n=this.accountLayouts.get(t);if(!n)throw Error(`Unknown account: ${t}`);return n.decode(r)}memcmp(t,e){let r=this.accountDiscriminator(t);return{offset:0,bytes:h().encode(e?a.Buffer.concat([r,e]):r)}}size(t){return tJ+IdlCoder.typeSize({defined:{name:t}},this.idl)}accountDiscriminator(t){var e;let r=null===(e=this.idl.accounts)||void 0===e?void 0:e.find(e=>e.name===t);if(!r)throw Error(`Account not found: ${t}`);return a.Buffer.from(r.discriminator)}};let BorshEventCoder=class BorshEventCoder{constructor(t){var e;if(!t.events){this.layouts=new Map;return}let r=t.types;if(!r)throw Error("Events require `idl.types`");let n=t.events.map(t=>{let e=r.find(e=>e.name===t.name);if(!e)throw Error(`Event not found: ${t.name}`);return[t.name,IdlCoder.typeDefLayout({typeDef:e,types:r})]});this.layouts=new Map(n),this.discriminators=new Map((null!==(e=t.events)&&void 0!==e?e:[]).map(t=>[encode(a.Buffer.from(t.discriminator)),t.name]))}decode(t){let e;try{e=decode(t)}catch(t){return null}let r=encode(e.slice(0,8)),n=this.discriminators.get(r);if(!n)return null;let o=this.layouts.get(n);if(!o)throw Error(`Unknown event: ${n}`);let i=o.decode(e.slice(8));return{data:i,name:n}}};let BorshTypesCoder=class BorshTypesCoder{constructor(t){let e=t.types;if(!e){this.typeLayouts=new Map;return}let r=e.filter(t=>!t.generics).map(t=>[t.name,IdlCoder.typeDefLayout({typeDef:t,types:e})]);this.typeLayouts=new Map(r)}encode(t,e){let r=a.Buffer.alloc(1e3),n=this.typeLayouts.get(t);if(!n)throw Error(`Unknown type: ${t}`);let o=n.encode(e,r);return r.slice(0,o)}
1decode(t,e){let r=this.typeLayouts.get(t);if(!r)throw Error(`Unknown type: ${t}`);return r.decode(e)}};let BorshCoder=class BorshCoder{constructor(t){this.instruction=new BorshInstructionCoder(t),this.accounts=new BorshAccountsCoder(t),this.events=new BorshEventCoder(t),this.types=new BorshTypesCoder(t)}};let Layout=class Layout{constructor(t,e){if(!Number.isInteger(t))throw TypeError("span must be an integer");this.span=t,this.property=e}makeDestinationObject(){return{}}decode(t,e){throw Error("Layout is abstract")}encode(t,e,r){throw Error("Layout is abstract")}getSpan(t,e){if(0>this.span)throw RangeError("indeterminate span");return this.span}replicate(t){let e=Object.create(this.constructor.prototype);return Object.assign(e,this),e.property=t,e}fromArray(t){}};var t0=Layout;function nameWithProperty(t,e){return e.property?t+"["+e.property+"]":t}let ExternalLayout=class ExternalLayout extends Layout{isCount(){throw Error("ExternalLayout is abstract")}};let OffsetLayout=class OffsetLayout extends ExternalLayout{constructor(t,e,r){if(!(t instanceof Layout))throw TypeError("layout must be a Layout");if(void 0===e)e=0;else if(!Number.isInteger(e))throw TypeError("offset must be integer or undefined");super(t.span,r||t.property),this.layout=t,this.offset=e}isCount(){return this.layout instanceof UInt||this.layout instanceof UIntBE}decode(t,e){return void 0===e&&(e=0),this.layout.decode(t,e+this.offset)}encode(t,e,r){return void 0===r&&(r=0),this.layout.encode(t,e,r+this.offset)}};let UInt=class UInt extends Layout{constructor(t,e){if(super(t,e),6<this.span)throw RangeError("span must not exceed 6 bytes")}decode(t,e){return void 0===e&&(e=0),t.readUIntLE(e,this.span)}encode(t,e,r){return void 0===r&&(r=0),e.writeUIntLE(t,r,this.span),this.span}};let UIntBE=class UIntBE extends Layout{constructor(t,e){if(super(t,e),6<this.span)throw RangeError("span must not exceed 6 bytes")}decode(t,e){return void 0===e&&(e=0),t.readUIntBE(e,this.span)}encode(t,e,r){return void 0===r&&(r=0),e.writeUIntBE(t,r,this.span),this.span}};function divmodInt64(t){let e=Math.floor(t/4294967296);return{hi32:e,lo32:t-4294967296*e}}
1function roundedInt64(t,e){return 4294967296*t+e}let NearUInt64=class NearUInt64 extends Layout{constructor(t){super(8,t)}decode(t,e){void 0===e&&(e=0);let r=t.readUInt32LE(e),n=t.readUInt32LE(e+4);return roundedInt64(n,r)}encode(t,e,r){void 0===r&&(r=0);let n=divmodInt64(t);return e.writeUInt32LE(n.lo32,r),e.writeUInt32LE(n.hi32,r+4),8}};let NearInt64=class NearInt64 extends Layout{constructor(t){super(8,t)}decode(t,e){void 0===e&&(e=0);let r=t.readUInt32LE(e),n=t.readInt32LE(e+4);return roundedInt64(n,r)}encode(t,e,r){void 0===r&&(r=0);let n=divmodInt64(t);return e.writeUInt32LE(n.lo32,r),e.writeInt32LE(n.hi32,r+4),8}};let Structure=class Structure extends Layout{constructor(t,e,r){if(!(Array.isArray(t)&&t.reduce((t,e)=>t&&e instanceof Layout,!0)))throw TypeError("fields must be array of Layout instances");for(let n of("boolean"==typeof e&&void 0===r&&(r=e,e=void 0),t))if(0>n.span&&void 0===n.property)throw Error("fields cannot contain unnamed variable-length layout");let n=-1;try{n=t.reduce((t,e)=>t+e.getSpan(),0)}catch(t){}super(n,e),this.fields=t,this.decodePrefixes=!!r}getSpan(t,e){if(0<=this.span)return this.span;void 0===e&&(e=0);let r=0;try{r=this.fields.reduce((r,n)=>{let o=n.getSpan(t,e);return e+=o,r+o},0)}catch(t){throw RangeError("indeterminate span")}return r}decode(t,e){void 0===e&&(e=0);let r=this.makeDestinationObject();for(let n of this.fields)if(void 0!==n.property&&(r[n.property]=n.decode(t,e)),e+=n.getSpan(t,e),this.decodePrefixes&&t.length===e)break;return r}encode(t,e,r){void 0===r&&(r=0);let n=r,o=0,i=0;for(let n of this.fields){let s=n.span;if(i=0<s?s:0,void 0!==n.property){let o=t[n.property];void 0!==o&&(i=n.encode(o,e,r),0>s&&(s=n.getSpan(e,r)))}o=r,r+=s}return o+i-n}fromArray(t){let e=this.makeDestinationObject();for(let r of this.fields)void 0!==r.property&&0<t.length&&(e[r.property]=t.shift());return e}layoutFor(t){if("string"!=typeof t)throw TypeError("property must be string");for(let e of this.fields)if(e.property===t)return e}offsetOf(t){if("string"!=typeof t)throw TypeError("property must be string");let e=0;for(let r of this.fields){if(r.property===t)return e;0>r.span?e=-1:0<=e&&(e+=r.span)}}};let UnionDiscriminator=class UnionDiscriminator{constructor(t){this.property=t}decode(){throw Error("UnionDiscriminator is abstract")}encode(){throw Error("UnionDiscriminator is abstract")}};let UnionLayoutDiscriminator=class UnionLayoutDiscriminator extends UnionDiscriminator{constructor(t,e){if(!(t instanceof ExternalLayout&&t.isCount()))throw TypeError("layout must be an unsigned integer ExternalLayout");super(e||t.property||"variant"),this.layout=t}decode(t,e){return this.layout.decode(t,e)}encode(t,e,r){return this.layout.encode(t,e,r)}};let Union=class Union extends Layout{constructor(t,e,r){let n=t instanceof UInt||t instanceof UIntBE;if(n)t=new UnionLayoutDiscriminator(new OffsetLayout(t));else if(t instanceof ExternalLayout&&t.isCount())t=new UnionLayoutDiscriminator(t);else if(!(t instanceof UnionDiscriminator))throw TypeError("discr must be a UnionDiscriminator or an unsigned integer layout");if(void 0===e&&(e=null),!(null===e||e instanceof Layout))throw TypeError("defaultLayout must be null or a Layout");if(null!==e){if(0>e.span)throw Error("defaultLayout must have constant span");void 0===e.property&&(e=e.replicate("content"))}let o=-1;e&&0<=(o=e.span)&&n&&(o+=t.layout.span),super(o,r),this.discriminator=t,this.usesPrefixDiscriminator=n,this.defaultLayout=e,this.registry={};let i=this.defaultGetSourceVariant.bind(this);this.getSourceVariant=function(t){return i(t)},this.configGetSourceVariant=function(t){i=t.bind(this)}}getSpan(t,e){if(0<=this.span)return this.span;void 0===e&&(e=0);let r=this.getVariant(t,e);if(!r)throw Error("unable to determine span for unrecognized variant");return r.getSpan(t,e)}defaultGetSourceVariant(t){if(t.hasOwnProperty(this.discriminator.property)){if(this.defaultLayout&&t.hasOwnProperty(this.defaultLayout.property))return;let e=this.registry[t[this.discriminator.property]];if(e&&(!e.layout||t.hasOwnProperty(e.property)))return e}else for(let e in this.registry){let r=this.registry[e];if(t.hasOwnProperty(r.property))return r}throw Error("unable to infer src variant")}decode(t,e){let r;void 0===e&&(e=0);let n=this.discriminator,o=n.decode(t,e),i=this.registry[o];if(void 0===i){let s=0;i=this.defaultLayout,this.usesPrefixDiscriminator&&(s=n.layout.span),(r=this.makeDestinationObject())[n.property]=o,r[i.property]=this.defaultLayout.decode(t,e+s)}else r=i.decode(t,e);return r}encode(t,e,r){void 0===r&&(r=0);let n=this.getSourceVariant(t);if(void 0===n){let n=this.discriminator,o=this.defaultLayout,i=0;return this.usesPrefixDiscriminator&&(i=n.layout.span),n.encode(t[n.property],e,r),i+o.encode(t[o.property],e,r+i)}return n.encode(t,e,r)}addVariant(t,e,r){let n=new VariantLayout(this,t,e,r);return this.registry[t]=n,n}getVariant(t,e){let r=t;return E.isBuffer(t)&&(void 0===e&&(e=0),r=this.discriminator.decode(t,e)),this.registry[r]}};let VariantLayout=class VariantLayout extends Layout{constructor(t,e,r,n){if(!(t instanceof Union))throw TypeError("union must be a Union");if(!Number.isInteger(e)||0>e)throw TypeError("variant must be a (non-negative) integer");if("string"==typeof r&&void 0===n&&(n=r,r=null),r){if(!(r instanceof Layout))throw TypeError("layout must be a Layout");
1if(null!==t.defaultLayout&&0<=r.span&&r.span>t.defaultLayout.span)throw Error("variant span exceeds span of containing union");if("string"!=typeof n)throw TypeError("variant must have a String property")}let o=t.span;0>t.span&&0<=(o=r?r.span:0)&&t.usesPrefixDiscriminator&&(o+=t.discriminator.layout.span),super(o,n),this.union=t,this.variant=e,this.layout=r||null}getSpan(t,e){if(0<=this.span)return this.span;void 0===e&&(e=0);let r=0;return this.union.usesPrefixDiscriminator&&(r=this.union.discriminator.layout.span),r+this.layout.getSpan(t,e+r)}decode(t,e){let r=this.makeDestinationObject();if(void 0===e&&(e=0),this!==this.union.getVariant(t,e))throw Error("variant mismatch");let n=0;return this.union.usesPrefixDiscriminator&&(n=this.union.discriminator.layout.span),this.layout?r[this.property]=this.layout.decode(t,e+n):this.property?r[this.property]=!0:this.union.usesPrefixDiscriminator&&(r[this.union.discriminator.property]=this.variant),r}encode(t,e,r){void 0===r&&(r=0);let n=0;if(this.union.usesPrefixDiscriminator&&(n=this.union.discriminator.layout.span),this.layout&&!t.hasOwnProperty(this.property))throw TypeError("variant lacks property "+this.property);this.union.discriminator.encode(this.variant,e,r);let o=n;if(this.layout&&(this.layout.encode(t[this.property],e,r+n),o+=this.layout.getSpan(e,r+n),0<=this.union.span&&o>this.union.span))throw Error("encoded variant overruns containing union");return o}fromArray(t){if(this.layout)return this.layout.fromArray(t)}};let Blob$1=class Blob$1 extends Layout{constructor(t,e){if(!(t instanceof ExternalLayout&&t.isCount()||Number.isInteger(t)&&0<=t))throw TypeError("length must be positive integer or an unsigned integer ExternalLayout");let r=-1;t instanceof ExternalLayout||(r=t),super(r,e),this.length=t}getSpan(t,e){let r=this.span;return 0>r&&(r=this.length.decode(t,e)),r}decode(t,e){void 0===e&&(e=0);let r=this.span;return 0>r&&(r=this.length.decode(t,e)),t.slice(e,e+r)}encode(t,e,r){let n=this.length;if(this.length instanceof ExternalLayout&&(n=t.length),!(E.isBuffer(t)&&n===t.length))throw TypeError(nameWithProperty("Blob.encode",this)+" requires (length "+n+") Buffer as src");if(r+n>e.length)throw RangeError("encoding overruns Buffer");return e.write(t.toString("hex"),r,n,"hex"),this.length instanceof ExternalLayout&&this.length.encode(n,e,r),n}};var offset=(t,e,r)=>new OffsetLayout(t,e,r),u8=t=>new UInt(1,t),u32=t=>new UInt(4,t),ns64=t=>new NearInt64(t),struct=(t,e,r)=>new Structure(t,e,r),union=(t,e,r)=>new Union(t,e,r),blob=(t,e)=>new Blob$1(t,e);let RustStringLayout=class RustStringLayout extends t0{constructor(t){super(-1,t),this.property=t,this.layout=struct([u32("length"),u32("lengthPadding"),blob(offset(u32(),-8),"chars")],this.property)}encode(t,e,r=0){if(null==t)return this.layout.span;let n={chars:E.from(t,"utf8")};return this.layout.encode(n,e,r)}decode(t,e=0){let r=this.layout.decode(t,e);return r.chars.toString()}getSpan(t,e=0){return u32().span+u32().span+new(l())(new Uint8Array(t).slice(e,e+4),10,"le").toNumber()}};function rustStringLayout(t){return new RustStringLayout(t)}function publicKey$2(t){return blob(32,t)}let t1=union(u32("instruction"));t1.addVariant(0,struct([ns64("lamports"),ns64("space"),publicKey$2("owner")]),"createAccount"),t1.addVariant(1,struct([publicKey$2("owner")]),"assign"),t1.addVariant(2,struct([ns64("lamports")]),"transfer"),t1.addVariant(3,struct([publicKey$2("base"),rustStringLayout("seed"),ns64("lamports"),ns64("space"),publicKey$2("owner")]),"createAccountWithSeed"),t1.addVariant(4,struct([publicKey$2("authorized")]),"advanceNonceAccount"),t1.addVariant(5,struct([ns64("lamports")]),"withdrawNonceAccount"),t1.addVariant(6,struct([publicKey$2("authorized")]),"initializeNonceAccount"),t1.addVariant(7,struct([publicKey$2("authorized")]),"authorizeNonceAccount"),t1.addVariant(8,struct([ns64("space")]),"allocate"),t1.addVariant(9,struct([publicKey$2("base"),rustStringLayout("seed"),ns64("space"),publicKey$2("owner")]),"allocateWithSeed"),t1.addVariant(10,struct([publicKey$2("base"),rustStringLayout("seed"),publicKey$2("owner")]),"assignWithSeed"),t1.addVariant(11,struct([ns64("lamports"),rustStringLayout("seed"),publicKey$2("owner")]),"transferWithSeed"),Object.values(t1.registry).map(t=>t.span);let WrappedLayout$1=class WrappedLayout$1 extends t0{constructor(t,e,r,n){super(t.span,n),this.layout=t,this.decoder=e,this.encoder=r}decode(t,e){return this.decoder(this.layout.decode(t,e))}encode(t,e,r){return this.layout.encode(this.encoder(t),e,r)}getSpan(t,e){return this.layout.getSpan(t,e)}};function publicKey$1(t){return new WrappedLayout$1(blob(32),t=>new c.PublicKey(t),t=>t.toBuffer(),t)}struct([u32("version"),u32("state"),publicKey$1("authorizedPubkey"),publicKey$1("nonce"),struct([new NearUInt64("lamportsPerSignature")
1],"feeCalculator")]),new c.PublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"),new c.PublicKey("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");var t2={exports:{}};n=t2.exports,o="undefined"!=typeof self?self:T,s=i=function(){function F(){this.fetch=!1,this.DOMException=o.DOMException}return F.prototype=o,new F}(),function(t){var e={searchParams:"URLSearchParams"in s,iterable:"Symbol"in s&&"iterator"in Symbol,blob:"FileReader"in s&&"Blob"in s&&function(){try{return new Blob,!0}catch(t){return!1}}(),formData:"FormData"in s,arrayBuffer:"ArrayBuffer"in s};function isDataView(t){return t&&DataView.prototype.isPrototypeOf(t)}if(e.arrayBuffer)var r=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],n=ArrayBuffer.isView||function(t){return t&&r.indexOf(Object.prototype.toString.call(t))>-1};function normalizeName(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(t))throw TypeError("Invalid character in header field name");return t.toLowerCase()}function normalizeValue(t){return"string"!=typeof t&&(t=String(t)),t}function iteratorFor(t){var r={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return e.iterable&&(r[Symbol.iterator]=function(){return r}),r}function Headers(t){this.map={},t instanceof Headers?t.forEach(function(t,e){this.append(e,t)},this):Array.isArray(t)?t.forEach(function(t){this.append(t[0],t[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(e){this.append(e,t[e])},this)}function consumed(t){if(t.bodyUsed)return Promise.reject(TypeError("Already read"));t.bodyUsed=!0}function fileReaderReady(t){return new Promise(function(e,r){t.onload=function(){e(t.result)},t.onerror=function(){r(t.error)}})}function readBlobAsArrayBuffer(t){var e=new FileReader,r=fileReaderReady(e);return e.readAsArrayBuffer(t),r}function readBlobAsText(t){var e=new FileReader,r=fileReaderReady(e);return e.readAsText(t),r}function readArrayBufferAsText(t){for(var e=new Uint8Array(t),r=Array(e.length),n=0;n<e.length;n++)r[n]=String.fromCharCode(e[n]);return r.join("")}function bufferClone(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function Body(){return this.bodyUsed=!1,this._initBody=function(t){this._bodyInit=t,t?"string"==typeof t?this._bodyText=t:e.blob&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:e.formData&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:e.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():e.arrayBuffer&&e.blob&&isDataView(t)?(this._bodyArrayBuffer=bufferClone(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):e.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(t)||n(t))?this._bodyArrayBuffer=bufferClone(t):this._bodyText=t=Object.prototype.toString.call(t):this._bodyText="",!this.headers.get("content-type")&&("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):e.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},e.blob&&(this.blob=function(){var t=consumed(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(!this._bodyFormData)return Promise.resolve(new Blob([this._bodyText]));throw Error("could not read FormData body as blob")},this.arrayBuffer=function(){return this._bodyArrayBuffer?consumed(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(readBlobAsArrayBuffer)}),this.text=function(){var t=consumed(this);if(t)return t;if(this._bodyBlob)return readBlobAsText(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer));if(!this._bodyFormData)return Promise.resolve(this._bodyText);throw Error("could not read FormData body as text")},e.formData&&(this.formData=function(){return this.text().then(decode)}),this.json=function(){return this.text().then(JSON.parse)},this}Headers.prototype.append=function(t,e){t=normalizeName(t),e=normalizeValue(e);var r=this.map[t];this.map[t]=r?r+", "+e:e},Headers.prototype.delete=function(t){delete this.map[normalizeName(t)]},Headers.prototype.get=function(t){return t=normalizeName(t),this.has(t)?this.map[t]:null},Headers.prototype.has=function(t){return this.map.hasOwnProperty(normalizeName(t))},Headers.prototype.set=function(t,e){this.map[normalizeName(t)]=normalizeValue(e)},Headers.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)},Headers.prototype.keys=function(){var t=[];return this.forEach(function(e,r){t.push(r)}),iteratorFor(t)}
1,Headers.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),iteratorFor(t)},Headers.prototype.entries=function(){var t=[];return this.forEach(function(e,r){t.push([r,e])}),iteratorFor(t)},e.iterable&&(Headers.prototype[Symbol.iterator]=Headers.prototype.entries);var o=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function normalizeMethod(t){var e=t.toUpperCase();return o.indexOf(e)>-1?e:t}function Request(t,e){var r=(e=e||{}).body;if(t instanceof Request){if(t.bodyUsed)throw TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new Headers(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,r||null==t._bodyInit||(r=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"same-origin",(e.headers||!this.headers)&&(this.headers=new Headers(e.headers)),this.method=normalizeMethod(e.method||this.method||"GET"),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&r)throw TypeError("Body not allowed for GET or HEAD requests");this._initBody(r)}function decode(t){var e=new FormData;return t.trim().split("&").forEach(function(t){if(t){var r=t.split("="),n=r.shift().replace(/\+/g," "),o=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(n),decodeURIComponent(o))}}),e}function parseHeaders(t){var e=new Headers;return t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach(function(t){var r=t.split(":"),n=r.shift().trim();if(n){var o=r.join(":").trim();e.append(n,o)}}),e}function Response(t,e){e||(e={}),this.type="default",this.status=void 0===e.status?200:e.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in e?e.statusText:"OK",this.headers=new Headers(e.headers),this.url=e.url||"",this._initBody(t)}Request.prototype.clone=function(){return new Request(this,{body:this._bodyInit})},Body.call(Request.prototype),Body.call(Response.prototype),Response.prototype.clone=function(){return new Response(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new Headers(this.headers),url:this.url})},Response.error=function(){var t=new Response(null,{status:0,statusText:""});return t.type="error",t};var i=[301,302,303,307,308];Response.redirect=function(t,e){if(-1===i.indexOf(e))throw RangeError("Invalid status code");return new Response(null,{status:e,headers:{location:t}})},t.DOMException=s.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(t,e){this.message=t,this.name=e;var r=Error(t);this.stack=r.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function fetch(r,n){return new Promise(function(o,i){var s=new Request(r,n);if(s.signal&&s.signal.aborted)return i(new t.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function abortXhr(){a.abort()}a.onload=function(){var t={status:a.status,statusText:a.statusText,headers:parseHeaders(a.getAllResponseHeaders()||"")};t.url="responseURL"in a?a.responseURL:t.headers.get("X-Request-URL"),o(new Response("response"in a?a.response:a.responseText,t))},a.onerror=function(){i(TypeError("Network request failed"))},a.ontimeout=function(){i(TypeError("Network request failed"))},a.onabort=function(){i(new t.DOMException("Aborted","AbortError"))},a.open(s.method,s.url,!0),"include"===s.credentials?a.withCredentials=!0:"omit"===s.credentials&&(a.withCredentials=!1),"responseType"in a&&e.blob&&(a.responseType="blob"),s.headers.forEach(function(t,e){a.setRequestHeader(e,t)}),s.signal&&(s.signal.addEventListener("abort",abortXhr),a.onreadystatechange=function(){4===a.readyState&&s.signal.removeEventListener("abort",abortXhr)}),a.send(void 0===s._bodyInit?null:s._bodyInit)})}fetch.polyfill=!0,s.fetch||(s.fetch=fetch,s.Headers=Headers,s.Request=Request,s.Response=Response),t.Headers=Headers,t.Request=Request,t.Response=Response,t.fetch=fetch,Object.defineProperty(t,"__esModule",{value:!0})}({}),i.fetch.ponyfill=!0,delete i.fetch.polyfill,(n=i.fetch).default=i.fetch,n.fetch=i.fetch,n.Headers=i.Headers,n.Request=i.Request,n.Response=i.Response,t2.exports=n,t2.exports;let t3=f.rustEnum([f.struct([],"uninitialized"),f.struct([f.option(f.publicKey(),"authorityAddress")],"buffer"),f.struct([f.publicKey("programdataAddress")],"program"),f.struct([f.u64("slot"),f.option(f.publicKey(),"upgradeAuthorityAddress")],"programData")],void 0,f.u32());function splitArgsAndCtx(t,e){var r,n;let o={},i=t.args?t.args.length:0;if(e.length>i){if(e.length!==i+1)throw Error(`provided too many arguments ${e} to instruction ${null==t?void 0:t.name} expecting: ${null!==(n=null===(r=t.args)||void 0===r?void 0:r.map(t=>t.name))&&void 0!==n?n:[]}`);o=e.pop()}return[e,o]}
1let InstructionNamespaceFactory=class InstructionNamespaceFactory{static build(t,e,r){if("_inner"===t.name)throw new IdlError("the _inner name is reserved");let ix=(...n)=>{let[o,i]=splitArgsAndCtx(t,[...n]);validateAccounts(t.accounts,i.accounts),[...n];let s=ix.accounts(i.accounts);return void 0!==i.remainingAccounts&&s.push(...i.remainingAccounts),isSet("debug-logs")&&console.log("Outgoing account metas:",s),new c.TransactionInstruction({keys:s,programId:r,data:e(t.name,toInstruction(t,...o))})};return ix.accounts=e=>InstructionNamespaceFactory.accountsArray(e,t.accounts,r,t.name),ix}static accountsArray(t,e,r,n){return t?e.map(e=>{let o;if(isCompositeAccounts(e)){let o=t[e.name];return InstructionNamespaceFactory.accountsArray(o,e.accounts,r,n).flat()}try{o=translateAddress(t[e.name])}catch(t){throw Error(`Wrong input type for account "${e.name}" in the instruction accounts object${void 0!==n?' for instruction "'+n+'"':""}. Expected PublicKey or string.`)}let i=e.optional&&o.equals(r),s=!!(e.writable&&!i),a=!!(e.signer&&!i);return{pubkey:o,isWritable:s,isSigner:a}}).flat():[]}};let TransactionFactory=class TransactionFactory{static build(t,e){return(...r)=>{var n,o,i;let[,s]=splitArgsAndCtx(t,[...r]),a=new c.Transaction;if(s.preInstructions&&s.instructions)throw Error("instructions is deprecated, use preInstructions");return null===(n=s.preInstructions)||void 0===n||n.forEach(t=>a.add(t)),null===(o=s.instructions)||void 0===o||o.forEach(t=>a.add(t)),a.add(e(...r)),null===(i=s.postInstructions)||void 0===i||i.forEach(t=>a.add(t)),a}}};let RpcFactory=class RpcFactory{static build(t,e,r,n){let rpc=async(...o)=>{var i;let s=e(...o),[,a]=splitArgsAndCtx(t,[...o]);if(void 0===n.sendAndConfirm)throw Error("This function requires 'Provider.sendAndConfirm' to be implemented.");try{return await n.sendAndConfirm(s,null!==(i=a.signers)&&void 0!==i?i:[],a.options)}catch(t){throw translateError(t,r)}};return rpc}};let AccountFactory=class AccountFactory{static build(t,e,r,n){var o;return(null!==(o=t.accounts)&&void 0!==o?o:[]).reduce((o,i)=>(o[i.name]=new AccountClient(t,i,r,n,e),o),{})}};let AccountClient=class AccountClient{get size(){return this._size}get programId(){return this._programId}get provider(){return this._provider}get coder(){return this._coder}constructor(t,e,r,n,o){this._idlAccount=e,this._programId=r,this._provider=null!=n?n:getProvider(),this._coder=null!=o?o:new BorshCoder(t),this._size=this._coder.accounts.size(e.name)}async fetchNullable(t,e){let{data:r}=await this.fetchNullableAndContext(t,e);return r}async fetchNullableAndContext(t,e){let r=await this.getAccountInfoAndContext(t,e),{value:n,context:o}=r;return{data:n&&0!==n.data.length?this._coder.accounts.decode(this._idlAccount.name,n.data):null,context:o}}async fetch(t,e){let{data:r}=await this.fetchNullableAndContext(t,e);if(null===r)throw Error(`Account does not exist or has no data ${t.toString()}`);return r}async fetchAndContext(t,e){let{data:r,context:n}=await this.fetchNullableAndContext(t,e);if(null===r)throw Error(`Account does not exist ${t.toString()}`);return{data:r,context:n}}async fetchMultiple(t,e){let r=await this.fetchMultipleAndContext(t,e);return r.map(t=>t?t.data:null)}async fetchMultipleAndContext(t,e){let r=await getMultipleAccountsAndContext(this._provider.connection,t.map(t=>translateAddress(t)),e);return r.map(t=>{if(null==t)return null;let{account:e,context:r}=t;return{data:this._coder.accounts.decode(this._idlAccount.name,e.data),context:r}})}async all(t){let e=this.coder.accounts.memcmp(this._idlAccount.name,t instanceof E?t:void 0),r=[];return(null==e?void 0:e.offset)!=void 0&&(null==e?void 0:e.bytes)!=void 0&&r.push({memcmp:{offset:e.offset,bytes:e.bytes}}),(null==e?void 0:e.dataSize)!=void 0&&r.push({dataSize:e.dataSize}),(await this._provider.connection.getProgramAccounts(this._programId,{commitment:this._provider.connection.commitment,filters:[...r,...Array.isArray(t)?t:[]]})).map(({pubkey:t,account:e})=>({publicKey:t,account:this._coder.accounts.decode(this._idlAccount.name,e.data)}))}subscribe(t,e){let r=t6.get(t.toString());if(r)return r.ee;let n=new(A());t=translateAddress(t);let o=this._provider.connection.onAccountChange(t,t=>{let e=this._coder.accounts.decode(this._idlAccount.name,t.data);n.emit("change",e)},e);return t6.set(t.toString(),{ee:n,listener:o}),n}async unsubscribe(t){let e=t6.get(t.toString());if(!e){console.warn("Address is not subscribed");return}t6&&await this._provider.connection.removeAccountChangeListener(e.listener).then(()=>{t6.delete(t.toString())}).catch(console.error)}async createInstruction(t,e){let r=this.size;if(void 0===this._provider.publicKey)throw Error("This function requires the Provider interface implementor to have a 'publicKey' field.");return c.SystemProgram.createAccount({fromPubkey:this._provider.publicKey,newAccountPubkey:t.publicKey,space:null!=e?e:r,lamports:await this._provider.connection.getMinimumBalanceForRentExemption(null!=e?e:r),programId:this._programId})}async getAccountInfo(t,e){return await this._provider.connection.getAccountInfo(translateAddress(t),e)}async getAccountInfoAndContext(t,e){return await this._provider.connection.getAccountInfoAndContext(translateAddress(t),e)}};let t6=new Map,t4="Program log: ",t8="Program data: ",t5=t4.length,t9=t8.length;let EventManager=class EventManager{constructor(t,e,r){this._programId=t,this._provider=e,this._eventParser=new EventParser(t,r),this._eventCallbacks=new Map,this._eventListeners=new Map,this._listenerIdCount=0}
1addEventListener(t,e){var r;let n=this._listenerIdCount;return this._listenerIdCount+=1,this._eventListeners.has(t)||this._eventListeners.set(t,[]),this._eventListeners.set(t,(null!==(r=this._eventListeners.get(t))&&void 0!==r?r:[]).concat(n)),this._eventCallbacks.set(n,[t,e]),void 0!==this._onLogsSubscriptionId||(this._onLogsSubscriptionId=this._provider.connection.onLogs(this._programId,(t,e)=>{if(!t.err)for(let r of this._eventParser.parseLogs(t.logs)){let n=this._eventListeners.get(r.name);n&&n.forEach(n=>{let o=this._eventCallbacks.get(n);if(o){let[,n]=o;n(r.data,e.slot,t.signature)}})}})),n}async removeEventListener(t){let e=this._eventCallbacks.get(t);if(!e)throw Error(`Event listener ${t} doesn't exist!`);let[r]=e,n=this._eventListeners.get(r);if(!n)throw Error(`Event listeners don't exist for ${r}!`);if(this._eventCallbacks.delete(t),n=n.filter(e=>e!==t),this._eventListeners.set(r,n),0===n.length&&this._eventListeners.delete(r),0===this._eventCallbacks.size){if(0!==this._eventListeners.size)throw Error(`Expected event listeners size to be 0 but got ${this._eventListeners.size}`);void 0!==this._onLogsSubscriptionId&&(await this._provider.connection.removeOnLogsListener(this._onLogsSubscriptionId),this._onLogsSubscriptionId=void 0)}}};let EventParser=class EventParser{constructor(t,e){this.coder=e,this.programId=t}*parseLogs(t,e=!1){let r=new LogScanner(t),n=new ExecutionContext,o=r.next();for(;null!==o;){let[t,i,s]=this.handleLog(n,o,e);t&&(yield t),i&&n.push(i),s&&n.pop(),o=r.next()}}handleLog(t,e,r){return t.stack.length>0&&t.program()===this.programId.toString()?this.handleProgramLog(e,r):[null,...this.handleSystemLog(e)]}handleProgramLog(t,e){if(!(t.startsWith(t4)||t.startsWith(t8)))return[null,...this.handleSystemLog(t)];{let r=t.startsWith(t4)?t.slice(t5):t.slice(t9),n=this.coder.events.decode(r);if(e&&null===n)throw Error(`Unable to decode event ${r}`);return[n,null,!1]}}handleSystemLog(t){let e=t.split(":")[0];return null!==e.match(/^Program (.*) success/g)?[null,!0]:e.startsWith(`Program ${this.programId.toString()} invoke`)?[this.programId.toString(),!1]:e.includes("invoke")?["cpi",!1]:[null,!1]}};let ExecutionContext=class ExecutionContext{constructor(){this.stack=[]}program(){if(!this.stack.length)throw Error("Expected the stack to have elements");return this.stack[this.stack.length-1]}push(t){this.stack.push(t)}pop(){if(!this.stack.length)throw Error("Expected the stack to have elements");this.stack.pop()}};let LogScanner=class LogScanner{constructor(t){this.logs=t}next(){if(0===this.logs.length)return null;let t=this.logs[0];return this.logs=this.logs.slice(1),t}};let SimulateFactory=class SimulateFactory{static build(t,e,r,n,o,i,s){let simulate=async(...a)=>{var c;let u;let l=e(...a),[,d]=splitArgsAndCtx(t,[...a]);if(void 0===n.simulate)throw Error("This function requires 'Provider.simulate' to be implemented.");try{u=await n.simulate(l,d.signers,null===(c=d.options)||void 0===c?void 0:c.commitment)}catch(t){throw translateError(t,r)}if(void 0===u)throw Error("Unable to simulate transaction");let h=u.logs;if(!h)throw Error("Simulated logs not found");let _=[];if(s.events)for(let t of new EventParser(i,o).parseLogs(h))_.push(t);return{events:_,raw:h}};return simulate}};function uint64(t){return new WrappedLayout(blob(8),t=>u64.fromBuffer(t),t=>t.toBuffer(),t)}function publicKey(t){return new WrappedLayout(blob(32),t=>new c.PublicKey(t),t=>t.toBuffer(),t)}let WrappedLayout=class WrappedLayout extends t0{constructor(t,e,r,n){super(t.span,n),this.layout=t,this.decoder=e,this.encoder=r}decode(t,e){return this.decoder(this.layout.decode(t,e))}encode(t,e,r){return this.layout.encode(this.encoder(t),e,r)}getSpan(t,e){return this.layout.getSpan(t,e)}};let COptionLayout=class COptionLayout extends t0{constructor(t,e){super(-1,e),this.layout=t,this.discriminator=u32()}encode(t,e,r=0){return null==t?this.layout.span+this.discriminator.encode(0,e,r):(this.discriminator.encode(1,e,r),this.layout.encode(t,e,r+4)+4)}decode(t,e=0){let r=this.discriminator.decode(t,e);if(0===r)return null;if(1===r)return this.layout.decode(t,e+4);throw Error("Invalid coption "+this.layout.property)}getSpan(t,e=0){return this.layout.getSpan(t,e+4)+4}};let u64=class u64 extends l(){toBuffer(){let t=super.toArray().reverse(),e=E.from(t);if(8===e.length)return e;if(e.length>=8)throw Error("u64 too large");let r=E.alloc(8);return e.copy(r),r}static fromBuffer(t){if(8!==t.length)throw Error(`Invalid buffer length: ${t.length}`);return new u64([...t].reverse().map(t=>`00${t.toString(16)}`.slice(-2)).join(""),16)}};let t7=struct([publicKey("mint"),publicKey("owner"),uint64("amount"),new COptionLayout(publicKey(),"delegate"),
1(t=>{let e=union(u8("discriminator"),null,t);return e.addVariant(0,struct([]),"uninitialized"),e.addVariant(1,struct([]),"initialized"),e.addVariant(2,struct([]),"frozen"),e})("state"),new COptionLayout(uint64(),"isNative"),uint64("delegatedAmount"),new COptionLayout(publicKey(),"closeAuthority")]);function decodeTokenAccount(t){return t7.decode(t)}let AccountsResolver=class AccountsResolver{constructor(t,e,r,n,o,i,s,a){this._args=t,this._accounts=e,this._provider=r,this._programId=n,this._idlIx=o,this._idlTypes=s,this._customResolver=a,this._accountStore=new AccountStore(r,i,n)}args(t){this._args=t}async resolve(){this.resolveEventCpi(this._idlIx.accounts),this.resolveConst(this._idlIx.accounts);let t=0;for(;await this.resolvePdasAndRelations(this._idlIx.accounts)+await this.resolveCustom()>0;)if(16==++t)throw Error("Reached maximum depth for account resolution")}resolveOptionals(t){Object.assign(this._accounts,this.resolveOptionalsHelper(t,this._idlIx.accounts))}get(t){let e=t.reduce((t,e)=>t&&t[e],this._accounts);if(e&&e.toBase58)return e}set(t,e){let r=this._accounts;t.forEach((n,o)=>{var i;let s=o===t.length-1;s&&(r[n]=e),r[n]=null!==(i=r[n])&&void 0!==i?i:{},r=r[n]})}resolveOptionalsHelper(t,e){let r={};for(let n of e){let e=n.name,o=t[e];void 0!==o&&(isPartialAccounts(o)?isCompositeAccounts(n)?r[e]=this.resolveOptionalsHelper(o,n.accounts):r[e]=flattenPartialAccounts(o,!0):null!==o?r[e]=translateAddress(o):n.optional&&(r[e]=this._programId))}return r}async resolveCustom(){if(this._customResolver){let{accounts:t,resolved:e}=await this._customResolver({args:this._args,accounts:this._accounts,provider:this._provider,programId:this._programId,idlIx:this._idlIx});return this._accounts=t,e}return 0}resolveEventCpi(t,e=[]){for(let r in t){let n=t[r];isCompositeAccounts(n)&&this.resolveEventCpi(n.accounts,[...e,n.name]);let o=+r+1;if(o===t.length)return;let i=t[r].name,s=t[o].name;if("eventAuthority"===i&&"program"===s){let t=[...e,i],r=[...e,s];this.get(t)||this.set(t,c.PublicKey.findProgramAddressSync([E.from("__event_authority")],this._programId)[0]),this.get(r)||this.set(r,this._programId);return}}}resolveConst(t,e=[]){for(let r of t){let t=r.name;if(isCompositeAccounts(r))this.resolveConst(r.accounts,[...e,t]);else if((r.signer||r.address)&&!this.get([...e,t])){if(r.signer){if(!this._provider.wallet)throw Error("This function requires the `Provider` interface implementor to have a `wallet` field.");this.set([...e,t],this._provider.wallet.publicKey)}r.address&&this.set([...e,t],translateAddress(r.address))}}}async resolvePdasAndRelations(t,e=[]){let r=0;for(let n of t){let t=n.name;if(isCompositeAccounts(n))r+=await this.resolvePdasAndRelations(n.accounts,[...e,t]);else if((n.pda||n.relations)&&!this.get([...e,t])){r++;try{if(n.pda){let r=await Promise.all(n.pda.seeds.map(t=>this.toBuffer(t,e)));if(r.some(t=>!t))continue;let o=await this.parseProgramId(n,e),[i]=c.PublicKey.findProgramAddressSync(r,o);this.set([...e,t],i)}}catch{}try{if(n.relations){let r=this.get([...e,n.relations[0]]);if(r){let n=await this._accountStore.fetchAccount({publicKey:r});this.set([...e,t],n[t])}}}catch{}}}return r}async parseProgramId(t,e=[]){var r;if(!(null===(r=t.pda)||void 0===r?void 0:r.program))return this._programId;let n=await this.toBuffer(t.pda.program,e);if(!n)throw Error(`Program seed not resolved: ${t.name}`);return new c.PublicKey(n)}async toBuffer(t,e=[]){switch(t.kind){case"const":return this.toBufferConst(t);case"arg":return await this.toBufferArg(t);case"account":return await this.toBufferAccount(t,e);default:throw Error(`Unexpected seed: ${t}`)}}toBufferConst(t){return this.toBufferValue("bytes",t.value)}async toBufferArg(t){let[e,...r]=t.path.split("."),n=this._idlIx.args.findIndex(t=>t.name===e);if(-1===n)throw Error(`Unable to find argument for seed: ${e}`);let o=r.reduce((t,e)=>(null!=t?t:{})[e],this._args[n]);if(void 0===o)return;let i=this.getType(this._idlIx.args[n].type,r);return this.toBufferValue(i,o)}async toBufferAccount(t,e=[]){let[r,...n]=t.path.split("."),o=this.get([...e,r]);if(!o)return;if(!n.length)return this.toBufferValue("pubkey",o);if(!t.account)throw Error(`Seed account is required in order to resolve type: ${t.path}`);let i=await this._accountStore.fetchAccount({publicKey:o,name:t.account}),s=i,a=n;for(;a.length>0;)s=s[a[0]],a=a.slice(1);if(void 0===s)return;let c=this.getType({defined:{name:t.account}},n);return this.toBufferValue(c,s)}toBufferValue(t,e){switch(t){case"u8":case"i8":return E.from([e]);case"u16":case"i16":return new(l())(e).toArrayLike(E,"le",2);case"u32":case"i32":return new(l())(e).toArrayLike(E,"le",4);case"u64":case"i64":return new(l())(e).toArrayLike(E,"le",8);case"u128":case"i128":return new(l())(e).toArrayLike(E,"le",16);case"u256":case"i256":return new(l())(e).toArrayLike(E,"le",32);case"string":case"bytes":return E.from(e);case"pubkey":return e.toBuffer();default:if(null==t?void 0:t.array)return E.from(e);throw Error(`Unexpected seed type: ${t}`)}}getType(t,e=[]){var r;let n=null===(r=null==t?void 0:t.defined)||void 0===r?void 0:r.name;if(n){if("tokenAccount"===n)switch(e.at(0)){case"mint":case"owner":return"pubkey";case"amount":case"delagatedAmount":return"u64";default:throw Error(`Unknown token account path: ${e}`)}let t=this._idlTypes.find(t=>t.name===n);if(!t)throw Error(`Type not found: ${n}`);let[r,...o]=e,i=t.type.fields,s=i.find(t=>t.name===r);if(!s)throw Error(`Field not found: ${r}`);return this.getType(s.type,o)}return t}};let AccountStore=class AccountStore{constructor(t,e,r){this._provider=t,this._cache=new Map,this._idls={},this._idls[r.toBase58()]=e}async fetchAccount({publicKey:t,name:e}){let r=t.toBase58();if(!this._cache.has(r)){let n=await this._provider.connection.getAccountInfo(t);if(null===n)throw Error(`Account not found: ${r}`);if("tokenAccount"===e){let t=decodeTokenAccount(n.data);this._cache.set(r,t)}else{let t=await this.getAccountsNs(n.owner);if(t){let e=Object.values(t)[0];if(e){let t=e.coder.accounts.decodeAny(n.data);this._cache.set(r,t)}}}}return this._cache.get(r)}async getAccountsNs(t){let e=t.toBase58();if(!this._idls[e]){let r=await Program.fetchIdl(t,this._provider);if(r){let t=new Program(r,this._provider);this._idls[e]=t.account}}return this._idls[e]}};let MethodsBuilderFactory=class MethodsBuilderFactory{static build(t,e,r,n,o,i,s,a,c,u,l){return(...d)=>new MethodsBuilder(d,n,o,i,s,a,t,e,r,c,u,l)}};function isPartialAccounts(t){return"object"==typeof t&&null!==t&&!("_bn"in t)}function flattenPartialAccounts(t,e){let r={};for(let n in t){let o=t[n];if(null===o){if(e)throw Error("Failed to resolve optionals due to IDL type mismatch with input accounts!");continue}r[n]=isPartialAccounts(o)?flattenPartialAccounts(o,!0):translateAddress(o)}return r}let MethodsBuilder=class MethodsBuilder{constructor(t,e,r,n,o,i,s,a,c,u,l,d){this._args=t,this._ixFn=e,this._txFn=r,this._rpcFn=n,this._simulateFn=o,this._viewFn=i,this._accounts={},this._remainingAccounts=[],this._signers=[],this._preInstructions=[],this._postInstructions=[],this._resolveAccounts=!0,this._accountsResolver=new AccountsResolver(t,this._accounts,s,a,c,u,l,d)}args(t){this._args=t,this._accountsResolver.args(t)}accounts(t){return this.accountsPartial(t)}accountsPartial(t){return this._resolveAccounts=!0,this._accountsResolver.resolveOptionals(t),this}accountsStrict(t){return this._resolveAccounts=!1,this._accountsResolver.resolveOptionals(t),this}signers(t){return this._signers=this._signers.concat(t),this}remainingAccounts(t){return this._remainingAccounts=this._remainingAccounts.concat(t),this}preInstructions(t,e=!1){return e?this._preInstructions=t.concat(this._preInstructions):this._preInstructions=this._preInstructions.concat(t),this}postInstructions(t){return this._postInstructions=this._postInstructions.concat(t),this}async pubkeys(){return this._resolveAccounts&&await this._accountsResolver.resolve(),this._accounts}async rpc(t){return this._resolveAccounts&&await this._accountsResolver.resolve(),this._rpcFn(...this._args,{accounts:this._accounts,signers:this._signers,remainingAccounts:this._remainingAccounts,preInstructions:this._preInstructions,postInstructions:this._postInstructions,options:t})}async rpcAndKeys(t){let e=await this.pubkeys();return{pubkeys:e,signature:await this.rpc(t)}}async view(t){if(this._resolveAccounts&&await this._accountsResolver.resolve(),!this._viewFn)throw Error("Method does not support views");return this._viewFn(...this._args,{accounts:this._accounts,signers:this._signers,remainingAccounts:this._remainingAccounts,preInstructions:this._preInstructions,postInstructions:this._postInstructions,options:t})}async simulate(t){return this._resolveAccounts&&await this._accountsResolver.resolve(),this._simulateFn(...this._args,{accounts:this._accounts,signers:this._signers,remainingAccounts:this._remainingAccounts,preInstructions:this._preInstructions,postInstructions:this._postInstructions,options:t})}async instruction(){return this._resolveAccounts&&await this._accountsResolver.resolve(),this._ixFn(...this._args,{accounts:this._accounts,signers:this._signers,remainingAccounts:this._remainingAccounts,preInstructions:this._preInstructions,postInstructions:this._postInstructions})}async prepare(){return{instruction:await this.instruction(),pubkeys:await this.pubkeys(),signers:this._signers}}async transaction(){return this._resolveAccounts&&await this._accountsResolver.resolve(),this._txFn(...this._args,{accounts:this._accounts,signers:this._signers,remainingAccounts:this._remainingAccounts,preInstructions:this._preInstructions,postInstructions:this._postInstructions})}};let ViewFactory=class ViewFactory{static build(t,e,r,n){let o=e.accounts.find(t=>t.writable),i=!!e.returns;if(o||!i)return;let view=async(...o)=>{let i=await r(...o),s=`Program return: ${t} `,a=i.raw.find(t=>t.startsWith(s));if(!a)throw Error("View expected return log");let c=decode(a.slice(s.length)),u=e.returns;if(!u)throw Error("View expected return type");let l=IdlCoder.fieldLayout({type:u},n.types);return l.decode(c)};return view}};let NamespaceFactory=class NamespaceFactory{static build(t,e,r,n,o){let i={},s={},a={},c={},u={},l={},d=parseIdlErrors(t),h=t.accounts?AccountFactory.build(t,e,r,n):{};return t.instructions.forEach(_=>{let p=InstructionNamespaceFactory.build(_,(t,r)=>e.instruction.encode(t,r),r),f=TransactionFactory.build(_,p),R=RpcFactory.build(_,f,d,n),y=SimulateFactory.build(_,f,d,n,e,r,t),A=ViewFactory.build(r,_,y,t),E=MethodsBuilderFactory.build(n,r,_,p,f,R,y,A,h,t.types||[],null==o?void 0:o(_)),m=_.name;s[m]=p,a[m]=f,i[m]=R,c[m]=y,u[m]=E,A&&(l[m]=A)}),[i,s,a,h,c,u,l]}};let Program=class Program{get programId(){return this._programId}get idl(){return this._idl}get rawIdl(){return this._rawIdl}get coder(){return this._coder}get provider(){return this._provider}constructor(t,e=getProvider(),r,n){let o=convertIdlToCamelCase(t);this._idl=o,this._rawIdl=t,this._provider=e,this._programId=translateAddress(t.address),this._coder=null!=r?r:new BorshCoder(o),this._events=new EventManager(this._programId,e,this._coder);let[i,s,a,c,u,l,d]=NamespaceFactory.build(o,this._coder,this._programId,e,n);this.rpc=i,this.instruction=s,this.transaction=a,this.account=c,this.simulate=u,this.methods=l,this.views=d}static async at(t,e){let r=translateAddress(t),n=await Program.fetchIdl(r,e);if(!n)throw Error(`IDL not found for program: ${t.toString()}`);return new Program(n,e)}static async fetchIdl(t,e){e=null!=e?e:getProvider();let r=translateAddress(t),n=await idlAddress(r),o=await e.connection.getAccountInfo(n);if(!o)return null;let i=decodeIdlAccount(o.data.slice(8)),s=(0,R.rr)(i.data);return JSON.parse(decode$2(s))}addEventListener(t,e){return this._events.addEventListener(t,e)}async removeEventListener(t){return await this._events.removeEventListener(t)}};new c.PublicKey("11111111111111111111111111111111")}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.