@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 +1 @@
|
|
|
1
|
-
"use strict";var _=Object.defineProperty;var v=(h,e,t)=>e in h?_(h,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):h[e]=t;var c=(h,e,t)=>(v(h,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("./index-
|
|
1
|
+
"use strict";var _=Object.defineProperty;var v=(h,e,t)=>e in h?_(h,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):h[e]=t;var c=(h,e,t)=>(v(h,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("./index-BHWhOqWI.js");const i=require("./cosmwasm-8FJsT7LT.js"),o=require("./unsignedTransaction-DZq5iThY.js"),r=require("./index-C1oy9Lkm.js"),C=require("./chain-BteoJHpg.js");class l{constructor(e,t,s,n){c(this,"network");c(this,"chain");c(this,"rpc");c(this,"contracts");c(this,"tokenBridge");c(this,"translator");this.network=e,this.chain=t,this.rpc=s,this.contracts=n;const a=this.contracts.tokenBridge;if(!a)throw new Error(`Wormhole Token Bridge contract for domain ${t} not found`);if(this.tokenBridge=a,this.translator=this.contracts.translator,this.translator!==void 0&&this.translator==="")throw new Error("Translator address may be undefined but not empty string")}static async fromRpc(e,t){const[s,n]=await i.CosmwasmPlatform.chainFromRpc(e),a=t[n];if(a.network!==s)throw new Error(`Network mismatch: ${a.network} != ${s}`);return new l(s,n,e,t[n].contracts)}async isWrappedAsset(e){try{return await this.getOriginalAsset(e),!0}catch{}return!1}async hasWrappedAsset(e){try{return await this.getWrappedAsset(e),!0}catch{}return!1}async getWrappedAsset(e){if(e.chain===this.chain)throw new Error(`Expected foreign chain, got ${e.chain}`);if(r.isNative(e.address))throw new Error("Native asset cannot be a wrapped asset");const t=r.b64.encode(e.address.toUniversalAddress().toUint8Array()),{address:s}=await this.rpc.queryContractSmart(this.tokenBridge,{wrapped_registry:{chain:r.toChainId(e.chain),address:t}});return r.toNative(this.chain,s)}async getOriginalAsset(e){let t=new i.CosmwasmAddress(e);t.denomType==="factory"&&(t=i.Gateway.factoryToCw20(t));const s=await this.rpc.queryContractSmart(t.toString(),{wrapped_asset_info:{}}),n=r.toChain(s.asset_chain),a=r.b64.decode(s.asset_address);return{chain:n,address:new r.UniversalAddress(new Uint8Array(a))}}async isTransferCompleted(e){const t=r.b64.encode(r.serialize(e));return(await this.rpc.queryContractSmart(this.tokenBridge,{is_vaa_redeemed:{vaa:t}})).is_redeemed}async*createAttestation(e,t){if(!t)throw new Error("Payer required to create attestation");const s=new i.CosmwasmAddress(e).toString(),n=new i.CosmwasmAddress(t).toString(),a=0,w=r.isNative(e)?{native_token:{denom:i.CosmwasmPlatform.getNativeDenom(this.network,this.chain)}}:{token:{contract_addr:s}};yield this.createUnsignedTx({msgs:[o.buildExecuteMsg(n,this.tokenBridge,{create_asset_meta:{asset_info:w,nonce:a}})],fee:o.computeFee(this.network,this.chain),memo:"Wormhole - Create Attestation"},"TokenBridge.createAttestation")}async*submitAttestation(e,t){if(!t)throw new Error("Payer required to submit attestation");const s=new i.CosmwasmAddress(t).toString();yield this.createUnsignedTx({msgs:[o.buildExecuteMsg(s,this.tokenBridge,{submit_vaa:{data:r.serialize(e)}})],fee:o.computeFee(this.network,this.chain),memo:"Wormhole - Submit Attestation"},"TokenBridge.submitAttestation")}async*transfer(e,t,s,n,a){const w=Math.round(Math.random()*1e5),u="0",k=r.toChainId(t.chain),A=r.b64.encode(t.address.toUniversalAddress().toUint8Array()),T=i.CosmwasmPlatform.getNativeDenom(this.network,this.chain),f=r.isNative(s);let d=f?T:s.toString();d.startsWith("factory")&&(d=i.Gateway.factoryToCw20(new i.CosmwasmAddress(d)).toString());const g=new i.CosmwasmAddress(e).toString(),p=m=>{const y={asset:{amount:n.toString(),info:m},recipient_chain:k,recipient:A,fee:u,nonce:w};return a?{initiate_transfer_with_payload:{...y,payload:r.b64.encode(a)}}:{initiate_transfer:y}};if(f){const m=[o.buildExecuteMsg(g,this.tokenBridge,{deposit_tokens:{}},[{amount:n.toString(),denom:d}]),o.buildExecuteMsg(g,this.tokenBridge,p({native_token:{denom:d}}))];yield this.createUnsignedTx({msgs:m,fee:o.computeFee(this.network,this.chain),memo:"Wormhole - Initiate Native Transfer"},"TokenBridge.transferNative")}else{const m=[o.buildExecuteMsg(g,d,{increase_allowance:{spender:this.tokenBridge,amount:n.toString(),expires:{never:{}}}}),o.buildExecuteMsg(g,this.tokenBridge,p({token:{contract_addr:d}}),[{amount:n.toString(),denom:d}])];yield this.createUnsignedTx({msgs:m,fee:o.computeFee(this.network,this.chain),memo:"Wormhole - Initiate Transfer"},"TokenBridge.transfer")}}async*redeem(e,t,s=!0){const n=r.b64.encode(r.serialize(t)),a=new i.CosmwasmAddress(e).toString(),u=this.translator&&new i.CosmwasmAddress(this.translator).toUniversalAddress().equals(t.payload.to.address)?o.buildExecuteMsg(a,this.translator,{complete_transfer_and_convert:{vaa:n}}):o.buildExecuteMsg(a,this.tokenBridge,{submit_vaa:{data:n}});yield this.createUnsignedTx({msgs:[u],fee:o.computeFee(this.network,this.chain),memo:"Wormhole - Complete Transfer"},"TokenBridge.redeem")}async parseTransactionDetails(e){throw new Error("Not implemented")}async getWrappedNative(){return r.toNative(this.chain,i.CosmwasmPlatform.getNativeDenom(this.network,this.chain))}createUnsignedTx(e,t,s=!1){return new o.CosmwasmUnsignedTransaction(e,this.network,this.chain,t,s)}}C.registerProtocol(i._platform,"TokenBridge",l);exports.CosmwasmTokenBridge=l;
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
var m = Object.defineProperty;
|
|
2
2
|
var w = (c, e, r) => e in c ? m(c, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : c[e] = r;
|
|
3
3
|
var a = (c, e, r) => (w(c, typeof e != "symbol" ? e + "" : e, r), r);
|
|
4
|
-
import { C as p, _ as u } from "./cosmwasm-
|
|
5
|
-
import { c as g } from "./create-
|
|
6
|
-
import { au as l, at as h } from "./index-
|
|
7
|
-
import { r as f } from "./chain-
|
|
4
|
+
import { C as p, _ as u } from "./cosmwasm-BHEBPmf7.mjs";
|
|
5
|
+
import { c as g } from "./create-BIAJIVSg.mjs";
|
|
6
|
+
import { au as l, at as h } from "./index-D4oa5qLu.mjs";
|
|
7
|
+
import { r as f } from "./chain-Cc-vL0Ji.mjs";
|
|
8
8
|
class i {
|
|
9
9
|
constructor(e, r, s, t) {
|
|
10
10
|
a(this, "network");
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
var Hs = Object.defineProperty;
|
|
2
2
|
var Gs = (i, e, t) => e in i ? Hs(i, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[e] = t;
|
|
3
3
|
var M = (i, e, t) => (Gs(i, typeof e != "symbol" ? e + "" : e, t), t);
|
|
4
|
-
import { n as B, aH as se, aI as P, aJ as R, aK as he, aL as q, aM as re, aN as ze, aO as ge, aP as Gt, aQ as J, a2 as ne, aF as bt, aG as Sn, aR as je, aS as js, aT as Ys, aU as Js, aV as Xs, aW as Vn, c7 as wn, aX as Zs, aY as Qs, aZ as er, cf as In, cg as tr, d as F, ab as nr, o as An, $ as sr, ch as _n, a_ as rr, ce as ir, bp as Ye, ci as or, c6 as ar } from "./index-
|
|
4
|
+
import { n as B, aH as se, aI as P, aJ as R, aK as he, aL as q, aM as re, aN as ze, aO as ge, aP as Gt, aQ as J, a2 as ne, aF as bt, aG as Sn, aR as je, aS as js, aT as Ys, aU as Js, aV as Xs, aW as Vn, c7 as wn, aX as Zs, aY as Qs, aZ as er, cf as In, cg as tr, d as F, ab as nr, o as An, $ as sr, ch as _n, a_ as rr, ce as ir, bp as Ye, ci as or, c6 as ar } from "./index-D4oa5qLu.mjs";
|
|
5
5
|
import { c as cr } from "./index-DpFNxVts.mjs";
|
|
6
|
-
import { P as He, a as yt, S as ur, b as dr, _ as lr } from "./solana-
|
|
7
|
-
import { c as hr } from "./create-
|
|
8
|
-
import { r as fr } from "./chain-
|
|
6
|
+
import { P as He, a as yt, S as ur, b as dr, _ as lr } from "./solana-BMm013WW.mjs";
|
|
7
|
+
import { c as hr } from "./create-BIAJIVSg.mjs";
|
|
8
|
+
import { r as fr } from "./chain-Cc-vL0Ji.mjs";
|
|
9
9
|
function Te(i, e) {
|
|
10
10
|
return He.findProgramAddressSync(i, new He(e))[0];
|
|
11
11
|
}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
var d = Object.defineProperty;
|
|
2
2
|
var h = (i, e, r) => e in i ? d(i, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : i[e] = r;
|
|
3
3
|
var n = (i, e, r) => (h(i, typeof e != "symbol" ? e + "" : e, r), r);
|
|
4
|
-
import { S as m, o as p, _ as w } from "./sui-
|
|
5
|
-
import { bp as g } from "./index-
|
|
6
|
-
import { c as l } from "./create-
|
|
7
|
-
import { r as u } from "./chain-
|
|
4
|
+
import { S as m, o as p, _ as w } from "./sui-Btvc4SGv.mjs";
|
|
5
|
+
import { bp as g } from "./index-D4oa5qLu.mjs";
|
|
6
|
+
import { c as l } from "./create-BIAJIVSg.mjs";
|
|
7
|
+
import { r as u } from "./chain-Cc-vL0Ji.mjs";
|
|
8
8
|
class c {
|
|
9
9
|
constructor(e, r, t, o) {
|
|
10
10
|
n(this, "network");
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("./index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("./index-isN8Fo1n.js"),Mr=require("./dijkstra-CtFxn7S9.js"),Sr=require("./index-C1oy9Lkm.js");var Or=function(t){for(var o=[],n=t.length,r=0;r<n;r++){var i=t.charCodeAt(r);if(i>=55296&&i<=56319&&n>r+1){var a=t.charCodeAt(r+1);a>=56320&&a<=57343&&(i=(i-55296)*1024+a-56320+65536,r+=1)}if(i<128){o.push(i);continue}if(i<2048){o.push(i>>6|192),o.push(i&63|128);continue}if(i<55296||i>=57344&&i<65536){o.push(i>>12|224),o.push(i>>6&63|128),o.push(i&63|128);continue}if(i>=65536&&i<=1114111){o.push(i>>18|240),o.push(i>>12&63|128),o.push(i>>6&63|128),o.push(i&63|128);continue}o.push(239,191,189)}return new Uint8Array(o).buffer};/**
|
|
2
2
|
* @license
|
|
3
3
|
* Copyright 2019 Google LLC
|
|
4
4
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var Xn=Object.defineProperty;var Qn=(t,e,n)=>e in t?Xn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var T=(t,e,n)=>(Qn(t,typeof e!="symbol"?e+"":e,n),n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=require("./index-CO9tmWap.js"),s=require("./index-Tl7zYqHL.js"),er=require("./index-DnneI5--.js"),P=require("./solana-Bd9eRY8E.js"),tn=require("./chain-BT07YJHt.js");class tr extends TypeError{constructor(e,n){let r;const{message:i,...a}=e,{path:o}=e,c=o.length===0?i:"At path: "+o.join(".")+" -- "+i;super(c),Object.assign(this,a),this.name=this.constructor.name,this.failures=()=>{var d;return(d=r)!=null?d:r=[e,...n()]}}}function nr(t){return se(t)&&typeof t[Symbol.iterator]=="function"}function se(t){return typeof t=="object"&&t!=null}function $(t){return typeof t=="string"?JSON.stringify(t):""+t}function rr(t){const{done:e,value:n}=t.next();return e?void 0:n}function sr(t,e,n,r){if(t===!0)return;t===!1?t={}:typeof t=="string"&&(t={message:t});const{path:i,branch:a}=e,{type:o}=n,{refinement:c,message:d="Expected a value of type `"+o+"`"+(c?" with refinement `"+c+"`":"")+", but received: `"+$(r)+"`"}=t;return{value:r,type:o,refinement:c,key:i[i.length-1],path:i,branch:a,...t,message:d}}function*Ut(t,e,n,r){nr(t)||(t=[t]);for(const i of t){const a=sr(i,e,n,r);a&&(yield a)}}function*yt(t,e,n={}){const{path:r=[],branch:i=[t],coerce:a=!1,mask:o=!1}=n,c={path:r,branch:i};if(a&&(t=e.coercer(t,c),o&&e.type!=="type"&&se(e.schema)&&se(t)&&!Array.isArray(t)))for(const f in t)e.schema[f]===void 0&&delete t[f];let d=!0;for(const f of e.validator(t,c))d=!1,yield[f,void 0];for(let[f,y,S]of e.entries(t,c)){const b=yt(y,S,{path:f===void 0?r:[...r,f],branch:f===void 0?i:[...i,y],coerce:a,mask:o});for(const M of b)M[0]?(d=!1,yield[M[0],void 0]):a&&(y=M[1],f===void 0?t=y:t instanceof Map?t.set(f,y):t instanceof Set?t.add(y):se(t)&&(t[f]=y))}if(d)for(const f of e.refiner(t,c))d=!1,yield[f,void 0];d&&(yield[void 0,t])}let ee=class{constructor(e){const{type:n,schema:r,validator:i,refiner:a,coercer:o=d=>d,entries:c=function*(){}}=e;this.type=n,this.schema=r,this.entries=c,this.coercer=o,i?this.validator=(d,f)=>{const y=i(d,f);return Ut(y,f,this,d)}:this.validator=()=>[],a?this.refiner=(d,f)=>{const y=a(d,f);return Ut(y,f,this,d)}:this.refiner=()=>[]}assert(e){return ir(e,this)}create(e){return Ee(e,this)}is(e){return nn(e,this)}mask(e){return ar(e,this)}validate(e,n={}){return _e(e,this,n)}};function ir(t,e){const n=_e(t,e);if(n[0])throw n[0]}function Ee(t,e){const n=_e(t,e,{coerce:!0});if(n[0])throw n[0];return n[1]}function ar(t,e){const n=_e(t,e,{coerce:!0,mask:!0});if(n[0])throw n[0];return n[1]}function nn(t,e){return!_e(t,e)[0]}function _e(t,e,n={}){const r=yt(t,e,n),i=rr(r);return i[0]?[new tr(i[0],function*(){for(const o of r)o[0]&&(yield o[0])}),void 0]:[void 0,i[1]]}function oe(t,e){return new ee({type:t,schema:null,validator:e})}function or(){return oe("any",()=>!0)}function p(t){return new ee({type:"array",schema:t,*entries(e){if(t&&Array.isArray(e))for(const[n,r]of e.entries())yield[n,r,t]},coercer(e){return Array.isArray(e)?e.slice():e},validator(e){return Array.isArray(e)||"Expected an array value, but received: "+$(e)}})}function Q(){return oe("boolean",t=>typeof t=="boolean")}function wt(t){return oe("instance",e=>e instanceof t||"Expected a `"+t.name+"` instance, but received: "+$(e))}function E(t){const e=$(t),n=typeof t;return new ee({type:"literal",schema:n==="string"||n==="number"||n==="boolean"?t:null,validator(r){return r===t||"Expected the literal `"+e+"`, but received: "+$(r)}})}function cr(){return oe("never",()=>!1)}function m(t){return new ee({...t,validator:(e,n)=>e===null||t.validator(e,n),refiner:(e,n)=>e===null||t.refiner(e,n)})}function u(){return oe("number",t=>typeof t=="number"&&!isNaN(t)||"Expected a number, but received: "+$(t))}function A(t){return new ee({...t,validator:(e,n)=>e===void 0||t.validator(e,n),refiner:(e,n)=>e===void 0||t.refiner(e,n)})}function rn(t,e){return new ee({type:"record",schema:null,*entries(n){if(se(n))for(const r in n){const i=n[r];yield[r,r,t],yield[r,i,e]}},validator(n){return se(n)||"Expected an object, but received: "+$(n)}})}function g(){return oe("string",t=>typeof t=="string"||"Expected a string, but received: "+$(t))}function St(t){const e=cr();return new ee({type:"tuple",schema:null,*entries(n){if(Array.isArray(n)){const r=Math.max(t.length,n.length);for(let i=0;i<r;i++)yield[i,n[i],t[i]||e]}},validator(n){return Array.isArray(n)||"Expected an array, but received: "+$(n)}})}function h(t){const e=Object.keys(t);return new ee({type:"type",schema:t,*entries(n){if(se(n))for(const r of e)yield[r,n[r],t[r]]},validator(n){return se(n)||"Expected an object, but received: "+$(n)}})}function F(t){const e=t.map(n=>n.type).join(" | ");return new ee({type:"union",schema:null,validator(n,r){const i=[];for(const a of t){const[...o]=yt(n,a,r),[c]=o;if(c[0])for(const[d]of o)d&&i.push(d);else return[]}return["Expected the value to satisfy a union of `"+e+"`, but received: "+$(n),...i]}})}function Ne(){return oe("unknown",()=>!0)}function Ke(t,e,n){return new ee({...t,coercer:(r,i)=>nn(r,e)?t.coercer(n(r,i),i):t.coercer(r,i)})}const zt=()=>{const t=s.ed25519.utils.randomPrivateKey(),e=ut(t),n=new Uint8Array(64);return n.set(t),n.set(e,32),{publicKey:e,secretKey:n}},ut=s.ed25519.getPublicKey;function Ot(t){try{return s.ed25519.ExtendedPoint.fromHex(t),!0}catch{return!1}}const ur=(t,e)=>s.ed25519.sign(t,e.slice(0,32)),dr=s.ed25519.verify,O=t=>s.bufferPolyfill.Buffer.isBuffer(t)?t:t instanceof Uint8Array?s.bufferPolyfill.Buffer.from(t.buffer,t.byteOffset,t.byteLength):s.bufferPolyfill.Buffer.from(t);class lr{constructor(e){Object.assign(this,e)}encode(){return s.bufferPolyfill.Buffer.from(s.serialize_1(qe,this))}static decode(e){return s.deserialize_1(qe,this,e)}static decodeUnchecked(e){return s.deserializeUnchecked_1(qe,this,e)}}const qe=new Map;var sn;let an;const fr=32,Be=32;function hr(t){return t._bn!==void 0}let Ft=1;an=Symbol.toStringTag;class l extends lr{constructor(e){if(super({}),this._bn=void 0,hr(e))this._bn=e._bn;else{if(typeof e=="string"){const n=s.bs58.decode(e);if(n.length!=Be)throw new Error("Invalid public key input");this._bn=new s.BN(n)}else this._bn=new s.BN(e);if(this._bn.byteLength()>Be)throw new Error("Invalid public key input")}}static unique(){const e=new l(Ft);return Ft+=1,new l(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return s.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(s.bufferPolyfill.Buffer);if(e.length===Be)return e;const n=s.bufferPolyfill.Buffer.alloc(32);return e.copy(n,32-e.length),n}get[an](){return`PublicKey(${this.toString()})`}toString(){return this.toBase58()}static async createWithSeed(e,n,r){const i=s.bufferPolyfill.Buffer.concat([e.toBuffer(),s.bufferPolyfill.Buffer.from(n),r.toBuffer()]),a=s.sha256(i);return new l(a)}static createProgramAddressSync(e,n){let r=s.bufferPolyfill.Buffer.alloc(0);e.forEach(function(a){if(a.length>fr)throw new TypeError("Max seed length exceeded");r=s.bufferPolyfill.Buffer.concat([r,O(a)])}),r=s.bufferPolyfill.Buffer.concat([r,n.toBuffer(),s.bufferPolyfill.Buffer.from("ProgramDerivedAddress")]);const i=s.sha256(r);if(Ot(i))throw new Error("Invalid seeds, address must fall off the curve");return new l(i)}static async createProgramAddress(e,n){return this.createProgramAddressSync(e,n)}static findProgramAddressSync(e,n){let r=255,i;for(;r!=0;){try{const a=e.concat(s.bufferPolyfill.Buffer.from([r]));i=this.createProgramAddressSync(a,n)}catch(a){if(a instanceof TypeError)throw a;r--;continue}return[i,r]}throw new Error("Unable to find a viable program address nonce")}static async findProgramAddress(e,n){return this.findProgramAddressSync(e,n)}static isOnCurve(e){const n=new l(e);return Ot(n.toBytes())}}sn=l;l.default=new sn("11111111111111111111111111111111");qe.set(l,{kind:"struct",fields:[["_bn","u256"]]});new l("BPFLoader1111111111111111111111111111111111");const dt=1232,gr=127,on=64;class Lt{constructor(e,n){this.staticAccountKeys=void 0,this.accountKeysFromLookups=void 0,this.staticAccountKeys=e,this.accountKeysFromLookups=n}keySegments(){const e=[this.staticAccountKeys];return this.accountKeysFromLookups&&(e.push(this.accountKeysFromLookups.writable),e.push(this.accountKeysFromLookups.readonly)),e}get(e){for(const n of this.keySegments()){if(e<n.length)return n[e];e-=n.length}}get length(){return this.keySegments().flat().length}compileInstructions(e){if(this.length>256)throw new Error("Account index overflow encountered during compilation");const r=new Map;this.keySegments().flat().forEach((a,o)=>{r.set(a.toBase58(),o)});const i=a=>{const o=r.get(a.toBase58());if(o===void 0)throw new Error("Encountered an unknown instruction account key during compilation");return o};return e.map(a=>({programIdIndex:i(a.programId),accountKeyIndexes:a.keys.map(o=>i(o.pubkey)),data:a.data}))}}const B=(t="publicKey")=>s.blob(32,t),me=(t="string")=>{const e=s.struct([s.u32("length"),s.u32("lengthPadding"),s.blob(s.offset(s.u32(),-8),"chars")],t),n=e.decode.bind(e),r=e.encode.bind(e),i=e;return i.decode=(a,o)=>n(a,o).chars.toString(),i.encode=(a,o,c)=>{const d={chars:s.bufferPolyfill.Buffer.from(a,"utf8")};return r(d,o,c)},i.alloc=a=>s.u32().span+s.u32().span+s.bufferPolyfill.Buffer.from(a,"utf8").length,i},mr=(t="authorized")=>s.struct([B("staker"),B("withdrawer")],t),pr=(t="lockup")=>s.struct([s.ns64("unixTimestamp"),s.ns64("epoch"),B("custodian")],t),yr=(t="voteInit")=>s.struct([B("nodePubkey"),B("authorizedVoter"),B("authorizedWithdrawer"),s.u8("commission")],t),wr=(t="voteAuthorizeWithSeedArgs")=>s.struct([s.u32("voteAuthorizationType"),B("currentAuthorityDerivedKeyOwnerPubkey"),me("currentAuthorityDerivedKeySeed"),B("newAuthorized")],t);function cn(t,e){const n=i=>{if(i.span>=0)return i.span;if(typeof i.alloc=="function")return i.alloc(e[i.property]);if("count"in i&&"elementLayout"in i){const a=e[i.property];if(Array.isArray(a))return a.length*n(i.elementLayout)}else if("fields"in i)return cn({layout:i},e[i.property]);return 0};let r=0;return t.layout.fields.forEach(i=>{r+=n(i)}),r}function Te(t){let e=0,n=0;for(;;){let r=t.shift();if(e|=(r&127)<<n*7,n+=1,!(r&128))break}return e}function Ce(t,e){let n=e;for(;;){let r=n&127;if(n>>=7,n==0){t.push(r);break}else r|=128,t.push(r)}}function L(t,e){if(!t)throw new Error(e||"Assertion failed")}class bt{constructor(e,n){this.payer=void 0,this.keyMetaMap=void 0,this.payer=e,this.keyMetaMap=n}static compile(e,n){const r=new Map,i=o=>{const c=o.toBase58();let d=r.get(c);return d===void 0&&(d={isSigner:!1,isWritable:!1,isInvoked:!1},r.set(c,d)),d},a=i(n);a.isSigner=!0,a.isWritable=!0;for(const o of e){i(o.programId).isInvoked=!0;for(const c of o.keys){const d=i(c.pubkey);d.isSigner||(d.isSigner=c.isSigner),d.isWritable||(d.isWritable=c.isWritable)}}return new bt(n,r)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];L(e.length<=256,"Max static account keys length exceeded");const n=e.filter(([,d])=>d.isSigner&&d.isWritable),r=e.filter(([,d])=>d.isSigner&&!d.isWritable),i=e.filter(([,d])=>!d.isSigner&&d.isWritable),a=e.filter(([,d])=>!d.isSigner&&!d.isWritable),o={numRequiredSignatures:n.length+r.length,numReadonlySignedAccounts:r.length,numReadonlyUnsignedAccounts:a.length};{L(n.length>0,"Expected at least one writable signer key");const[d]=n[0];L(d===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}const c=[...n.map(([d])=>new l(d)),...r.map(([d])=>new l(d)),...i.map(([d])=>new l(d)),...a.map(([d])=>new l(d))];return[o,c]}extractTableLookup(e){const[n,r]=this.drainKeysFoundInLookupTable(e.state.addresses,o=>!o.isSigner&&!o.isInvoked&&o.isWritable),[i,a]=this.drainKeysFoundInLookupTable(e.state.addresses,o=>!o.isSigner&&!o.isInvoked&&!o.isWritable);if(!(n.length===0&&i.length===0))return[{accountKey:e.key,writableIndexes:n,readonlyIndexes:i},{writable:r,readonly:a}]}drainKeysFoundInLookupTable(e,n){const r=new Array,i=new Array;for(const[a,o]of this.keyMetaMap.entries())if(n(o)){const c=new l(a),d=e.findIndex(f=>f.equals(c));d>=0&&(L(d<256,"Max lookup table index exceeded"),r.push(d),i.push(c),this.keyMetaMap.delete(a))}return[r,i]}}const un="Reached end of buffer unexpectedly";function Le(t){if(t.length===0)throw new Error(un);return t.shift()}function ve(t,...e){const[n]=e;if(e.length===2?n+(e[1]??0)>t.length:n>=t.length)throw new Error(un);return t.splice(...e)}class We{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(n=>new l(n)),this.recentBlockhash=e.recentBlockhash,this.instructions=e.instructions,this.instructions.forEach(n=>this.indexToProgramIds.set(n.programIdIndex,this.accountKeys[n.programIdIndex]))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:s.bs58.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new Lt(this.staticAccountKeys)}static compile(e){const n=bt.compile(e.instructions,e.payerKey),[r,i]=n.getMessageComponents(),o=new Lt(i).compileInstructions(e.instructions).map(c=>({programIdIndex:c.programIdIndex,accounts:c.accountKeyIndexes,data:s.bs58.encode(c.data)}));return new We({header:r,accountKeys:i,recentBlockhash:e.recentBlockhash,instructions:o})}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const n=this.header.numRequiredSignatures;if(e>=this.header.numRequiredSignatures){const r=e-n,a=this.accountKeys.length-n-this.header.numReadonlyUnsignedAccounts;return r<a}else{const r=n-this.header.numReadonlySignedAccounts;return e<r}}isProgramId(e){return this.indexToProgramIds.has(e)}programIds(){return[...this.indexToProgramIds.values()]}nonProgramIds(){return this.accountKeys.filter((e,n)=>!this.isProgramId(n))}serialize(){const e=this.accountKeys.length;let n=[];Ce(n,e);const r=this.instructions.map(S=>{const{accounts:b,programIdIndex:M}=S,C=Array.from(s.bs58.decode(S.data));let w=[];Ce(w,b.length);let v=[];return Ce(v,C.length),{programIdIndex:M,keyIndicesCount:s.bufferPolyfill.Buffer.from(w),keyIndices:b,dataLength:s.bufferPolyfill.Buffer.from(v),data:C}});let i=[];Ce(i,r.length);let a=s.bufferPolyfill.Buffer.alloc(dt);s.bufferPolyfill.Buffer.from(i).copy(a);let o=i.length;r.forEach(S=>{const M=s.struct([s.u8("programIdIndex"),s.blob(S.keyIndicesCount.length,"keyIndicesCount"),s.seq(s.u8("keyIndex"),S.keyIndices.length,"keyIndices"),s.blob(S.dataLength.length,"dataLength"),s.seq(s.u8("userdatum"),S.data.length,"data")]).encode(S,a,o);o+=M}),a=a.slice(0,o);const c=s.struct([s.blob(1,"numRequiredSignatures"),s.blob(1,"numReadonlySignedAccounts"),s.blob(1,"numReadonlyUnsignedAccounts"),s.blob(n.length,"keyCount"),s.seq(B("key"),e,"keys"),B("recentBlockhash")]),d={numRequiredSignatures:s.bufferPolyfill.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:s.bufferPolyfill.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:s.bufferPolyfill.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:s.bufferPolyfill.Buffer.from(n),keys:this.accountKeys.map(S=>O(S.toBytes())),recentBlockhash:s.bs58.decode(this.recentBlockhash)};let f=s.bufferPolyfill.Buffer.alloc(2048);const y=c.encode(d,f);return a.copy(f,y),f.slice(0,y+a.length)}static from(e){let n=[...e];const r=Le(n);if(r!==(r&gr))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const i=Le(n),a=Le(n),o=Te(n);let c=[];for(let b=0;b<o;b++){const M=ve(n,0,Be);c.push(new l(s.bufferPolyfill.Buffer.from(M)))}const d=ve(n,0,Be),f=Te(n);let y=[];for(let b=0;b<f;b++){const M=Le(n),C=Te(n),w=ve(n,0,C),v=Te(n),I=ve(n,0,v),N=s.bs58.encode(s.bufferPolyfill.Buffer.from(I));y.push({programIdIndex:M,accounts:w,data:N})}const S={header:{numRequiredSignatures:r,numReadonlySignedAccounts:i,numReadonlyUnsignedAccounts:a},recentBlockhash:s.bs58.encode(s.bufferPolyfill.Buffer.from(d)),accountKeys:c,instructions:y};return new We(S)}}const Sr=s.bufferPolyfill.Buffer.alloc(on).fill(0);class U{constructor(e){this.keys=void 0,this.programId=void 0,this.data=s.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:n,isWritable:r})=>({pubkey:e.toJSON(),isSigner:n,isWritable:r})),programId:this.programId.toJSON(),data:[...this.data]}}}class q{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:n,nonceInfo:r}=e;this.minNonceContextSlot=n,this.nonceInfo=r}else if(Object.prototype.hasOwnProperty.call(e,"lastValidBlockHeight")){const{blockhash:n,lastValidBlockHeight:r}=e;this.recentBlockhash=n,this.lastValidBlockHeight=r}else{const{recentBlockhash:n,nonceInfo:r}=e;r&&(this.nonceInfo=r),this.recentBlockhash=n}}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(n=>{"instructions"in n?this.instructions=this.instructions.concat(n.instructions):"data"in n&&"programId"in n&&"keys"in n?this.instructions.push(n):this.instructions.push(new U(n))}),this}compileMessage(){if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json))return this._message;let e,n;if(this.nonceInfo?(e=this.nonceInfo.nonce,this.instructions[0]!=this.nonceInfo.nonceInstruction?n=[this.nonceInfo.nonceInstruction,...this.instructions]:n=this.instructions):(e=this.recentBlockhash,n=this.instructions),!e)throw new Error("Transaction recentBlockhash required");n.length<1&&console.warn("No instructions provided");let r;if(this.feePayer)r=this.feePayer;else if(this.signatures.length>0&&this.signatures[0].publicKey)r=this.signatures[0].publicKey;else throw new Error("Transaction fee payer required");for(let w=0;w<n.length;w++)if(n[w].programId===void 0)throw new Error(`Transaction instruction index ${w} has undefined program id`);const i=[],a=[];n.forEach(w=>{w.keys.forEach(I=>{a.push({...I})});const v=w.programId.toString();i.includes(v)||i.push(v)}),i.forEach(w=>{a.push({pubkey:new l(w),isSigner:!1,isWritable:!1})});const o=[];a.forEach(w=>{const v=w.pubkey.toString(),I=o.findIndex(N=>N.pubkey.toString()===v);I>-1?(o[I].isWritable=o[I].isWritable||w.isWritable,o[I].isSigner=o[I].isSigner||w.isSigner):o.push(w)}),o.sort(function(w,v){if(w.isSigner!==v.isSigner)return w.isSigner?-1:1;if(w.isWritable!==v.isWritable)return w.isWritable?-1:1;const I={localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"};return w.pubkey.toBase58().localeCompare(v.pubkey.toBase58(),"en",I)});const c=o.findIndex(w=>w.pubkey.equals(r));if(c>-1){const[w]=o.splice(c,1);w.isSigner=!0,w.isWritable=!0,o.unshift(w)}else o.unshift({pubkey:r,isSigner:!0,isWritable:!0});for(const w of this.signatures){const v=o.findIndex(I=>I.pubkey.equals(w.publicKey));if(v>-1)o[v].isSigner||(o[v].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: ${w.publicKey.toString()}`)}let d=0,f=0,y=0;const S=[],b=[];o.forEach(({pubkey:w,isSigner:v,isWritable:I})=>{v?(S.push(w.toString()),d+=1,I||(f+=1)):(b.push(w.toString()),I||(y+=1))});const M=S.concat(b),C=n.map(w=>{const{data:v,programId:I}=w;return{programIdIndex:M.indexOf(I.toString()),accounts:w.keys.map(N=>M.indexOf(N.pubkey.toString())),data:s.bs58.encode(v)}});return C.forEach(w=>{L(w.programIdIndex>=0),w.accounts.forEach(v=>L(v>=0))}),new We({header:{numRequiredSignatures:d,numReadonlySignedAccounts:f,numReadonlyUnsignedAccounts:y},accountKeys:M,recentBlockhash:e,instructions:C})}_compile(){const e=this.compileMessage(),n=e.accountKeys.slice(0,e.header.numRequiredSignatures);return this.signatures.length===n.length&&this.signatures.every((i,a)=>n[a].equals(i.publicKey))||(this.signatures=n.map(r=>({signature:null,publicKey:r}))),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 n=new Set;this.signatures=e.filter(r=>{const i=r.toString();return n.has(i)?!1:(n.add(i),!0)}).map(r=>({signature:null,publicKey:r}))}sign(...e){if(e.length===0)throw new Error("No signers");const n=new Set,r=[];for(const a of e){const o=a.publicKey.toString();n.has(o)||(n.add(o),r.push(a))}this.signatures=r.map(a=>({signature:null,publicKey:a.publicKey}));const i=this._compile();this._partialSign(i,...r)}partialSign(...e){if(e.length===0)throw new Error("No signers");const n=new Set,r=[];for(const a of e){const o=a.publicKey.toString();n.has(o)||(n.add(o),r.push(a))}const i=this._compile();this._partialSign(i,...r)}_partialSign(e,...n){const r=e.serialize();n.forEach(i=>{const a=ur(r,i.secretKey);this._addSignature(i.publicKey,O(a))})}addSignature(e,n){this._compile(),this._addSignature(e,n)}_addSignature(e,n){L(n.length===64);const r=this.signatures.findIndex(i=>e.equals(i.publicKey));if(r<0)throw new Error(`unknown signer: ${e.toString()}`);this.signatures[r].signature=s.bufferPolyfill.Buffer.from(n)}verifySignatures(e=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),e)}_getMessageSignednessErrors(e,n){const r={};for(const{signature:i,publicKey:a}of this.signatures)i===null?n&&(r.missing||(r.missing=[])).push(a):dr(i,e,a.toBytes())||(r.invalid||(r.invalid=[])).push(a);return r.invalid||r.missing?r:void 0}serialize(e){const{requireAllSignatures:n,verifySignatures:r}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},e),i=this.serializeMessage();if(r){const a=this._getMessageSignednessErrors(i,n);if(a){let o="Signature verification failed.";throw a.invalid&&(o+=`
|
|
1
|
+
"use strict";var Xn=Object.defineProperty;var Qn=(t,e,n)=>e in t?Xn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var T=(t,e,n)=>(Qn(t,typeof e!="symbol"?e+"":e,n),n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=require("./index-WhcobQtR.js"),s=require("./index-C1oy9Lkm.js"),er=require("./index-DnneI5--.js"),P=require("./solana--YauUjmQ.js"),tn=require("./chain-BteoJHpg.js");class tr extends TypeError{constructor(e,n){let r;const{message:i,...a}=e,{path:o}=e,c=o.length===0?i:"At path: "+o.join(".")+" -- "+i;super(c),Object.assign(this,a),this.name=this.constructor.name,this.failures=()=>{var d;return(d=r)!=null?d:r=[e,...n()]}}}function nr(t){return se(t)&&typeof t[Symbol.iterator]=="function"}function se(t){return typeof t=="object"&&t!=null}function $(t){return typeof t=="string"?JSON.stringify(t):""+t}function rr(t){const{done:e,value:n}=t.next();return e?void 0:n}function sr(t,e,n,r){if(t===!0)return;t===!1?t={}:typeof t=="string"&&(t={message:t});const{path:i,branch:a}=e,{type:o}=n,{refinement:c,message:d="Expected a value of type `"+o+"`"+(c?" with refinement `"+c+"`":"")+", but received: `"+$(r)+"`"}=t;return{value:r,type:o,refinement:c,key:i[i.length-1],path:i,branch:a,...t,message:d}}function*Ut(t,e,n,r){nr(t)||(t=[t]);for(const i of t){const a=sr(i,e,n,r);a&&(yield a)}}function*yt(t,e,n={}){const{path:r=[],branch:i=[t],coerce:a=!1,mask:o=!1}=n,c={path:r,branch:i};if(a&&(t=e.coercer(t,c),o&&e.type!=="type"&&se(e.schema)&&se(t)&&!Array.isArray(t)))for(const f in t)e.schema[f]===void 0&&delete t[f];let d=!0;for(const f of e.validator(t,c))d=!1,yield[f,void 0];for(let[f,y,S]of e.entries(t,c)){const b=yt(y,S,{path:f===void 0?r:[...r,f],branch:f===void 0?i:[...i,y],coerce:a,mask:o});for(const M of b)M[0]?(d=!1,yield[M[0],void 0]):a&&(y=M[1],f===void 0?t=y:t instanceof Map?t.set(f,y):t instanceof Set?t.add(y):se(t)&&(t[f]=y))}if(d)for(const f of e.refiner(t,c))d=!1,yield[f,void 0];d&&(yield[void 0,t])}let ee=class{constructor(e){const{type:n,schema:r,validator:i,refiner:a,coercer:o=d=>d,entries:c=function*(){}}=e;this.type=n,this.schema=r,this.entries=c,this.coercer=o,i?this.validator=(d,f)=>{const y=i(d,f);return Ut(y,f,this,d)}:this.validator=()=>[],a?this.refiner=(d,f)=>{const y=a(d,f);return Ut(y,f,this,d)}:this.refiner=()=>[]}assert(e){return ir(e,this)}create(e){return Ee(e,this)}is(e){return nn(e,this)}mask(e){return ar(e,this)}validate(e,n={}){return _e(e,this,n)}};function ir(t,e){const n=_e(t,e);if(n[0])throw n[0]}function Ee(t,e){const n=_e(t,e,{coerce:!0});if(n[0])throw n[0];return n[1]}function ar(t,e){const n=_e(t,e,{coerce:!0,mask:!0});if(n[0])throw n[0];return n[1]}function nn(t,e){return!_e(t,e)[0]}function _e(t,e,n={}){const r=yt(t,e,n),i=rr(r);return i[0]?[new tr(i[0],function*(){for(const o of r)o[0]&&(yield o[0])}),void 0]:[void 0,i[1]]}function oe(t,e){return new ee({type:t,schema:null,validator:e})}function or(){return oe("any",()=>!0)}function p(t){return new ee({type:"array",schema:t,*entries(e){if(t&&Array.isArray(e))for(const[n,r]of e.entries())yield[n,r,t]},coercer(e){return Array.isArray(e)?e.slice():e},validator(e){return Array.isArray(e)||"Expected an array value, but received: "+$(e)}})}function Q(){return oe("boolean",t=>typeof t=="boolean")}function wt(t){return oe("instance",e=>e instanceof t||"Expected a `"+t.name+"` instance, but received: "+$(e))}function E(t){const e=$(t),n=typeof t;return new ee({type:"literal",schema:n==="string"||n==="number"||n==="boolean"?t:null,validator(r){return r===t||"Expected the literal `"+e+"`, but received: "+$(r)}})}function cr(){return oe("never",()=>!1)}function m(t){return new ee({...t,validator:(e,n)=>e===null||t.validator(e,n),refiner:(e,n)=>e===null||t.refiner(e,n)})}function u(){return oe("number",t=>typeof t=="number"&&!isNaN(t)||"Expected a number, but received: "+$(t))}function A(t){return new ee({...t,validator:(e,n)=>e===void 0||t.validator(e,n),refiner:(e,n)=>e===void 0||t.refiner(e,n)})}function rn(t,e){return new ee({type:"record",schema:null,*entries(n){if(se(n))for(const r in n){const i=n[r];yield[r,r,t],yield[r,i,e]}},validator(n){return se(n)||"Expected an object, but received: "+$(n)}})}function g(){return oe("string",t=>typeof t=="string"||"Expected a string, but received: "+$(t))}function St(t){const e=cr();return new ee({type:"tuple",schema:null,*entries(n){if(Array.isArray(n)){const r=Math.max(t.length,n.length);for(let i=0;i<r;i++)yield[i,n[i],t[i]||e]}},validator(n){return Array.isArray(n)||"Expected an array, but received: "+$(n)}})}function h(t){const e=Object.keys(t);return new ee({type:"type",schema:t,*entries(n){if(se(n))for(const r of e)yield[r,n[r],t[r]]},validator(n){return se(n)||"Expected an object, but received: "+$(n)}})}function F(t){const e=t.map(n=>n.type).join(" | ");return new ee({type:"union",schema:null,validator(n,r){const i=[];for(const a of t){const[...o]=yt(n,a,r),[c]=o;if(c[0])for(const[d]of o)d&&i.push(d);else return[]}return["Expected the value to satisfy a union of `"+e+"`, but received: "+$(n),...i]}})}function Ne(){return oe("unknown",()=>!0)}function Ke(t,e,n){return new ee({...t,coercer:(r,i)=>nn(r,e)?t.coercer(n(r,i),i):t.coercer(r,i)})}const zt=()=>{const t=s.ed25519.utils.randomPrivateKey(),e=ut(t),n=new Uint8Array(64);return n.set(t),n.set(e,32),{publicKey:e,secretKey:n}},ut=s.ed25519.getPublicKey;function Ot(t){try{return s.ed25519.ExtendedPoint.fromHex(t),!0}catch{return!1}}const ur=(t,e)=>s.ed25519.sign(t,e.slice(0,32)),dr=s.ed25519.verify,O=t=>s.bufferPolyfill.Buffer.isBuffer(t)?t:t instanceof Uint8Array?s.bufferPolyfill.Buffer.from(t.buffer,t.byteOffset,t.byteLength):s.bufferPolyfill.Buffer.from(t);class lr{constructor(e){Object.assign(this,e)}encode(){return s.bufferPolyfill.Buffer.from(s.serialize_1(qe,this))}static decode(e){return s.deserialize_1(qe,this,e)}static decodeUnchecked(e){return s.deserializeUnchecked_1(qe,this,e)}}const qe=new Map;var sn;let an;const fr=32,Be=32;function hr(t){return t._bn!==void 0}let Ft=1;an=Symbol.toStringTag;class l extends lr{constructor(e){if(super({}),this._bn=void 0,hr(e))this._bn=e._bn;else{if(typeof e=="string"){const n=s.bs58.decode(e);if(n.length!=Be)throw new Error("Invalid public key input");this._bn=new s.BN(n)}else this._bn=new s.BN(e);if(this._bn.byteLength()>Be)throw new Error("Invalid public key input")}}static unique(){const e=new l(Ft);return Ft+=1,new l(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return s.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(s.bufferPolyfill.Buffer);if(e.length===Be)return e;const n=s.bufferPolyfill.Buffer.alloc(32);return e.copy(n,32-e.length),n}get[an](){return`PublicKey(${this.toString()})`}toString(){return this.toBase58()}static async createWithSeed(e,n,r){const i=s.bufferPolyfill.Buffer.concat([e.toBuffer(),s.bufferPolyfill.Buffer.from(n),r.toBuffer()]),a=s.sha256(i);return new l(a)}static createProgramAddressSync(e,n){let r=s.bufferPolyfill.Buffer.alloc(0);e.forEach(function(a){if(a.length>fr)throw new TypeError("Max seed length exceeded");r=s.bufferPolyfill.Buffer.concat([r,O(a)])}),r=s.bufferPolyfill.Buffer.concat([r,n.toBuffer(),s.bufferPolyfill.Buffer.from("ProgramDerivedAddress")]);const i=s.sha256(r);if(Ot(i))throw new Error("Invalid seeds, address must fall off the curve");return new l(i)}static async createProgramAddress(e,n){return this.createProgramAddressSync(e,n)}static findProgramAddressSync(e,n){let r=255,i;for(;r!=0;){try{const a=e.concat(s.bufferPolyfill.Buffer.from([r]));i=this.createProgramAddressSync(a,n)}catch(a){if(a instanceof TypeError)throw a;r--;continue}return[i,r]}throw new Error("Unable to find a viable program address nonce")}static async findProgramAddress(e,n){return this.findProgramAddressSync(e,n)}static isOnCurve(e){const n=new l(e);return Ot(n.toBytes())}}sn=l;l.default=new sn("11111111111111111111111111111111");qe.set(l,{kind:"struct",fields:[["_bn","u256"]]});new l("BPFLoader1111111111111111111111111111111111");const dt=1232,gr=127,on=64;class Lt{constructor(e,n){this.staticAccountKeys=void 0,this.accountKeysFromLookups=void 0,this.staticAccountKeys=e,this.accountKeysFromLookups=n}keySegments(){const e=[this.staticAccountKeys];return this.accountKeysFromLookups&&(e.push(this.accountKeysFromLookups.writable),e.push(this.accountKeysFromLookups.readonly)),e}get(e){for(const n of this.keySegments()){if(e<n.length)return n[e];e-=n.length}}get length(){return this.keySegments().flat().length}compileInstructions(e){if(this.length>256)throw new Error("Account index overflow encountered during compilation");const r=new Map;this.keySegments().flat().forEach((a,o)=>{r.set(a.toBase58(),o)});const i=a=>{const o=r.get(a.toBase58());if(o===void 0)throw new Error("Encountered an unknown instruction account key during compilation");return o};return e.map(a=>({programIdIndex:i(a.programId),accountKeyIndexes:a.keys.map(o=>i(o.pubkey)),data:a.data}))}}const B=(t="publicKey")=>s.blob(32,t),me=(t="string")=>{const e=s.struct([s.u32("length"),s.u32("lengthPadding"),s.blob(s.offset(s.u32(),-8),"chars")],t),n=e.decode.bind(e),r=e.encode.bind(e),i=e;return i.decode=(a,o)=>n(a,o).chars.toString(),i.encode=(a,o,c)=>{const d={chars:s.bufferPolyfill.Buffer.from(a,"utf8")};return r(d,o,c)},i.alloc=a=>s.u32().span+s.u32().span+s.bufferPolyfill.Buffer.from(a,"utf8").length,i},mr=(t="authorized")=>s.struct([B("staker"),B("withdrawer")],t),pr=(t="lockup")=>s.struct([s.ns64("unixTimestamp"),s.ns64("epoch"),B("custodian")],t),yr=(t="voteInit")=>s.struct([B("nodePubkey"),B("authorizedVoter"),B("authorizedWithdrawer"),s.u8("commission")],t),wr=(t="voteAuthorizeWithSeedArgs")=>s.struct([s.u32("voteAuthorizationType"),B("currentAuthorityDerivedKeyOwnerPubkey"),me("currentAuthorityDerivedKeySeed"),B("newAuthorized")],t);function cn(t,e){const n=i=>{if(i.span>=0)return i.span;if(typeof i.alloc=="function")return i.alloc(e[i.property]);if("count"in i&&"elementLayout"in i){const a=e[i.property];if(Array.isArray(a))return a.length*n(i.elementLayout)}else if("fields"in i)return cn({layout:i},e[i.property]);return 0};let r=0;return t.layout.fields.forEach(i=>{r+=n(i)}),r}function Te(t){let e=0,n=0;for(;;){let r=t.shift();if(e|=(r&127)<<n*7,n+=1,!(r&128))break}return e}function Ce(t,e){let n=e;for(;;){let r=n&127;if(n>>=7,n==0){t.push(r);break}else r|=128,t.push(r)}}function L(t,e){if(!t)throw new Error(e||"Assertion failed")}class bt{constructor(e,n){this.payer=void 0,this.keyMetaMap=void 0,this.payer=e,this.keyMetaMap=n}static compile(e,n){const r=new Map,i=o=>{const c=o.toBase58();let d=r.get(c);return d===void 0&&(d={isSigner:!1,isWritable:!1,isInvoked:!1},r.set(c,d)),d},a=i(n);a.isSigner=!0,a.isWritable=!0;for(const o of e){i(o.programId).isInvoked=!0;for(const c of o.keys){const d=i(c.pubkey);d.isSigner||(d.isSigner=c.isSigner),d.isWritable||(d.isWritable=c.isWritable)}}return new bt(n,r)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];L(e.length<=256,"Max static account keys length exceeded");const n=e.filter(([,d])=>d.isSigner&&d.isWritable),r=e.filter(([,d])=>d.isSigner&&!d.isWritable),i=e.filter(([,d])=>!d.isSigner&&d.isWritable),a=e.filter(([,d])=>!d.isSigner&&!d.isWritable),o={numRequiredSignatures:n.length+r.length,numReadonlySignedAccounts:r.length,numReadonlyUnsignedAccounts:a.length};{L(n.length>0,"Expected at least one writable signer key");const[d]=n[0];L(d===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}const c=[...n.map(([d])=>new l(d)),...r.map(([d])=>new l(d)),...i.map(([d])=>new l(d)),...a.map(([d])=>new l(d))];return[o,c]}extractTableLookup(e){const[n,r]=this.drainKeysFoundInLookupTable(e.state.addresses,o=>!o.isSigner&&!o.isInvoked&&o.isWritable),[i,a]=this.drainKeysFoundInLookupTable(e.state.addresses,o=>!o.isSigner&&!o.isInvoked&&!o.isWritable);if(!(n.length===0&&i.length===0))return[{accountKey:e.key,writableIndexes:n,readonlyIndexes:i},{writable:r,readonly:a}]}drainKeysFoundInLookupTable(e,n){const r=new Array,i=new Array;for(const[a,o]of this.keyMetaMap.entries())if(n(o)){const c=new l(a),d=e.findIndex(f=>f.equals(c));d>=0&&(L(d<256,"Max lookup table index exceeded"),r.push(d),i.push(c),this.keyMetaMap.delete(a))}return[r,i]}}const un="Reached end of buffer unexpectedly";function Le(t){if(t.length===0)throw new Error(un);return t.shift()}function ve(t,...e){const[n]=e;if(e.length===2?n+(e[1]??0)>t.length:n>=t.length)throw new Error(un);return t.splice(...e)}class We{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(n=>new l(n)),this.recentBlockhash=e.recentBlockhash,this.instructions=e.instructions,this.instructions.forEach(n=>this.indexToProgramIds.set(n.programIdIndex,this.accountKeys[n.programIdIndex]))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:s.bs58.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new Lt(this.staticAccountKeys)}static compile(e){const n=bt.compile(e.instructions,e.payerKey),[r,i]=n.getMessageComponents(),o=new Lt(i).compileInstructions(e.instructions).map(c=>({programIdIndex:c.programIdIndex,accounts:c.accountKeyIndexes,data:s.bs58.encode(c.data)}));return new We({header:r,accountKeys:i,recentBlockhash:e.recentBlockhash,instructions:o})}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const n=this.header.numRequiredSignatures;if(e>=this.header.numRequiredSignatures){const r=e-n,a=this.accountKeys.length-n-this.header.numReadonlyUnsignedAccounts;return r<a}else{const r=n-this.header.numReadonlySignedAccounts;return e<r}}isProgramId(e){return this.indexToProgramIds.has(e)}programIds(){return[...this.indexToProgramIds.values()]}nonProgramIds(){return this.accountKeys.filter((e,n)=>!this.isProgramId(n))}serialize(){const e=this.accountKeys.length;let n=[];Ce(n,e);const r=this.instructions.map(S=>{const{accounts:b,programIdIndex:M}=S,C=Array.from(s.bs58.decode(S.data));let w=[];Ce(w,b.length);let v=[];return Ce(v,C.length),{programIdIndex:M,keyIndicesCount:s.bufferPolyfill.Buffer.from(w),keyIndices:b,dataLength:s.bufferPolyfill.Buffer.from(v),data:C}});let i=[];Ce(i,r.length);let a=s.bufferPolyfill.Buffer.alloc(dt);s.bufferPolyfill.Buffer.from(i).copy(a);let o=i.length;r.forEach(S=>{const M=s.struct([s.u8("programIdIndex"),s.blob(S.keyIndicesCount.length,"keyIndicesCount"),s.seq(s.u8("keyIndex"),S.keyIndices.length,"keyIndices"),s.blob(S.dataLength.length,"dataLength"),s.seq(s.u8("userdatum"),S.data.length,"data")]).encode(S,a,o);o+=M}),a=a.slice(0,o);const c=s.struct([s.blob(1,"numRequiredSignatures"),s.blob(1,"numReadonlySignedAccounts"),s.blob(1,"numReadonlyUnsignedAccounts"),s.blob(n.length,"keyCount"),s.seq(B("key"),e,"keys"),B("recentBlockhash")]),d={numRequiredSignatures:s.bufferPolyfill.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:s.bufferPolyfill.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:s.bufferPolyfill.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:s.bufferPolyfill.Buffer.from(n),keys:this.accountKeys.map(S=>O(S.toBytes())),recentBlockhash:s.bs58.decode(this.recentBlockhash)};let f=s.bufferPolyfill.Buffer.alloc(2048);const y=c.encode(d,f);return a.copy(f,y),f.slice(0,y+a.length)}static from(e){let n=[...e];const r=Le(n);if(r!==(r&gr))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const i=Le(n),a=Le(n),o=Te(n);let c=[];for(let b=0;b<o;b++){const M=ve(n,0,Be);c.push(new l(s.bufferPolyfill.Buffer.from(M)))}const d=ve(n,0,Be),f=Te(n);let y=[];for(let b=0;b<f;b++){const M=Le(n),C=Te(n),w=ve(n,0,C),v=Te(n),I=ve(n,0,v),N=s.bs58.encode(s.bufferPolyfill.Buffer.from(I));y.push({programIdIndex:M,accounts:w,data:N})}const S={header:{numRequiredSignatures:r,numReadonlySignedAccounts:i,numReadonlyUnsignedAccounts:a},recentBlockhash:s.bs58.encode(s.bufferPolyfill.Buffer.from(d)),accountKeys:c,instructions:y};return new We(S)}}const Sr=s.bufferPolyfill.Buffer.alloc(on).fill(0);class U{constructor(e){this.keys=void 0,this.programId=void 0,this.data=s.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:n,isWritable:r})=>({pubkey:e.toJSON(),isSigner:n,isWritable:r})),programId:this.programId.toJSON(),data:[...this.data]}}}class q{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:n,nonceInfo:r}=e;this.minNonceContextSlot=n,this.nonceInfo=r}else if(Object.prototype.hasOwnProperty.call(e,"lastValidBlockHeight")){const{blockhash:n,lastValidBlockHeight:r}=e;this.recentBlockhash=n,this.lastValidBlockHeight=r}else{const{recentBlockhash:n,nonceInfo:r}=e;r&&(this.nonceInfo=r),this.recentBlockhash=n}}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(n=>{"instructions"in n?this.instructions=this.instructions.concat(n.instructions):"data"in n&&"programId"in n&&"keys"in n?this.instructions.push(n):this.instructions.push(new U(n))}),this}compileMessage(){if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json))return this._message;let e,n;if(this.nonceInfo?(e=this.nonceInfo.nonce,this.instructions[0]!=this.nonceInfo.nonceInstruction?n=[this.nonceInfo.nonceInstruction,...this.instructions]:n=this.instructions):(e=this.recentBlockhash,n=this.instructions),!e)throw new Error("Transaction recentBlockhash required");n.length<1&&console.warn("No instructions provided");let r;if(this.feePayer)r=this.feePayer;else if(this.signatures.length>0&&this.signatures[0].publicKey)r=this.signatures[0].publicKey;else throw new Error("Transaction fee payer required");for(let w=0;w<n.length;w++)if(n[w].programId===void 0)throw new Error(`Transaction instruction index ${w} has undefined program id`);const i=[],a=[];n.forEach(w=>{w.keys.forEach(I=>{a.push({...I})});const v=w.programId.toString();i.includes(v)||i.push(v)}),i.forEach(w=>{a.push({pubkey:new l(w),isSigner:!1,isWritable:!1})});const o=[];a.forEach(w=>{const v=w.pubkey.toString(),I=o.findIndex(N=>N.pubkey.toString()===v);I>-1?(o[I].isWritable=o[I].isWritable||w.isWritable,o[I].isSigner=o[I].isSigner||w.isSigner):o.push(w)}),o.sort(function(w,v){if(w.isSigner!==v.isSigner)return w.isSigner?-1:1;if(w.isWritable!==v.isWritable)return w.isWritable?-1:1;const I={localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"};return w.pubkey.toBase58().localeCompare(v.pubkey.toBase58(),"en",I)});const c=o.findIndex(w=>w.pubkey.equals(r));if(c>-1){const[w]=o.splice(c,1);w.isSigner=!0,w.isWritable=!0,o.unshift(w)}else o.unshift({pubkey:r,isSigner:!0,isWritable:!0});for(const w of this.signatures){const v=o.findIndex(I=>I.pubkey.equals(w.publicKey));if(v>-1)o[v].isSigner||(o[v].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: ${w.publicKey.toString()}`)}let d=0,f=0,y=0;const S=[],b=[];o.forEach(({pubkey:w,isSigner:v,isWritable:I})=>{v?(S.push(w.toString()),d+=1,I||(f+=1)):(b.push(w.toString()),I||(y+=1))});const M=S.concat(b),C=n.map(w=>{const{data:v,programId:I}=w;return{programIdIndex:M.indexOf(I.toString()),accounts:w.keys.map(N=>M.indexOf(N.pubkey.toString())),data:s.bs58.encode(v)}});return C.forEach(w=>{L(w.programIdIndex>=0),w.accounts.forEach(v=>L(v>=0))}),new We({header:{numRequiredSignatures:d,numReadonlySignedAccounts:f,numReadonlyUnsignedAccounts:y},accountKeys:M,recentBlockhash:e,instructions:C})}_compile(){const e=this.compileMessage(),n=e.accountKeys.slice(0,e.header.numRequiredSignatures);return this.signatures.length===n.length&&this.signatures.every((i,a)=>n[a].equals(i.publicKey))||(this.signatures=n.map(r=>({signature:null,publicKey:r}))),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 n=new Set;this.signatures=e.filter(r=>{const i=r.toString();return n.has(i)?!1:(n.add(i),!0)}).map(r=>({signature:null,publicKey:r}))}sign(...e){if(e.length===0)throw new Error("No signers");const n=new Set,r=[];for(const a of e){const o=a.publicKey.toString();n.has(o)||(n.add(o),r.push(a))}this.signatures=r.map(a=>({signature:null,publicKey:a.publicKey}));const i=this._compile();this._partialSign(i,...r)}partialSign(...e){if(e.length===0)throw new Error("No signers");const n=new Set,r=[];for(const a of e){const o=a.publicKey.toString();n.has(o)||(n.add(o),r.push(a))}const i=this._compile();this._partialSign(i,...r)}_partialSign(e,...n){const r=e.serialize();n.forEach(i=>{const a=ur(r,i.secretKey);this._addSignature(i.publicKey,O(a))})}addSignature(e,n){this._compile(),this._addSignature(e,n)}_addSignature(e,n){L(n.length===64);const r=this.signatures.findIndex(i=>e.equals(i.publicKey));if(r<0)throw new Error(`unknown signer: ${e.toString()}`);this.signatures[r].signature=s.bufferPolyfill.Buffer.from(n)}verifySignatures(e=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),e)}_getMessageSignednessErrors(e,n){const r={};for(const{signature:i,publicKey:a}of this.signatures)i===null?n&&(r.missing||(r.missing=[])).push(a):dr(i,e,a.toBytes())||(r.invalid||(r.invalid=[])).push(a);return r.invalid||r.missing?r:void 0}serialize(e){const{requireAllSignatures:n,verifySignatures:r}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},e),i=this.serializeMessage();if(r){const a=this._getMessageSignednessErrors(i,n);if(a){let o="Signature verification failed.";throw a.invalid&&(o+=`
|
|
2
2
|
Invalid signature for public key${a.invalid.length===1?"":"(s)"} [\`${a.invalid.map(c=>c.toBase58()).join("`, `")}\`].`),a.missing&&(o+=`
|
|
3
3
|
Missing signature for public key${a.missing.length===1?"":"(s)"} [\`${a.missing.map(c=>c.toBase58()).join("`, `")}\`].`),new Error(o)}}return this._serialize(i)}_serialize(e){const{signatures:n}=this,r=[];Ce(r,n.length);const i=r.length+n.length*64+e.length,a=s.bufferPolyfill.Buffer.alloc(i);return L(n.length<256),s.bufferPolyfill.Buffer.from(r).copy(a,0),n.forEach(({signature:o},c)=>{o!==null&&(L(o.length===64,"signature has invalid length"),s.bufferPolyfill.Buffer.from(o).copy(a,r.length+c*64))}),e.copy(a,r.length+n.length*64),L(a.length<=dt,`Transaction too large: ${a.length} > ${dt}`),a}get keys(){return L(this.instructions.length===1),this.instructions[0].keys.map(e=>e.pubkey)}get programId(){return L(this.instructions.length===1),this.instructions[0].programId}get data(){return L(this.instructions.length===1),this.instructions[0].data}static from(e){let n=[...e];const r=Te(n);let i=[];for(let a=0;a<r;a++){const o=ve(n,0,on);i.push(s.bs58.encode(s.bufferPolyfill.Buffer.from(o)))}return q.populate(We.from(n),i)}static populate(e,n=[]){const r=new q;return r.recentBlockhash=e.recentBlockhash,e.header.numRequiredSignatures>0&&(r.feePayer=e.accountKeys[0]),n.forEach((i,a)=>{const o={signature:i==s.bs58.encode(Sr)?null:s.bs58.decode(i),publicKey:e.accountKeys[a]};r.signatures.push(o)}),e.instructions.forEach(i=>{const a=i.accounts.map(o=>{const c=e.accountKeys[o];return{pubkey:c,isSigner:r.signatures.some(d=>d.publicKey.toString()===c.toString())||e.isAccountSigner(o),isWritable:e.isAccountWritable(o)}});r.instructions.push(new U({keys:a,programId:e.accountKeys[i.programIdIndex],data:s.bs58.decode(i.data)}))}),r._message=e,r._json=r.toJSON(),r}}const br=new l("SysvarC1ock11111111111111111111111111111111");new l("SysvarEpochSchedu1e111111111111111111111111");new l("Sysvar1nstructions1111111111111111111111111");const ot=new l("SysvarRecentB1ockHashes11111111111111111111"),Z=new l("SysvarRent111111111111111111111111111111111");new l("SysvarRewards111111111111111111111111111111");new l("SysvarS1otHashes111111111111111111111111111");new l("SysvarS1otHistory11111111111111111111111111");new l("SysvarStakeHistory1111111111111111111111111");function H(t,e){const n=t.layout.span>=0?t.layout.span:cn(t,e),r=s.bufferPolyfill.Buffer.alloc(n),i=Object.assign({instruction:t.index},e);return t.layout.encode(i,r),r}const kr=s.nu64("lamportsPerSignature"),Ar=s.struct([s.u32("version"),s.u32("state"),B("authorizedPubkey"),B("nonce"),s.struct([kr],"feeCalculator")]),qt=Ar.span,Mr=t=>{const e=t.decode.bind(t),n=t.encode.bind(t);return{decode:e,encode:n}},Tr=t=>e=>{const n=s.blob(t,e),{encode:r,decode:i}=Mr(n),a=n;return a.decode=(o,c)=>{const d=i(o,c);return s.toBigIntLE_1(s.bufferPolyfill.Buffer.from(d))},a.encode=(o,c,d)=>{const f=s.toBufferLE_1(o,t);return r(f,c,d)},a},pe=Tr(8),G=Object.freeze({Create:{index:0,layout:s.struct([s.u32("instruction"),s.ns64("lamports"),s.ns64("space"),B("programId")])},Assign:{index:1,layout:s.struct([s.u32("instruction"),B("programId")])},Transfer:{index:2,layout:s.struct([s.u32("instruction"),pe("lamports")])},CreateWithSeed:{index:3,layout:s.struct([s.u32("instruction"),B("base"),me("seed"),s.ns64("lamports"),s.ns64("space"),B("programId")])},AdvanceNonceAccount:{index:4,layout:s.struct([s.u32("instruction")])},WithdrawNonceAccount:{index:5,layout:s.struct([s.u32("instruction"),s.ns64("lamports")])},InitializeNonceAccount:{index:6,layout:s.struct([s.u32("instruction"),B("authorized")])},AuthorizeNonceAccount:{index:7,layout:s.struct([s.u32("instruction"),B("authorized")])},Allocate:{index:8,layout:s.struct([s.u32("instruction"),s.ns64("space")])},AllocateWithSeed:{index:9,layout:s.struct([s.u32("instruction"),B("base"),me("seed"),s.ns64("space"),B("programId")])},AssignWithSeed:{index:10,layout:s.struct([s.u32("instruction"),B("base"),me("seed"),B("programId")])},TransferWithSeed:{index:11,layout:s.struct([s.u32("instruction"),pe("lamports"),me("seed"),B("programId")])},UpgradeNonceAccount:{index:12,layout:s.struct([s.u32("instruction")])}});class K{constructor(){}static createAccount(e){const n=G.Create,r=H(n,{lamports:e.lamports,space:e.space,programId:O(e.programId.toBuffer())});return new U({keys:[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!0,isWritable:!0}],programId:this.programId,data:r})}static transfer(e){let n,r;if("basePubkey"in e){const i=G.TransferWithSeed;n=H(i,{lamports:BigInt(e.lamports),seed:e.seed,programId:O(e.programId.toBuffer())}),r=[{pubkey:e.fromPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}else{const i=G.Transfer;n=H(i,{lamports:BigInt(e.lamports)}),r=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}return new U({keys:r,programId:this.programId,data:n})}static assign(e){let n,r;if("basePubkey"in e){const i=G.AssignWithSeed;n=H(i,{base:O(e.basePubkey.toBuffer()),seed:e.seed,programId:O(e.programId.toBuffer())}),r=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{const i=G.Assign;n=H(i,{programId:O(e.programId.toBuffer())}),r=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new U({keys:r,programId:this.programId,data:n})}static createAccountWithSeed(e){const n=G.CreateWithSeed,r=H(n,{base:O(e.basePubkey.toBuffer()),seed:e.seed,lamports:e.lamports,space:e.space,programId:O(e.programId.toBuffer())});let i=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!1,isWritable:!0}];return e.basePubkey!=e.fromPubkey&&i.push({pubkey:e.basePubkey,isSigner:!0,isWritable:!1}),new U({keys:i,programId:this.programId,data:r})}static createNonceAccount(e){const n=new q;"basePubkey"in e&&"seed"in e?n.add(K.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:qt,programId:this.programId})):n.add(K.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,lamports:e.lamports,space:qt,programId:this.programId}));const r={noncePubkey:e.noncePubkey,authorizedPubkey:e.authorizedPubkey};return n.add(this.nonceInitialize(r)),n}static nonceInitialize(e){const n=G.InitializeNonceAccount,r=H(n,{authorized:O(e.authorizedPubkey.toBuffer())}),i={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:ot,isSigner:!1,isWritable:!1},{pubkey:Z,isSigner:!1,isWritable:!1}],programId:this.programId,data:r};return new U(i)}static nonceAdvance(e){const n=G.AdvanceNonceAccount,r=H(n),i={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:ot,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:r};return new U(i)}static nonceWithdraw(e){const n=G.WithdrawNonceAccount,r=H(n,{lamports:e.lamports});return new U({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0},{pubkey:ot,isSigner:!1,isWritable:!1},{pubkey:Z,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:r})}static nonceAuthorize(e){const n=G.AuthorizeNonceAccount,r=H(n,{authorized:O(e.newAuthorizedPubkey.toBuffer())});return new U({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:r})}static allocate(e){let n,r;if("basePubkey"in e){const i=G.AllocateWithSeed;n=H(i,{base:O(e.basePubkey.toBuffer()),seed:e.seed,space:e.space,programId:O(e.programId.toBuffer())}),r=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{const i=G.Allocate;n=H(i,{space:e.space}),r=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new U({keys:r,programId:this.programId,data:n})}}K.programId=new l("11111111111111111111111111111111");new l("BPFLoader2111111111111111111111111111111111");s.struct([s.u32("typeIndex"),pe("deactivationSlot"),s.nu64("lastExtendedSlot"),s.u8("lastExtendedStartIndex"),s.u8(),s.seq(B(),s.offset(s.u8(),-1),"authority")]);const _=Ke(wt(l),g(),t=>new l(t)),dn=St([g(),E("base64")]),kt=Ke(wt(s.bufferPolyfill.Buffer),dn,t=>s.bufferPolyfill.Buffer.from(t[0],"base64"));function ln(t){return F([h({jsonrpc:E("2.0"),id:g(),result:t}),h({jsonrpc:E("2.0"),id:g(),error:h({code:Ne(),message:g(),data:A(or())})})])}const Cr=ln(Ne());function R(t){return Ke(ln(t),Cr,e=>"error"in e?e:{...e,result:Ee(e.result,t)})}function J(t){return R(h({context:h({slot:u()}),value:t}))}function je(t){return h({context:h({slot:u()}),value:t})}const vr=h({foundation:u(),foundationTerm:u(),initial:u(),taper:u(),terminal:u()});R(p(m(h({epoch:u(),effectiveSlot:u(),amount:u(),postBalance:u(),commission:A(m(u()))}))));const Br=p(h({slot:u(),prioritizationFee:u()})),Ir=h({total:u(),validator:u(),foundation:u(),epoch:u()}),Pr=h({epoch:u(),slotIndex:u(),slotsInEpoch:u(),absoluteSlot:u(),blockHeight:A(u()),transactionCount:A(u())}),Rr=h({slotsPerEpoch:u(),leaderScheduleSlotOffset:u(),warmup:Q(),firstNormalEpoch:u(),firstNormalSlot:u()}),Er=rn(g(),p(u())),ce=m(F([h({}),g()])),Wr=h({err:ce}),xr=E("receivedSignature");h({"solana-core":g(),"feature-set":A(u())});J(h({err:m(F([h({}),g()])),logs:m(p(g())),accounts:A(m(p(m(h({executable:Q(),owner:g(),lamports:u(),data:p(g()),rentEpoch:A(u())}))))),unitsConsumed:A(u()),returnData:A(m(h({programId:g(),data:St([g(),E("base64")])})))}));J(h({byIdentity:rn(g(),p(u())),range:h({firstSlot:u(),lastSlot:u()})}));R(vr);R(Ir);R(Br);R(Pr);R(Rr);R(Er);R(u());J(h({total:u(),circulating:u(),nonCirculating:u(),nonCirculatingAccounts:p(_)}));const _r=h({amount:g(),uiAmount:m(u()),decimals:u(),uiAmountString:A(g())});J(p(h({address:_,amount:g(),uiAmount:m(u()),decimals:u(),uiAmountString:A(g())})));J(p(h({pubkey:_,account:h({executable:Q(),owner:_,lamports:u(),data:kt,rentEpoch:u()})})));const lt=h({program:g(),parsed:Ne(),space:u()});J(p(h({pubkey:_,account:h({executable:Q(),owner:_,lamports:u(),data:lt,rentEpoch:u()})})));J(p(h({lamports:u(),address:_})));const At=h({executable:Q(),owner:_,lamports:u(),data:kt,rentEpoch:u()});h({pubkey:_,account:At});const Nr=Ke(F([wt(s.bufferPolyfill.Buffer),lt]),F([dn,lt]),t=>Array.isArray(t)?Ee(t,kt):t),Kr=h({executable:Q(),owner:_,lamports:u(),data:Nr,rentEpoch:u()});h({pubkey:_,account:Kr});h({state:F([E("active"),E("inactive"),E("activating"),E("deactivating")]),active:u(),inactive:u()});R(p(h({signature:g(),slot:u(),err:ce,memo:m(g()),blockTime:A(m(u()))})));R(p(h({signature:g(),slot:u(),err:ce,memo:m(g()),blockTime:A(m(u()))})));h({subscription:u(),result:je(At)});const Ur=h({pubkey:_,account:At});h({subscription:u(),result:je(Ur)});const zr=h({parent:u(),slot:u(),root:u()});h({subscription:u(),result:zr});const Or=F([h({type:F([E("firstShredReceived"),E("completed"),E("optimisticConfirmation"),E("root")]),slot:u(),timestamp:u()}),h({type:E("createdBank"),parent:u(),slot:u(),timestamp:u()}),h({type:E("frozen"),slot:u(),timestamp:u(),stats:h({numTransactionEntries:u(),numSuccessfulTransactions:u(),numFailedTransactions:u(),maxTransactionsPerEntry:u()})}),h({type:E("dead"),slot:u(),timestamp:u(),err:g()})]);h({subscription:u(),result:Or});h({subscription:u(),result:je(F([Wr,xr]))});h({subscription:u(),result:u()});h({pubkey:g(),gossip:m(g()),tpu:m(g()),rpc:m(g()),version:m(g())});const Dt=h({votePubkey:g(),nodePubkey:g(),activatedStake:u(),epochVoteAccount:Q(),epochCredits:p(St([u(),u(),u()])),commission:u(),lastVote:u(),rootSlot:m(u())});R(h({current:p(Dt),delinquent:p(Dt)}));const Fr=F([E("processed"),E("confirmed"),E("finalized")]),Lr=h({slot:u(),confirmations:m(u()),err:ce,confirmationStatus:A(Fr)});J(p(m(Lr)));R(u());const fn=h({accountKey:_,writableIndexes:p(u()),readonlyIndexes:p(u())}),Mt=h({signatures:p(g()),message:h({accountKeys:p(g()),header:h({numRequiredSignatures:u(),numReadonlySignedAccounts:u(),numReadonlyUnsignedAccounts:u()}),instructions:p(h({accounts:p(u()),data:g(),programIdIndex:u()})),recentBlockhash:g(),addressTableLookups:A(p(fn))})}),hn=h({pubkey:_,signer:Q(),writable:Q(),source:A(F([E("transaction"),E("lookupTable")]))}),gn=h({accountKeys:p(hn),signatures:p(g())}),mn=h({parsed:Ne(),program:g(),programId:_}),pn=h({accounts:p(_),data:g(),programId:_}),qr=F([pn,mn]),Dr=F([h({parsed:Ne(),program:g(),programId:g()}),h({accounts:p(g()),data:g(),programId:g()})]),yn=Ke(qr,Dr,t=>"accounts"in t?Ee(t,pn):Ee(t,mn)),wn=h({signatures:p(g()),message:h({accountKeys:p(hn),instructions:p(yn),recentBlockhash:g(),addressTableLookups:A(m(p(fn)))})}),De=h({accountIndex:u(),mint:g(),owner:A(g()),uiTokenAmount:_r}),Sn=h({writable:p(_),readonly:p(_)}),Ze=h({err:ce,fee:u(),innerInstructions:A(m(p(h({index:u(),instructions:p(h({accounts:p(u()),data:g(),programIdIndex:u()}))})))),preBalances:p(u()),postBalances:p(u()),logMessages:A(m(p(g()))),preTokenBalances:A(m(p(De))),postTokenBalances:A(m(p(De))),loadedAddresses:A(Sn),computeUnitsConsumed:A(u())}),Tt=h({err:ce,fee:u(),innerInstructions:A(m(p(h({index:u(),instructions:p(yn)})))),preBalances:p(u()),postBalances:p(u()),logMessages:A(m(p(g()))),preTokenBalances:A(m(p(De))),postTokenBalances:A(m(p(De))),loadedAddresses:A(Sn),computeUnitsConsumed:A(u())}),Se=F([E(0),E("legacy")]),ue=h({pubkey:g(),lamports:u(),postBalance:m(u()),rewardType:m(g()),commission:A(m(u()))});R(m(h({blockhash:g(),previousBlockhash:g(),parentSlot:u(),transactions:p(h({transaction:Mt,meta:m(Ze),version:A(Se)})),rewards:A(p(ue)),blockTime:m(u()),blockHeight:m(u())})));R(m(h({blockhash:g(),previousBlockhash:g(),parentSlot:u(),rewards:A(p(ue)),blockTime:m(u()),blockHeight:m(u())})));R(m(h({blockhash:g(),previousBlockhash:g(),parentSlot:u(),transactions:p(h({transaction:gn,meta:m(Ze),version:A(Se)})),rewards:A(p(ue)),blockTime:m(u()),blockHeight:m(u())})));R(m(h({blockhash:g(),previousBlockhash:g(),parentSlot:u(),transactions:p(h({transaction:wn,meta:m(Tt),version:A(Se)})),rewards:A(p(ue)),blockTime:m(u()),blockHeight:m(u())})));R(m(h({blockhash:g(),previousBlockhash:g(),parentSlot:u(),transactions:p(h({transaction:gn,meta:m(Tt),version:A(Se)})),rewards:A(p(ue)),blockTime:m(u()),blockHeight:m(u())})));R(m(h({blockhash:g(),previousBlockhash:g(),parentSlot:u(),rewards:A(p(ue)),blockTime:m(u()),blockHeight:m(u())})));R(m(h({blockhash:g(),previousBlockhash:g(),parentSlot:u(),transactions:p(h({transaction:Mt,meta:m(Ze)})),rewards:A(p(ue)),blockTime:m(u())})));R(m(h({blockhash:g(),previousBlockhash:g(),parentSlot:u(),signatures:p(g()),blockTime:m(u())})));R(m(h({slot:u(),meta:m(Ze),blockTime:A(m(u())),transaction:Mt,version:A(Se)})));R(m(h({slot:u(),transaction:wn,meta:m(Tt),blockTime:A(m(u())),version:A(Se)})));J(h({blockhash:g(),feeCalculator:h({lamportsPerSignature:u()})}));J(h({blockhash:g(),lastValidBlockHeight:u()}));J(Q());const Vr=h({slot:u(),numTransactions:u(),numSlots:u(),samplePeriodSecs:u()});R(p(Vr));J(m(h({feeCalculator:h({lamportsPerSignature:u()})})));R(g());R(g());const Hr=h({err:ce,logs:p(g()),signature:g()});h({result:je(Hr),subscription:u()});class ne{constructor(e){this._keypair=void 0,this._keypair=e??zt()}static generate(){return new ne(zt())}static fromSecretKey(e,n){if(e.byteLength!==64)throw new Error("bad secret key size");const r=e.slice(32,64);if(!n||!n.skipValidation){const i=e.slice(0,32),a=ut(i);for(let o=0;o<32;o++)if(r[o]!==a[o])throw new Error("provided secretKey is invalid")}return new ne({publicKey:r,secretKey:e})}static fromSeed(e){const n=ut(e),r=new Uint8Array(64);return r.set(e),r.set(n,32),new ne({publicKey:n,secretKey:r})}get publicKey(){return new l(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}Object.freeze({CreateLookupTable:{index:0,layout:s.struct([s.u32("instruction"),pe("recentSlot"),s.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:s.struct([s.u32("instruction")])},ExtendLookupTable:{index:2,layout:s.struct([s.u32("instruction"),pe(),s.seq(B(),s.offset(s.u32(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:s.struct([s.u32("instruction")])},CloseLookupTable:{index:4,layout:s.struct([s.u32("instruction")])}});new l("AddressLookupTab1e1111111111111111111111111");Object.freeze({RequestUnits:{index:0,layout:s.struct([s.u8("instruction"),s.u32("units"),s.u32("additionalFee")])},RequestHeapFrame:{index:1,layout:s.struct([s.u8("instruction"),s.u32("bytes")])},SetComputeUnitLimit:{index:2,layout:s.struct([s.u8("instruction"),s.u32("units")])},SetComputeUnitPrice:{index:3,layout:s.struct([s.u8("instruction"),pe("microLamports")])}});new l("ComputeBudget111111111111111111111111111111");s.struct([s.u8("numSignatures"),s.u8("padding"),s.u16("signatureOffset"),s.u16("signatureInstructionIndex"),s.u16("publicKeyOffset"),s.u16("publicKeyInstructionIndex"),s.u16("messageDataOffset"),s.u16("messageDataSize"),s.u16("messageInstructionIndex")]);new l("Ed25519SigVerify111111111111111111111111111");s.secp256k1.utils.isValidPrivateKey;s.secp256k1.getPublicKey;s.struct([s.u8("numSignatures"),s.u16("signatureOffset"),s.u8("signatureInstructionIndex"),s.u16("ethAddressOffset"),s.u8("ethAddressInstructionIndex"),s.u16("messageDataOffset"),s.u16("messageDataSize"),s.u8("messageInstructionIndex"),s.blob(20,"ethAddress"),s.blob(64,"signature"),s.u8("recoveryId")]);new l("KeccakSecp256k11111111111111111111111111111");var bn;new l("StakeConfig11111111111111111111111111111111");class kn{constructor(e,n,r){this.unixTimestamp=void 0,this.epoch=void 0,this.custodian=void 0,this.unixTimestamp=e,this.epoch=n,this.custodian=r}}bn=kn;kn.default=new bn(0,0,l.default);Object.freeze({Initialize:{index:0,layout:s.struct([s.u32("instruction"),mr(),pr()])},Authorize:{index:1,layout:s.struct([s.u32("instruction"),B("newAuthorized"),s.u32("stakeAuthorizationType")])},Delegate:{index:2,layout:s.struct([s.u32("instruction")])},Split:{index:3,layout:s.struct([s.u32("instruction"),s.ns64("lamports")])},Withdraw:{index:4,layout:s.struct([s.u32("instruction"),s.ns64("lamports")])},Deactivate:{index:5,layout:s.struct([s.u32("instruction")])},Merge:{index:7,layout:s.struct([s.u32("instruction")])},AuthorizeWithSeed:{index:8,layout:s.struct([s.u32("instruction"),B("newAuthorized"),s.u32("stakeAuthorizationType"),me("authoritySeed"),B("authorityOwner")])}});new l("Stake11111111111111111111111111111111111111");Object.freeze({InitializeAccount:{index:0,layout:s.struct([s.u32("instruction"),yr()])},Authorize:{index:1,layout:s.struct([s.u32("instruction"),B("newAuthorized"),s.u32("voteAuthorizationType")])},Withdraw:{index:3,layout:s.struct([s.u32("instruction"),s.ns64("lamports")])},UpdateValidatorIdentity:{index:4,layout:s.struct([s.u32("instruction")])},AuthorizeWithSeed:{index:10,layout:s.struct([s.u32("instruction"),wr()])}});new l("Vote111111111111111111111111111111111111111");new l("Va1idator1nfo111111111111111111111111111111");h({name:g(),website:A(g()),details:A(g()),keybaseUsername:A(g())});new l("Vote111111111111111111111111111111111111111");s.struct([B("nodePubkey"),B("authorizedWithdrawer"),s.u8("commission"),s.nu64(),s.seq(s.struct([s.nu64("slot"),s.u32("confirmationCount")]),s.offset(s.u32(),-8),"votes"),s.u8("rootSlotValid"),s.nu64("rootSlot"),s.nu64(),s.seq(s.struct([s.nu64("epoch"),B("authorizedVoter")]),s.offset(s.u32(),-8),"authorizedVoters"),s.struct([s.seq(s.struct([B("authorizedPubkey"),s.nu64("epochOfLastAuthorizedSwitch"),s.nu64("targetEpoch")]),32,"buf"),s.nu64("idx"),s.u8("isEmpty")],"priorVoters"),s.nu64(),s.seq(s.struct([s.nu64("epoch"),s.nu64("credits"),s.nu64("prevCredits")]),s.offset(s.u32(),-8),"epochCredits"),s.struct([s.nu64("slot"),s.nu64("timestamp")],"lastTimestamp")]);const W=new l("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");new l("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb");const Je=new l("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"),te=new l("So11111111111111111111111111111111111111112");new l("9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP");class be extends Error{constructor(e){super(e)}}class Ct extends be{constructor(){super(...arguments),this.name="TokenAccountNotFoundError"}}class Gr extends be{constructor(){super(...arguments),this.name="TokenInvalidAccountError"}}class An extends be{constructor(){super(...arguments),this.name="TokenInvalidAccountOwnerError"}}class Ie extends be{constructor(){super(...arguments),this.name="TokenInvalidAccountSizeError"}}class jr extends be{constructor(){super(...arguments),this.name="TokenInvalidMintError"}}class Mn extends be{constructor(){super(...arguments),this.name="TokenOwnerOffCurveError"}}var ye;(function(t){t[t.InitializeMint=0]="InitializeMint",t[t.InitializeAccount=1]="InitializeAccount",t[t.InitializeMultisig=2]="InitializeMultisig",t[t.Transfer=3]="Transfer",t[t.Approve=4]="Approve",t[t.Revoke=5]="Revoke",t[t.SetAuthority=6]="SetAuthority",t[t.MintTo=7]="MintTo",t[t.Burn=8]="Burn",t[t.CloseAccount=9]="CloseAccount",t[t.FreezeAccount=10]="FreezeAccount",t[t.ThawAccount=11]="ThawAccount",t[t.TransferChecked=12]="TransferChecked",t[t.ApproveChecked=13]="ApproveChecked",t[t.MintToChecked=14]="MintToChecked",t[t.BurnChecked=15]="BurnChecked",t[t.InitializeAccount2=16]="InitializeAccount2",t[t.SyncNative=17]="SyncNative",t[t.InitializeAccount3=18]="InitializeAccount3",t[t.InitializeMultisig2=19]="InitializeMultisig2",t[t.InitializeMint2=20]="InitializeMint2",t[t.GetAccountDataSize=21]="GetAccountDataSize",t[t.InitializeImmutableOwner=22]="InitializeImmutableOwner",t[t.AmountToUiAmount=23]="AmountToUiAmount",t[t.UiAmountToAmount=24]="UiAmountToAmount",t[t.InitializeMintCloseAuthority=25]="InitializeMintCloseAuthority",t[t.TransferFeeExtension=26]="TransferFeeExtension",t[t.ConfidentialTransferExtension=27]="ConfidentialTransferExtension",t[t.DefaultAccountStateExtension=28]="DefaultAccountStateExtension",t[t.Reallocate=29]="Reallocate",t[t.MemoTransferExtension=30]="MemoTransferExtension",t[t.CreateNativeMint=31]="CreateNativeMint",t[t.InitializeNonTransferableMint=32]="InitializeNonTransferableMint",t[t.InterestBearingMintExtension=33]="InterestBearingMintExtension",t[t.CpiGuardExtension=34]="CpiGuardExtension",t[t.InitializePermanentDelegate=35]="InitializePermanentDelegate",t[t.TransferHookExtension=36]="TransferHookExtension",t[t.MetadataPointerExtension=39]="MetadataPointerExtension"})(ye||(ye={}));function vt(t,e,n){if(n.length){t.push({pubkey:e,isSigner:!1,isWritable:!1});for(const r of n)t.push({pubkey:r instanceof l?r:r.publicKey,isSigner:!0,isWritable:!1})}else t.push({pubkey:e,isSigner:!0,isWritable:!1});return t}const Vt=s.struct([s.u8("instruction"),s.u64("amount")]);function Zr(t,e,n,r,i=[],a=W){const o=vt([{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:e,isSigner:!1,isWritable:!1}],n,i),c=s.dist.Buffer.alloc(Vt.span);return Vt.encode({instruction:ye.Approve,amount:BigInt(r)},c),new U({keys:o,programId:a,data:c})}const Ht=s.struct([s.u8("instruction")]);function Gt(t,e,n,r=[],i=W){const a=vt([{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:e,isSigner:!1,isWritable:!0}],n,r),o=s.dist.Buffer.alloc(Ht.span);return Ht.encode({instruction:ye.CloseAccount},o),new U({keys:a,programId:i,data:o})}var Ve;(function(t){t[t.Uninitialized=0]="Uninitialized",t[t.Mint=1]="Mint",t[t.Account=2]="Account"})(Ve||(Ve={}));const Bt=1,Jr=s.struct([s.u8("m"),s.u8("n"),s.bool("isInitialized"),s.publicKey("signer1"),s.publicKey("signer2"),s.publicKey("signer3"),s.publicKey("signer4"),s.publicKey("signer5"),s.publicKey("signer6"),s.publicKey("signer7"),s.publicKey("signer8"),s.publicKey("signer9"),s.publicKey("signer10"),s.publicKey("signer11")]),It=Jr.span;var He;(function(t){t[t.Uninitialized=0]="Uninitialized",t[t.Initialized=1]="Initialized",t[t.Frozen=2]="Frozen"})(He||(He={}));const Tn=s.struct([s.publicKey("mint"),s.publicKey("owner"),s.u64("amount"),s.u32("delegateOption"),s.publicKey("delegate"),s.u8("state"),s.u32("isNativeOption"),s.u64("isNative"),s.u64("delegatedAmount"),s.u32("closeAuthorityOption"),s.publicKey("closeAuthority")]),j=Tn.span;async function $r(t,e,n,r=W){const i=await t.getAccountInfo(e,n);return Xr(e,i,r)}async function jt(t,e){return await Yr(t,[],e)}async function Yr(t,e,n){const r=Ws(e);return await t.getMinimumBalanceForRentExemption(r,n)}function Xr(t,e,n=W){if(!e)throw new Ct;if(!e.owner.equals(n))throw new An;if(e.data.length<j)throw new Ie;const r=Tn.decode(e.data.slice(0,j));let i=s.dist.Buffer.alloc(0);if(e.data.length>j){if(e.data.length===It)throw new Ie;if(e.data[j]!=Ve.Account)throw new Gr;i=e.data.slice(j+Bt)}return{address:t,mint:r.mint,owner:r.owner,amount:r.amount,delegate:r.delegateOption?r.delegate:null,delegatedAmount:r.delegatedAmount,isInitialized:r.state!==He.Uninitialized,isFrozen:r.state===He.Frozen,isNative:!!r.isNativeOption,rentExemptReserve:r.isNativeOption?r.isNative:null,closeAuthority:r.closeAuthorityOption?r.closeAuthority:null,tlvData:i}}const Cn=s.struct([s.u32("mintAuthorityOption"),s.publicKey("mintAuthority"),s.u64("supply"),s.u8("decimals"),s.bool("isInitialized"),s.u32("freezeAuthorityOption"),s.publicKey("freezeAuthority")]),ct=Cn.span;async function Qr(t,e,n,r=W){const i=await t.getAccountInfo(e,n);return es(e,i,r)}function es(t,e,n=W){if(!e)throw new Ct;if(!e.owner.equals(n))throw new An;if(e.data.length<ct)throw new Ie;const r=Cn.decode(e.data.slice(0,ct));let i=s.dist.Buffer.alloc(0);if(e.data.length>ct){if(e.data.length<=j)throw new Ie;if(e.data.length===It)throw new Ie;if(e.data[j]!=Ve.Mint)throw new jr;i=e.data.slice(j+Bt)}return{address:t,mintAuthority:r.mintAuthorityOption?r.mintAuthority:null,supply:r.supply,decimals:r.decimals,isInitialized:r.isInitialized,freezeAuthority:r.freezeAuthorityOption?r.freezeAuthority:null,tlvData:i}}async function Zt(t,e,n=!1,r=W,i=Je){if(!n&&!l.isOnCurve(e.toBuffer()))throw new Mn;const[a]=await l.findProgramAddress([e.toBuffer(),r.toBuffer(),t.toBuffer()],i);return a}function Pt(t,e,n=!1,r=W,i=Je){if(!n&&!l.isOnCurve(e.toBuffer()))throw new Mn;const[a]=l.findProgramAddressSync([e.toBuffer(),r.toBuffer(),t.toBuffer()],i);return a}const ts=s.struct([s.bool("lockCpi")]),ns=ts.span,rs=s.struct([s.u8("state")]),ss=rs.span,is=s.struct([]),as=is.span,os=s.struct([s.publicKey("rateAuthority"),s.ns64("initializationTimestamp"),s.s16("preUpdateAverageRate"),s.ns64("lastUpdateTimestamp"),s.s16("currentRate")]),cs=os.span,us=s.struct([s.bool("requireIncomingTransferMemos")]),ds=us.span,ls=s.struct([s.publicKey("authority"),s.publicKey("metadataAddress")]),fs=ls.span,hs=s.struct([s.publicKey("closeAuthority")]),gs=hs.span,vn=s.struct([]),ms=vn.span,ps=vn.span,ys=s.struct([s.publicKey("delegate")]),ws=ys.span,Ss=1e4;BigInt(Ss);function Jt(t){return s.struct([s.u64("epoch"),s.u64("maximumFee"),s.u16("transferFeeBasisPoints")],t)}const bs=s.struct([s.publicKey("transferFeeConfigAuthority"),s.publicKey("withdrawWithheldAuthority"),s.u64("withheldAmount"),Jt("olderTransferFee"),Jt("newerTransferFee")]),ks=bs.span,As=s.struct([s.u64("withheldAmount")]),Ms=As.span,Ts=s.struct([s.publicKey("authority"),s.publicKey("programId")]),Cs=Ts.span,vs=s.struct([s.bool("transferring")]),Bs=vs.span,$t=s.struct([s.u8("discriminator"),s.blob(32,"addressConfig"),s.bool("isSigner"),s.bool("isWritable")]),Is=s.struct([s.u32("count"),s.seq($t,s.greedy($t.span),"extraAccounts")]);s.struct([s.u64("instructionDiscriminator"),s.u32("length"),Is.replicate("extraAccountsList")]);var x;(function(t){t[t.Uninitialized=0]="Uninitialized",t[t.TransferFeeConfig=1]="TransferFeeConfig",t[t.TransferFeeAmount=2]="TransferFeeAmount",t[t.MintCloseAuthority=3]="MintCloseAuthority",t[t.ConfidentialTransferMint=4]="ConfidentialTransferMint",t[t.ConfidentialTransferAccount=5]="ConfidentialTransferAccount",t[t.DefaultAccountState=6]="DefaultAccountState",t[t.ImmutableOwner=7]="ImmutableOwner",t[t.MemoTransfer=8]="MemoTransfer",t[t.NonTransferable=9]="NonTransferable",t[t.InterestBearingConfig=10]="InterestBearingConfig",t[t.CpiGuard=11]="CpiGuard",t[t.PermanentDelegate=12]="PermanentDelegate",t[t.NonTransferableAccount=13]="NonTransferableAccount",t[t.TransferHook=14]="TransferHook",t[t.TransferHookAccount=15]="TransferHookAccount",t[t.MetadataPointer=18]="MetadataPointer"})(x||(x={}));const Yt=2,Ps=2;function Rs(t){switch(t){case x.Uninitialized:return 0;case x.TransferFeeConfig:return ks;case x.TransferFeeAmount:return Ms;case x.MintCloseAuthority:return gs;case x.ConfidentialTransferMint:return 97;case x.ConfidentialTransferAccount:return 286;case x.CpiGuard:return ns;case x.DefaultAccountState:return ss;case x.ImmutableOwner:return as;case x.MemoTransfer:return ds;case x.MetadataPointer:return fs;case x.NonTransferable:return ms;case x.InterestBearingConfig:return cs;case x.PermanentDelegate:return ws;case x.NonTransferableAccount:return ps;case x.TransferHook:return Cs;case x.TransferHookAccount:return Bs;default:throw Error(`Unknown extension type: ${t}`)}}function Es(t,e){if(t.length===0)return e;{const n=j+Bt+t.filter((r,i)=>i===t.indexOf(r)).map(r=>Rs(r)+Yt+Ps).reduce((r,i)=>r+i);return n===It?n+Yt:n}}function Ws(t){return Es(t,j)}const Xt=s.struct([s.u8("instruction")]);function Qt(t,e,n,r=W){const i=[{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:e,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:Z,isSigner:!1,isWritable:!1}],a=s.dist.Buffer.alloc(Xt.span);return Xt.encode({instruction:ye.InitializeAccount},a),new U({keys:i,programId:r,data:a})}function Bn(t,e,n,r,i=W,a=Je){return xs(t,e,n,r,s.dist.Buffer.alloc(0),i,a)}function xs(t,e,n,r,i,a=W,o=Je){const c=[{pubkey:t,isSigner:!0,isWritable:!0},{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:K.programId,isSigner:!1,isWritable:!1},{pubkey:a,isSigner:!1,isWritable:!1}];return new U({keys:c,programId:o,data:i})}const en=s.struct([s.u8("instruction"),s.u64("amount")]);function _s(t,e,n,r,i=[],a=W){const o=vt([{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:e,isSigner:!1,isWritable:!0}],n,i),c=s.dist.Buffer.alloc(en.span);return en.encode({instruction:ye.Transfer,amount:BigInt(r)},c),new U({keys:o,programId:a,data:c})}function $e(t,e){const n=s.dist.Buffer.alloc(2);return n.writeUInt16BE(s.toChainId(e)),k.deriveAddress([s.dist.Buffer.from("foreign_contract"),n],t)}function In(t){return k.deriveAddress([s.dist.Buffer.from("redeemer")],t)}function Ye(t,e){return k.deriveAddress([s.dist.Buffer.from("mint"),new l(e).toBuffer()],t)}function Rt(t){return k.deriveAddress([s.dist.Buffer.from("sender")],t)}function Et(t,e){return k.deriveAddress([s.dist.Buffer.from("tmp"),new l(e).toBuffer()],t)}function Wt(t,e,n){return k.deriveAddress([s.dist.Buffer.from("bridged"),new l(e).toBuffer(),s.dist.Buffer.from(s.bignum.toBytes(BigInt(n.toString()),8))],t)}function z(t){return k.deriveAddress([s.dist.Buffer.from("config")],t)}async function Ns(t,e,n){return t.getAccountInfo(z(e),n).then(r=>Xe.deserialize(k.getAccountData(r)))}class Xe{constructor(e){T(this,"wormhole");this.wormhole=new l(e)}static deserialize(e){if(e.length!=32)throw new Error("data.length != 32");const n=e.subarray(0,32);return new Xe(n)}}function Ue(t,e){return k.deriveAddress([new l(e).toBuffer()],t)}function de(t,e,n){if(e==s.toChainId("Solana"))throw new Error("emitterChain == CHAIN_ID_SOLANA cannot exist as foreign token bridge emitter");const r=typeof n=="string"?new s.UniversalAddress(n).toUint8Array():n;return k.deriveAddress([(()=>{const i=s.dist.Buffer.alloc(2);return i.writeUInt16BE(e),i})(),r],t)}async function Ks(t,e,n){return t.getAccountInfo(new l(e),n).then(r=>Qe.deserialize(k.getAccountData(r)))}class Qe{constructor(e,n){T(this,"chain");T(this,"contract");this.chain=e,this.contract=n}static deserialize(e){if(e.length!=34)throw new Error("data.length != 34");const n=e.readUInt16LE(0),r=e.subarray(2,34);return new Qe(n,r)}}function et(t){return k.deriveAddress([s.dist.Buffer.from("sender")],t)}function tt(t){return k.deriveAddress([s.dist.Buffer.from("redeemer")],t)}function le(t){return k.deriveAddress([s.dist.Buffer.from("authority_signer")],t)}function ke(t){return k.deriveAddress([s.dist.Buffer.from("custody_signer")],t)}function ze(t){return k.deriveAddress([s.dist.Buffer.from("mint_signer")],t)}function fe(t,e,n){if(e==s.toChainId("Solana"))throw new Error("tokenChain == CHAIN_ID_SOLANA does not have wrapped mint key");return k.deriveAddress([s.dist.Buffer.from("wrapped"),(()=>{const r=s.dist.Buffer.alloc(2);return r.writeUInt16BE(e),r})(),n],t)}function ie(t,e){return k.deriveAddress([s.dist.Buffer.from("meta"),new l(e).toBuffer()],t)}async function Pe(t,e,n,r){return t.getAccountInfo(ie(e,n),r).then(i=>nt.deserialize(k.getAccountData(i)))}class nt{constructor(e,n,r,i){T(this,"chain");T(this,"tokenAddress");T(this,"originalDecimals");T(this,"lastUpdatedSequence");this.chain=e,this.tokenAddress=n,this.originalDecimals=r,this.lastUpdatedSequence=i}static deserialize(e){if(e.length!==35&&e.length!==43)throw new Error(`invalid wrapped meta length: ${e.length}`);const n=e.readUInt16LE(0),r=e.subarray(2,34),i=e.readUInt8(34),a=e.length===43?e.readBigUInt64LE(35):void 0;return new nt(n,r,i,a)}}function ft(t,e,n,r){return Zr(new l(e),le(t),new l(n),r)}class Us{constructor(e){T(this,"idl");this.idl=e}async encode(e,n){switch(e){default:throw new Error(`Invalid account name: ${e}`)}}decode(e,n){return this.decodeUnchecked(e,n)}decodeUnchecked(e,n){switch(e){default:throw new Error(`Invalid account name: ${e}`)}}memcmp(e,n){switch(e){default:throw new Error(`Invalid account name: ${e}`)}}size(e){return k.accountSize(this.idl,e)??0}}class zs{constructor(e){}decode(e){throw new Error("Token Bridge program does not have events")}}class Os{constructor(e){}encode(e,n){switch(e){case"initialize":return Fs(n);case"attestToken":return Ls(n);case"completeNative":return qs(n);case"completeWrapped":return Ds(n);case"transferWrapped":return Vs(n);case"transferNative":return Hs(n);case"registerChain":return Gs(n);case"createWrapped":return js(n);case"upgradeContract":return Zs(n);case"transferWrappedWithPayload":return Js(n);case"transferNativeWithPayload":return $s(n);default:throw new Error(`Invalid instruction: ${e}`)}}encodeState(e,n){throw new Error("Token Bridge program does not have state")}}var D;(function(t){t[t.Initialize=0]="Initialize",t[t.AttestToken=1]="AttestToken",t[t.CompleteNative=2]="CompleteNative",t[t.CompleteWrapped=3]="CompleteWrapped",t[t.TransferWrapped=4]="TransferWrapped",t[t.TransferNative=5]="TransferNative",t[t.RegisterChain=6]="RegisterChain",t[t.CreateWrapped=7]="CreateWrapped",t[t.UpgradeContract=8]="UpgradeContract",t[t.CompleteNativeWithPayload=9]="CompleteNativeWithPayload",t[t.CompleteWrappedWithPayload=10]="CompleteWrappedWithPayload",t[t.TransferWrappedWithPayload=11]="TransferWrappedWithPayload",t[t.TransferNativeWithPayload=12]="TransferNativeWithPayload"})(D||(D={}));function Y(t,e){const n=e===void 0?0:e.length,r=s.dist.Buffer.alloc(1+n);return r.writeUInt8(t,0),n>0&&r.write(e.toString("hex"),1,"hex"),r}function Fs({wormhole:t}){const e=s.dist.Buffer.alloc(32);return e.write(new l(t).toBuffer().toString("hex"),0,"hex"),Y(D.Initialize,e)}function Ls({nonce:t}){const e=s.dist.Buffer.alloc(4);return e.writeUInt32LE(t,0),Y(D.AttestToken,e)}function qs({}){return Y(D.CompleteNative)}function Ds({}){return Y(D.CompleteWrapped)}function Pn({nonce:t,amount:e,fee:n,targetAddress:r,targetChain:i}){if(typeof e!="bigint"&&(e=BigInt(e)),typeof n!="bigint"&&(n=BigInt(n)),!s.dist.Buffer.isBuffer(r))throw new Error("targetAddress must be Buffer");const a=s.dist.Buffer.alloc(54);return a.writeUInt32LE(t,0),a.writeBigUInt64LE(e,4),a.writeBigUInt64LE(n,12),a.write(r.toString("hex"),20,"hex"),a.writeUInt16LE(i,52),a}function Vs({nonce:t,amount:e,fee:n,targetAddress:r,targetChain:i}){return Y(D.TransferWrapped,Pn({nonce:t,amount:e,fee:n,targetAddress:r,targetChain:i}))}function Hs({nonce:t,amount:e,fee:n,targetAddress:r,targetChain:i}){return Y(D.TransferNative,Pn({nonce:t,amount:e,fee:n,targetAddress:r,targetChain:i}))}function Gs({}){return Y(D.RegisterChain)}function js({}){return Y(D.CreateWrapped)}function Zs({}){return Y(D.UpgradeContract)}function Rn({nonce:t,amount:e,targetAddress:n,targetChain:r,payload:i}){if(typeof e!="bigint"&&(e=BigInt(e)),!s.dist.Buffer.isBuffer(n))throw new Error("targetAddress must be Buffer");if(!s.dist.Buffer.isBuffer(i))throw new Error("payload must be Buffer");const a=s.dist.Buffer.alloc(50);return a.writeUInt32LE(t,0),a.writeBigUInt64LE(e,4),a.write(n.toString("hex"),12,"hex"),a.writeUInt16LE(r,44),a.writeUInt32LE(i.length,46),s.dist.Buffer.concat([a,i,s.dist.Buffer.alloc(1)])}function Js({nonce:t,amount:e,fee:n,targetAddress:r,targetChain:i,payload:a}){return Y(D.TransferWrappedWithPayload,Rn({nonce:t,amount:e,fee:n,targetAddress:r,targetChain:i,payload:a}))}function $s({nonce:t,amount:e,fee:n,targetAddress:r,targetChain:i,payload:a}){return Y(D.TransferNativeWithPayload,Rn({nonce:t,amount:e,fee:n,targetAddress:r,targetChain:i,payload:a}))}class Ys{constructor(e){}encode(e,n){throw new Error("Token Bridge program does not have state")}decode(e){throw new Error("Token Bridge program does not have state")}}class Xs{constructor(e){}encode(e,n){throw new Error("Token Bridge program does not have user-defined types")}decode(e,n){throw new Error("Token Bridge program does not have user-defined types")}}class Qs{constructor(e){T(this,"instruction");T(this,"accounts");T(this,"state");T(this,"events");T(this,"types");this.instruction=new Os(e),this.accounts=new Us(e),this.state=new Ys(e),this.events=new zs(e),this.types=new Xs(e)}}const xt={version:"0.1.0",name:"wormhole",instructions:[{name:"initialize",accounts:[{name:"payer",isMut:!0,isSigner:!0},{name:"config",isMut:!0,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1}],args:[{name:"wormhole",type:"publicKey"}]},{name:"attestToken",accounts:[{name:"payer",isMut:!0,isSigner:!0},{name:"config",isMut:!0,isSigner:!1},{name:"mint",isMut:!1,isSigner:!1},{name:"wrappedMeta",isMut:!1,isSigner:!1},{name:"splMetadata",isMut:!1,isSigner:!1},{name:"wormholeBridge",isMut:!0,isSigner:!1},{name:"wormholeMessage",isMut:!0,isSigner:!0},{name:"wormholeEmitter",isMut:!1,isSigner:!1},{name:"wormholeSequence",isMut:!0,isSigner:!1},{name:"wormholeFeeCollector",isMut:!0,isSigner:!1},{name:"clock",isMut:!1,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1},{name:"wormholeProgram",isMut:!1,isSigner:!1}],args:[{name:"nonce",type:"u32"}]},{name:"completeNative",accounts:[{name:"payer",isMut:!0,isSigner:!0},{name:"config",isMut:!1,isSigner:!1},{name:"vaa",isMut:!1,isSigner:!1},{name:"claim",isMut:!0,isSigner:!1},{name:"endpoint",isMut:!1,isSigner:!1},{name:"to",isMut:!0,isSigner:!1},{name:"toFees",isMut:!0,isSigner:!1},{name:"custody",isMut:!0,isSigner:!1},{name:"mint",isMut:!1,isSigner:!1},{name:"custodySigner",isMut:!1,isSigner:!1},{name:"rent",isMut:!0,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1},{name:"tokenProgram",isMut:!1,isSigner:!1},{name:"wormholeProgram",isMut:!1,isSigner:!1}],args:[]},{name:"completeWrapped",accounts:[{name:"payer",isMut:!0,isSigner:!0},{name:"config",isMut:!1,isSigner:!1},{name:"vaa",isMut:!1,isSigner:!1},{name:"claim",isMut:!0,isSigner:!1},{name:"endpoint",isMut:!1,isSigner:!1},{name:"to",isMut:!0,isSigner:!1},{name:"toFees",isMut:!0,isSigner:!1},{name:"mint",isMut:!0,isSigner:!1},{name:"wrappedMeta",isMut:!1,isSigner:!1},{name:"mintAuthority",isMut:!1,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1},{name:"tokenProgram",isMut:!1,isSigner:!1},{name:"wormholeProgram",isMut:!1,isSigner:!1}],args:[]},{name:"transferWrapped",accounts:[{name:"payer",isMut:!0,isSigner:!0},{name:"config",isMut:!1,isSigner:!1},{name:"from",isMut:!0,isSigner:!1},{name:"fromOwner",isMut:!0,isSigner:!0},{name:"mint",isMut:!0,isSigner:!1},{name:"wrappedMeta",isMut:!1,isSigner:!1},{name:"authoritySigner",isMut:!1,isSigner:!1},{name:"wormholeBridge",isMut:!0,isSigner:!1},{name:"wormholeMessage",isMut:!0,isSigner:!0},{name:"wormholeEmitter",isMut:!1,isSigner:!1},{name:"wormholeSequence",isMut:!0,isSigner:!1},{name:"wormholeFeeCollector",isMut:!0,isSigner:!1},{name:"clock",isMut:!1,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1},{name:"tokenProgram",isMut:!1,isSigner:!1},{name:"wormholeProgram",isMut:!1,isSigner:!1}],args:[{name:"nonce",type:"u32"},{name:"amount",type:"u64"},{name:"fee",type:"u64"},{name:"targetAddress",type:{array:["u8",32]}},{name:"targetChain",type:"u16"}]},{name:"transferNative",accounts:[{name:"payer",isMut:!0,isSigner:!0},{name:"config",isMut:!1,isSigner:!1},{name:"from",isMut:!0,isSigner:!1},{name:"mint",isMut:!0,isSigner:!1},{name:"custody",isMut:!0,isSigner:!1},{name:"authoritySigner",isMut:!1,isSigner:!1},{name:"custodySigner",isMut:!1,isSigner:!1},{name:"wormholeBridge",isMut:!0,isSigner:!1},{name:"wormholeMessage",isMut:!0,isSigner:!0},{name:"wormholeEmitter",isMut:!1,isSigner:!1},{name:"wormholeSequence",isMut:!0,isSigner:!1},{name:"wormholeFeeCollector",isMut:!0,isSigner:!1},{name:"clock",isMut:!1,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1},{name:"tokenProgram",isMut:!1,isSigner:!1},{name:"wormholeProgram",isMut:!1,isSigner:!1}],args:[{name:"nonce",type:"u32"},{name:"amount",type:"u64"},{name:"fee",type:"u64"},{name:"targetAddress",type:{array:["u8",32]}},{name:"targetChain",type:"u16"}]},{name:"registerChain",accounts:[{name:"payer",isMut:!0,isSigner:!0},{name:"config",isMut:!1,isSigner:!1},{name:"endpoint",isMut:!0,isSigner:!1},{name:"vaa",isMut:!1,isSigner:!1},{name:"claim",isMut:!0,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1},{name:"wormholeProgram",isMut:!1,isSigner:!1}],args:[]},{name:"createWrapped",accounts:[{name:"payer",isMut:!0,isSigner:!0},{name:"config",isMut:!1,isSigner:!1},{name:"endpoint",isMut:!1,isSigner:!1},{name:"vaa",isMut:!1,isSigner:!1},{name:"claim",isMut:!0,isSigner:!1},{name:"mint",isMut:!0,isSigner:!1},{name:"wrappedMeta",isMut:!0,isSigner:!1},{name:"splMetadata",isMut:!0,isSigner:!1},{name:"mintAuthority",isMut:!1,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1},{name:"tokenProgram",isMut:!1,isSigner:!1},{name:"splMetadataProgram",isMut:!1,isSigner:!1},{name:"wormholeProgram",isMut:!1,isSigner:!1}],args:[]},{name:"upgradeContract",accounts:[{name:"payer",isMut:!0,isSigner:!0},{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:"tokenBridgeProgram",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:"transferWrappedWithPayload",accounts:[{name:"payer",isMut:!0,isSigner:!0},{name:"config",isMut:!1,isSigner:!1},{name:"from",isMut:!0,isSigner:!1},{name:"fromOwner",isMut:!0,isSigner:!0},{name:"mint",isMut:!0,isSigner:!1},{name:"wrappedMeta",isMut:!1,isSigner:!1},{name:"authoritySigner",isMut:!1,isSigner:!1},{name:"wormholeBridge",isMut:!0,isSigner:!1},{name:"wormholeMessage",isMut:!0,isSigner:!0},{name:"wormholeEmitter",isMut:!1,isSigner:!1},{name:"wormholeSequence",isMut:!0,isSigner:!1},{name:"wormholeFeeCollector",isMut:!0,isSigner:!1},{name:"clock",isMut:!1,isSigner:!1},{name:"sender",isMut:!1,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1},{name:"tokenProgram",isMut:!1,isSigner:!1},{name:"wormholeProgram",isMut:!1,isSigner:!1}],args:[{name:"nonce",type:"u32"},{name:"amount",type:"u64"},{name:"targetAddress",type:{array:["u8",32]}},{name:"targetChain",type:"u16"},{name:"payload",type:"bytes"},{name:"cpiProgramId",type:{option:"publicKey"}}]},{name:"transferNativeWithPayload",accounts:[{name:"payer",isMut:!0,isSigner:!0},{name:"config",isMut:!1,isSigner:!1},{name:"from",isMut:!0,isSigner:!1},{name:"mint",isMut:!0,isSigner:!1},{name:"custody",isMut:!0,isSigner:!1},{name:"authoritySigner",isMut:!1,isSigner:!1},{name:"custodySigner",isMut:!1,isSigner:!1},{name:"wormholeBridge",isMut:!0,isSigner:!1},{name:"wormholeMessage",isMut:!0,isSigner:!0},{name:"wormholeEmitter",isMut:!1,isSigner:!1},{name:"wormholeSequence",isMut:!0,isSigner:!1},{name:"wormholeFeeCollector",isMut:!0,isSigner:!1},{name:"clock",isMut:!1,isSigner:!1},{name:"sender",isMut:!1,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1},{name:"tokenProgram",isMut:!1,isSigner:!1},{name:"wormholeProgram",isMut:!1,isSigner:!1}],args:[{name:"nonce",type:"u32"},{name:"amount",type:"u64"},{name:"targetAddress",type:{array:["u8",32]}},{name:"targetChain",type:"u16"},{name:"payload",type:"bytes"},{name:"cpiProgramId",type:{option:"publicKey"}}]}],accounts:[]};function En(t,e){return new s.Program(xt,new l(t),e===void 0?{connection:null}:e,Wn())}function V(t,e){return En(t,er.createReadOnlyProvider(e))}function Wn(){return new Qs(xt)}const Re=class Re{constructor(e,n,r){T(this,"address");T(this,"verified");T(this,"share");this.address=new l(e),this.verified=n,this.share=r}serialize(){const e=s.dist.Buffer.alloc(Re.size);return e.write(this.address.toBuffer().toString("hex"),0,"hex"),this.verified&&e.writeUInt8(1,32),e.writeUInt8(this.share,33),e}static deserialize(e){const n=e.subarray(0,32),r=e.readUInt8(32)>0,i=e.readUInt8(33);return new Re(n,r,i)}};T(Re,"size",34);let re=Re;class Oe{constructor(e,n,r,i,a){T(this,"name");T(this,"symbol");T(this,"uri");T(this,"sellerFeeBasisPoints");T(this,"creators");this.name=e,this.symbol=n,this.uri=r,this.sellerFeeBasisPoints=i,this.creators=a}serialize(){const e=this.name.length,n=this.symbol.length,r=this.uri.length,i=this.creators,[a,o]=(()=>{if(i===null)return[0,0];const d=i.length;return[d,4+d*re.size]})(),c=s.dist.Buffer.alloc(15+e+n+r+o);if(c.writeUInt32LE(e,0),c.write(this.name,4),c.writeUInt32LE(n,4+e),c.write(this.symbol,8+e),c.writeUInt32LE(r,8+e+n),c.write(this.uri,12+e+n),c.writeUInt16LE(this.sellerFeeBasisPoints,12+e+n+r),i===null)c.writeUInt8(0,14+e+n+r);else{c.writeUInt8(1,14+e+n+r),c.writeUInt32LE(a,15+e+n+r);for(let d=0;d<a;++d){const f=i.at(d),y=19+e+n+r+d*re.size;c.write(f.serialize().toString("hex"),y,"hex")}}return c}static deserialize(e){const n=e.readUInt32LE(0),r=e.subarray(4,4+n).toString(),i=e.readUInt32LE(4+n),a=e.subarray(8+n,8+n+i).toString(),o=e.readUInt32LE(8+n+i),c=e.subarray(12+n+i,12+n+i+o).toString(),d=e.readUInt16LE(12+n+i+o),f=e.readUInt8(14+n+i+o),y=(()=>{if(f==0)return null;const S=[],b=e.readUInt32LE(15+n+i+o);for(let M=0;M<b;++M){const C=19+n+i+o+M*re.size;S.push(re.deserialize(e.subarray(C,C+re.size)))}return S})();return new Oe(r,a,c,d,y)}}class xe extends Oe{constructor(n,r,i,a,o,c){super(n,r,i,a,o);T(this,"isMutable");this.isMutable=c}static serialize(n,r,i,a,o,c){return new xe(n,r,i,a,o,c).serialize()}static serializeInstructionData(n,r,i,a,o,c){return s.dist.Buffer.concat([s.dist.Buffer.alloc(1,0),xe.serialize(n,r,i,a,o,c)])}serialize(){return s.dist.Buffer.concat([super.serialize(),s.dist.Buffer.alloc(1,this.isMutable?1:0)])}}const Ge=class Ge{constructor(){}static createMetadataAccounts(e,n,r,i,a,o,c=!1,d,f,y,S=!1,b=Fe(n)){const M=[k.newAccountMeta(b,!1),k.newReadOnlyAccountMeta(n,!1),k.newReadOnlyAccountMeta(r,!0),k.newReadOnlyAccountMeta(e,!0),k.newReadOnlyAccountMeta(o,c),k.newReadOnlyAccountMeta(K.programId,!1),k.newReadOnlyAccountMeta(Z,!1)],C=xe.serializeInstructionData(i,a,d===void 0?"":d,y===void 0?0:y,f===void 0?null:f,S);return{programId:Ge.programId,keys:M,data:C}}};T(Ge,"programId",new l("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"));let we=Ge;function Fe(t){return k.deriveAddress([s.dist.Buffer.from("metadata"),we.programId.toBuffer(),new l(t).toBuffer()],we.programId)}exports.Key=void 0;(function(t){t[t.Uninitialized=0]="Uninitialized",t[t.EditionV1=1]="EditionV1",t[t.MasterEditionV1=2]="MasterEditionV1",t[t.ReservationListV1=3]="ReservationListV1",t[t.MetadataV1=4]="MetadataV1",t[t.ReservationListV2=5]="ReservationListV2",t[t.MasterEditionV2=6]="MasterEditionV2",t[t.EditionMarker=7]="EditionMarker"})(exports.Key||(exports.Key={}));class rt{constructor(e,n,r,i,a,o){T(this,"key");T(this,"updateAuthority");T(this,"mint");T(this,"data");T(this,"primarySaleHappened");T(this,"isMutable");this.key=e,this.updateAuthority=new l(n),this.mint=new l(r),this.data=i,this.primarySaleHappened=a,this.isMutable=o}static deserialize(e){const n=e.readUInt8(0),r=e.subarray(1,33),i=e.subarray(33,65),a=Oe.deserialize(e.subarray(65)),o=a.serialize().length,c=e.readUInt8(65+o)>0,d=e.readUInt8(66+o)>0;return new rt(n,r,i,a,c,d)}}async function ei(t,e,n){return t.getAccountInfo(Fe(e),n).then(r=>rt.deserialize(k.getAccountData(r)))}function xn(t,e,n,r,i,a,o){const c=V(e,t).methods.attestToken(o);return console.log(ht(e,n,r,i,a)),c._ixFn(...c._args,{accounts:ht(e,n,r,i,a),signers:void 0,remainingAccounts:void 0,preInstructions:void 0,postInstructions:void 0})}function ht(t,e,n,r,i){const{bridge:a,emitter:o,sequence:c,feeCollector:d,clock:f,rent:y,systemProgram:S}=k.getPostMessageAccounts(e,n,i,t);return{payer:new l(n),config:z(t),mint:new l(r),wrappedMeta:ie(t,r),splMetadata:Fe(r),wormholeBridge:a,wormholeMessage:new l(i),wormholeEmitter:o,wormholeSequence:c,wormholeFeeCollector:d,clock:f,rent:y,systemProgram:S,wormholeProgram:new l(e)}}function gt(t,e,n,r,i,a){const o=V(e,t).methods.completeNative();return o._ixFn(...o._args,{accounts:_n(e,n,r,i,a),signers:void 0,remainingAccounts:void 0,preInstructions:void 0,postInstructions:void 0})}function _n(t,e,n,r,i){const a=new l(r.payload.token.address.toUint8Array());return{payer:new l(n),config:z(t),vaa:k.derivePostedVaaKey(e,s.dist.Buffer.from(r.hash)),claim:k.deriveClaimKey(t,r.emitterAddress.toUint8Array(),s.toChainId(r.emitterChain),r.sequence),endpoint:de(t,s.toChainId(r.emitterChain),r.emitterAddress.toUint8Array()),to:new l(r.payload.to.address.toUint8Array()),toFees:new l(i===void 0?r.payload.to.address.toUint8Array():i),custody:Ue(t,a),mint:a,custodySigner:ke(t),rent:Z,systemProgram:K.programId,tokenProgram:W,wormholeProgram:new l(e)}}function Nn(t,e,n,r,i,a){const o=V(e,t).methods.completeWrapped();return o._ixFn(...o._args,{accounts:Kn(e,n,r,i,a),signers:void 0,remainingAccounts:void 0,preInstructions:void 0,postInstructions:void 0})}function Kn(t,e,n,r,i){const a=fe(t,s.toChainId(r.payload.token.chain),r.payload.token.address.toUint8Array());return{payer:new l(n),config:z(t),vaa:k.derivePostedVaaKey(e,s.dist.Buffer.from(r.hash)),claim:k.deriveClaimKey(t,r.emitterAddress.toUint8Array(),s.toChainId(r.emitterChain),r.sequence),endpoint:de(t,s.toChainId(r.emitterChain),r.emitterAddress.toUint8Array()),to:new l(r.payload.to.address.toUint8Array()),toFees:new l(i===void 0?r.payload.to.address.toUint8Array():i),mint:a,wrappedMeta:ie(t,a),mintAuthority:ze(t),rent:Z,systemProgram:K.programId,tokenProgram:W,wormholeProgram:new l(e)}}function Un(t,e,n,r,i){const a=V(e,t).methods.createWrapped();return a._ixFn(...a._args,{accounts:zn(e,n,r,i),signers:void 0,remainingAccounts:void 0,preInstructions:void 0,postInstructions:void 0})}function zn(t,e,n,r){const i=fe(t,s.toChainId(r.payload.token.chain),r.payload.token.address.toUint8Array());return{payer:new l(n),config:z(t),endpoint:de(t,s.toChainId(r.emitterChain),r.emitterAddress.toUint8Array()),vaa:k.derivePostedVaaKey(e,s.dist.Buffer.from(r.hash)),claim:k.deriveClaimKey(t,r.emitterAddress.toUint8Array(),s.toChainId(r.emitterChain),r.sequence),mint:i,wrappedMeta:ie(t,i),splMetadata:Fe(i),mintAuthority:ze(t),rent:Z,systemProgram:K.programId,tokenProgram:W,splMetadataProgram:we.programId,wormholeProgram:new l(e)}}function ti(t,e,n){const r=V(t).methods.initialize(n);return r._ixFn(...r._args,{accounts:On(t,e),signers:void 0,remainingAccounts:void 0,preInstructions:void 0,postInstructions:void 0})}function On(t,e){return{payer:new l(e),config:z(t),rent:Z,systemProgram:K.programId}}function ni(t,e,n,r){const i=V(t).methods.registerChain();return i._ixFn(...i._args,{accounts:Fn(t,e,n,r),signers:void 0,remainingAccounts:void 0,preInstructions:void 0,postInstructions:void 0})}function Fn(t,e,n,r){return{payer:new l(n),config:z(t),endpoint:de(t,s.toChainId(r.payload.foreignChain),r.payload.foreignAddress.toUint8Array()),vaa:k.derivePostedVaaKey(e,s.dist.Buffer.from(r.hash)),claim:k.deriveClaimKey(t,r.emitterAddress.toUint8Array(),s.toChainId(r.emitterChain),r.sequence),rent:Z,systemProgram:K.programId,wormholeProgram:new l(e)}}function ri(t,e,n,r,i){const a=V(t).methods.upgradeContract();return a._ixFn(...a._args,{accounts:Ln(t,e,n,r,i),signers:void 0,remainingAccounts:void 0,preInstructions:void 0,postInstructions:void 0})}function Ln(t,e,n,r,i){return{payer:new l(n),vaa:k.derivePostedVaaKey(e,s.dist.Buffer.from(r.hash)),claim:k.deriveClaimKey(t,r.emitterAddress.toUint8Array(),s.toChainId(r.emitterChain),r.sequence),upgradeAuthority:k.deriveUpgradeAuthorityKey(t),spill:new l(i===void 0?n:i),implementation:new l(r.payload.newContract),programData:k.deriveUpgradeableProgramKey(t),tokenBridgeProgram:new l(t),rent:Z,clock:br,bpfLoaderUpgradeable:k.BpfLoaderUpgradeable.programId,systemProgram:K.programId}}function mt(t,e,n,r,i,a,o,c,d,f,y,S){const b=V(e,t).methods.transferNative(c,d,f,s.dist.Buffer.from(y),S);return b._ixFn(...b._args,{accounts:qn(e,n,r,i,a,o),signers:void 0,remainingAccounts:void 0,preInstructions:void 0,postInstructions:void 0})}function qn(t,e,n,r,i,a){const{wormholeBridge:o,wormholeMessage:c,wormholeEmitter:d,wormholeSequence:f,wormholeFeeCollector:y,clock:S,rent:b,systemProgram:M}=k.getPostMessageCpiAccounts(t,e,n,r);return{payer:new l(n),config:z(t),from:new l(i),mint:new l(a),custody:Ue(t,a),authoritySigner:le(t),custodySigner:ke(t),wormholeBridge:o,wormholeMessage:c,wormholeEmitter:d,wormholeSequence:f,wormholeFeeCollector:y,clock:S,rent:b,systemProgram:M,tokenProgram:W,wormholeProgram:new l(e)}}function pt(t,e,n,r,i,a,o,c,d,f,y,S){const b=V(e,t).methods.transferNativeWithPayload(c,d,s.dist.Buffer.from(f),y,s.dist.Buffer.from(S),null);return b._ixFn(...b._args,{accounts:_t(e,n,r,i,a,o),signers:void 0,remainingAccounts:void 0,preInstructions:void 0,postInstructions:void 0})}function _t(t,e,n,r,i,a,o){const{wormholeBridge:c,wormholeMessage:d,wormholeEmitter:f,wormholeSequence:y,wormholeFeeCollector:S,clock:b,rent:M,systemProgram:C}=k.getPostMessageCpiAccounts(t,e,n,r);return{payer:new l(n),config:z(t),from:new l(i),mint:new l(a),custody:Ue(t,a),authoritySigner:le(t),custodySigner:ke(t),wormholeBridge:c,wormholeMessage:d,wormholeEmitter:f,wormholeSequence:y,wormholeFeeCollector:S,clock:b,sender:new l(o===void 0?n:et(o)),rent:M,systemProgram:C,tokenProgram:W,wormholeProgram:new l(e)}}function Dn(t,e,n,r,i,a,o,c,d,f,y,S,b,M){const C=V(e,t).methods.transferWrapped(f,y,S,s.dist.Buffer.from(b),M);return C._ixFn(...C._args,{accounts:Vn(e,n,r,i,a,o,c,d),signers:void 0,remainingAccounts:void 0,preInstructions:void 0,postInstructions:void 0})}function Vn(t,e,n,r,i,a,o,c){const d=fe(t,o,c),{wormholeBridge:f,wormholeMessage:y,wormholeEmitter:S,wormholeSequence:b,wormholeFeeCollector:M,clock:C,rent:w,systemProgram:v}=k.getPostMessageCpiAccounts(t,e,n,r);return{payer:new l(n),config:z(t),from:new l(i),fromOwner:new l(a),mint:d,wrappedMeta:ie(t,d),authoritySigner:le(t),wormholeBridge:f,wormholeMessage:y,wormholeEmitter:S,wormholeSequence:b,wormholeFeeCollector:M,clock:C,rent:w,systemProgram:v,wormholeProgram:new l(e),tokenProgram:W}}function Hn(t,e,n,r,i,a,o,c,d,f,y,S,b,M){const C=V(e,t).methods.transferWrappedWithPayload(f,y,s.dist.Buffer.from(S),b,s.dist.Buffer.from(M),null);return C._ixFn(...C._args,{accounts:Nt(e,n,r,i,a,o,c,d),signers:void 0,remainingAccounts:void 0,preInstructions:void 0,postInstructions:void 0})}function Nt(t,e,n,r,i,a,o,c,d){const f=fe(t,o,c),{wormholeBridge:y,wormholeMessage:S,wormholeEmitter:b,wormholeSequence:M,wormholeFeeCollector:C,clock:w,rent:v,systemProgram:I}=k.getPostMessageCpiAccounts(t,e,n,r);return{payer:new l(n),config:z(t),from:new l(i),fromOwner:new l(a),mint:f,wrappedMeta:ie(t,f),authoritySigner:le(t),wormholeBridge:y,wormholeMessage:S,wormholeEmitter:b,wormholeSequence:M,wormholeFeeCollector:C,clock:w,sender:new l(d===void 0?n:et(d)),rent:v,systemProgram:I,wormholeProgram:new l(e),tokenProgram:W}}function si(t,e,n){const{wormholeEmitter:r,wormholeBridge:i,wormholeFeeCollector:a,wormholeSequence:o}=k.getWormholeDerivedAccounts(e,n);return{tokenBridgeConfig:z(e),tokenBridgeAuthoritySigner:le(e),tokenBridgeCustodySigner:ke(e),tokenBridgeMintAuthority:ze(e),tokenBridgeSender:et(t),tokenBridgeRedeemer:tt(t),wormholeBridge:i,tokenBridgeEmitter:r,wormholeFeeCollector:a,tokenBridgeSequence:o}}function Gn(t,e,n,r,i,a,o){const c=_t(e,n,r,i,a,o,t);return{payer:c.payer,tokenBridgeConfig:c.config,fromTokenAccount:c.from,mint:c.mint,tokenBridgeCustody:c.custody,tokenBridgeAuthoritySigner:c.authoritySigner,tokenBridgeCustodySigner:c.custodySigner,wormholeBridge:c.wormholeBridge,wormholeMessage:c.wormholeMessage,tokenBridgeEmitter:c.wormholeEmitter,tokenBridgeSequence:c.wormholeSequence,wormholeFeeCollector:c.wormholeFeeCollector,clock:c.clock,tokenBridgeSender:c.sender,rent:c.rent,systemProgram:c.systemProgram,tokenProgram:c.tokenProgram,wormholeProgram:c.wormholeProgram}}function jn(t,e,n,r,i,a,o,c,d){const f=Nt(e,n,r,i,a,d===void 0?t:d,o,c,t);return{payer:f.payer,tokenBridgeConfig:f.config,fromTokenAccount:f.from,fromTokenAccountOwner:f.fromOwner,tokenBridgeWrappedMint:f.mint,tokenBridgeWrappedMeta:f.wrappedMeta,tokenBridgeAuthoritySigner:f.authoritySigner,wormholeBridge:f.wormholeBridge,wormholeMessage:f.wormholeMessage,tokenBridgeEmitter:f.wormholeEmitter,tokenBridgeSequence:f.wormholeSequence,wormholeFeeCollector:f.wormholeFeeCollector,clock:f.clock,tokenBridgeSender:f.sender,rent:f.rent,systemProgram:f.systemProgram,tokenProgram:f.tokenProgram,wormholeProgram:f.wormholeProgram}}function ii(t,e,n,r,i){const a=new l(r.payload.token.address.toUint8Array()),o=new l(r.payload.to.address.toUint8Array());return{payer:new l(n),tokenBridgeConfig:z(t),vaa:k.derivePostedVaaKey(e,s.dist.Buffer.from(r.hash)),tokenBridgeClaim:k.deriveClaimKey(t,r.emitterAddress.toUint8Array(),s.toChainId(r.emitterChain),r.sequence),tokenBridgeForeignEndpoint:de(t,s.toChainId(r.emitterChain),r.emitterAddress.toUint8Array()),toTokenAccount:new l(i),tokenBridgeRedeemer:tt(o),toFeesTokenAccount:new l(i),tokenBridgeCustody:Ue(t,a),mint:a,tokenBridgeCustodySigner:ke(t),rent:Z,systemProgram:K.programId,tokenProgram:W,wormholeProgram:new l(e)}}function ai(t,e,n,r,i){const a=fe(t,s.toChainId(r.payload.token.chain),r.payload.token.address.toUint8Array()),o=new l(r.payload.to.address.toUint8Array());return{payer:new l(n),tokenBridgeConfig:z(t),vaa:k.derivePostedVaaKey(e,s.dist.Buffer.from(r.hash)),tokenBridgeClaim:k.deriveClaimKey(t,r.emitterAddress.toUint8Array(),s.toChainId(r.emitterChain),r.sequence),tokenBridgeForeignEndpoint:de(t,s.toChainId(r.emitterChain),r.emitterAddress.toUint8Array()),toTokenAccount:new l(i),tokenBridgeRedeemer:tt(o),toFeesTokenAccount:new l(i),tokenBridgeWrappedMint:a,tokenBridgeWrappedMeta:ie(t,a),tokenBridgeMintAuthority:ze(t),rent:Z,systemProgram:K.programId,tokenProgram:W,wormholeProgram:new l(e)}}const Zn={version:"0.1.0",name:"token_bridge_relayer",constants:[{name:"SEED_PREFIX_BRIDGED",type:"bytes",value:"[98, 114, 105, 100, 103, 101, 100]"},{name:"SEED_PREFIX_TMP",type:"bytes",value:"[116, 109, 112]"},{name:"SWAP_RATE_PRECISION",type:"u32",value:"100_000_000"}],instructions:[{name:"initialize",docs:["This instruction is be used to generate your program's config.","And for convenience, we will store Wormhole-related PDAs in the","config so we can verify these accounts with a simple == constraint.","# Arguments","","* `ctx` - `Initialize` context","* `fee_recipient` - Recipient of all relayer fees and swap proceeds","* `assistant` - Privileged key to manage certain accounts"],accounts:[{name:"owner",isMut:!0,isSigner:!0,docs:["Deployer of the program."]},{name:"senderConfig",isMut:!0,isSigner:!1,docs:["Sender Config account, which saves program data useful for other","instructions, specifically for outbound transfers. Also saves the payer","of the [`initialize`](crate::initialize) instruction as the program's","owner."]},{name:"redeemerConfig",isMut:!0,isSigner:!1,docs:["Redeemer Config account, which saves program data useful for other","instructions, specifically for inbound transfers. Also saves the payer","of the [`initialize`](crate::initialize) instruction as the program's","owner."]},{name:"ownerConfig",isMut:!0,isSigner:!1,docs:["Owner config account, which saves the owner, assistant and","pending owner keys. This account is used to manage the ownership of the","program."]},{name:"tokenBridgeEmitter",isMut:!1,isSigner:!1,docs:["that holds data; it is purely just a signer for posting Wormhole","messages on behalf of the Token Bridge program."]},{name:"tokenBridgeSequence",isMut:!1,isSigner:!1,docs:["Token Bridge emitter's sequence account. Like with all Wormhole","emitters, this account keeps track of the sequence number of the last","posted message."]},{name:"systemProgram",isMut:!1,isSigner:!1,docs:["System program."]},{name:"programData",isMut:!0,isSigner:!1,docs:["upgrade authority. We check this PDA address just in case there is another program that this","deployer has deployed.","","NOTE: Set upgrade authority is scary because any public key can be used to set as the","authority."]},{name:"bpfLoaderUpgradeableProgram",isMut:!1,isSigner:!1}],args:[{name:"feeRecipient",type:"publicKey"},{name:"assistant",type:"publicKey"}]},{name:"registerForeignContract",docs:["This instruction registers a new foreign contract (from another","network) and saves the emitter information in a ForeignEmitter account.","This instruction is owner-only, meaning that only the owner of the","program (defined in the [Config] account) can add and update foreign","contracts.","","# Arguments","","* `ctx` - `RegisterForeignContract` context","* `chain` - Wormhole Chain ID","* `address` - Wormhole Emitter Address","* `relayer_fee` - Relayer fee scaled by the `relayer_fee_precision`"],accounts:[{name:"owner",isMut:!0,isSigner:!0,docs:["Owner of the program set in the [`SenderConfig`] account. Signer for","creating [`ForeignContract`] account."]},{name:"config",isMut:!1,isSigner:!1,docs:["Sender Config account. This program requires that the `owner` specified","in the context equals the pubkey specified in this account. Read-only."]},{name:"foreignContract",isMut:!0,isSigner:!1,docs:["Foreign Contract account. Create this account if an emitter has not been","registered yet for this Wormhole chain ID. If there already is a","contract address saved in this account, overwrite it."]},{name:"tokenBridgeForeignEndpoint",isMut:!1,isSigner:!1,docs:["Token Bridge foreign endpoint. This account should really be one","endpoint per chain, but Token Bridge's PDA allows for multiple","endpoints for each chain. We store the proper endpoint for the","emitter chain."]},{name:"tokenBridgeProgram",isMut:!1,isSigner:!1,docs:["Token Bridge program."]},{name:"systemProgram",isMut:!1,isSigner:!1,docs:["System program."]}],args:[{name:"chain",type:"u16"},{name:"address",type:{array:["u8",32]}},{name:"relayerFee",type:"u64"}]},{name:"registerToken",docs:["This instruction registers a new token and saves the initial `swap_rate`","and `max_native_token_amount` in a RegisteredToken account.","This instruction is owner-only, meaning that only the owner of the","program (defined in the [Config] account) can register a token.","","# Arguments","","* `ctx` - `RegisterToken` context","* `swap_rate`:","- USD conversion rate scaled by the `swap_rate_precision`. For example,","- if the conversion rate is $15 and the `swap_rate_precision` is","- 1000000, the `swap_rate` should be set to 15000000.","* `max_native_swap_amount`:","- Maximum amount of native tokens that can be swapped for this token","- on this chain."],accounts:[{name:"owner",isMut:!0,isSigner:!0,docs:["Owner of the program set in the [`SenderConfig`] account. Signer for","creating [`ForeignContract`] account."]},{name:"config",isMut:!1,isSigner:!1,docs:["Sender Config account. This program requires that the `owner` specified","in the context equals the pubkey specified in this account. Read-only."]},{name:"registeredToken",isMut:!0,isSigner:!1,docs:["Registered Token account. This account stores information about the","token, including the swap rate and max native swap amount. Create this","account if the mint has not been registered yet. Mutable."]},{name:"mint",isMut:!1,isSigner:!1,docs:["Mint info. This is the SPL token that will be bridged over to the","foreign contract."]},{name:"tokenProgram",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1,docs:["System program."]}],args:[{name:"swapRate",type:"u64"},{name:"maxNativeSwapAmount",type:"u64"}]},{name:"deregisterToken",docs:["This instruction deregisters a token by closing the existing","`RegisteredToken` account for a particular mint. This instruction is","owner-only, meaning that only the owner of the program (defined in the","[Config] account) can deregister a token."],accounts:[{name:"owner",isMut:!1,isSigner:!0,docs:["Owner of the program set in the [`SenderConfig`] account. Signer for","closing [`RegisteredToken`] account."]},{name:"config",isMut:!1,isSigner:!1,docs:["Sender Config account. This program requires that the `owner` specified","in the context equals the pubkey specified in this account. Read-only."]},{name:"mint",isMut:!1,isSigner:!1,docs:["Mint info. This is the SPL token that will be bridged over to the","foreign contract."]},{name:"registeredToken",isMut:!0,isSigner:!1,docs:["Registered Token account. This account stores information about the","token, including the swap rate and max native swap amount. This account","also determines if a mint is registered or not."]}],args:[]},{name:"updateRelayerFee",docs:["This instruction updates the `relayer_fee` in the `ForeignContract` account.","The `relayer_fee` is scaled by the `relayer_fee_precision`. For example,","if the `relayer_fee` is $15 and the `relayer_fee_precision` is 1000000,","the `relayer_fee` should be set to 15000000. This instruction can","only be called by the owner or assistant, which are defined in the","[OwnerConfig] account.","","# Arguments","","* `ctx` - `UpdateRelayerFee` context","* `chain` - Wormhole Chain ID","* `fee` - Relayer fee scaled by the `relayer_fee_precision`"],accounts:[{name:"payer",isMut:!0,isSigner:!0,docs:["Signer of the transaction. Must be the owner or assistant."]},{name:"ownerConfig",isMut:!1,isSigner:!1,docs:["The owner_config is used when updating the swap rate","so that the assistant key can be used in addition to the","owner key."]},{name:"foreignContract",isMut:!0,isSigner:!1,docs:["This account holds the USD denominated relayer fee for the specified","`chain`. This account is used to determine the cost of relaying","a transfer to a target chain. If there already is a relayer fee","saved in this account, overwrite it."]},{name:"systemProgram",isMut:!1,isSigner:!1,docs:["System program."]}],args:[{name:"chain",type:"u16"},{name:"fee",type:"u64"}]},{name:"updateRelayerFeePrecision",docs:["This instruction updates the `relayer_fee_precision` in the","`SenderConfig` and `RedeemerConfig` accounts. The `relayer_fee_precision`","is used to scale the `relayer_fee`. This instruction is owner-only,","meaning that only the owner of the program (defined in the [Config]","account) can register a token.","","# Arguments","","* `ctx` - `UpdatePrecision` context","* `relayer_fee_precision` - Precision used to scale the relayer fee."],accounts:[{name:"owner",isMut:!1,isSigner:!0,docs:["Owner of the program set in the [`RedeemerConfig`] and [`SenderConfig`] account."]},{name:"redeemerConfig",isMut:!0,isSigner:!1,docs:["Redeemer Config account. This program requires that the `owner`","specified in the context equals the pubkey specified in this account.","Mutable."]},{name:"senderConfig",isMut:!0,isSigner:!1,docs:["Sender Config account. This program requires that the `owner`","specified in the context equals the pubkey specified in this account.","Mutable. The `owner` check is redundant here, but we keep it as an","extra protection for future changes to the context. Mutable."]}],args:[{name:"relayerFeePrecision",type:"u32"}]},{name:"updateSwapRate",docs:["This instruction updates the `swap_rate` in the `RegisteredToken`","account. This instruction can only be called by the owner or","assistant, which are defined in the [OwnerConfig] account.","","# Arguments","","* `ctx` - `UpdateSwapRate` context","* `swap_rate` - USD conversion rate for the specified token."],accounts:[{name:"owner",isMut:!1,isSigner:!0,docs:["The signer of the transaction. Must be the owner or assistant."]},{name:"ownerConfig",isMut:!1,isSigner:!1,docs:["The owner_config is used when updating the swap rate so that the","assistant key can be used in additional to the owner key."]},{name:"registeredToken",isMut:!0,isSigner:!1,docs:["Registered Token account. This account stores information about the","token, including the swap rate and max native swap amount. The program","will modify this account to update the swap rate. Mutable."]},{name:"mint",isMut:!1,isSigner:!1,docs:["Mint info. This is the SPL token that will be bridged over to the","foreign contract."]}],args:[{name:"swapRate",type:"u64"}]},{name:"updateMaxNativeSwapAmount",docs:["This instruction updates the `max_native_swap_amount` in the","`RegisteredToken` account. This instruction is owner-only,","meaning that only the owner of the program (defined in the [Config]","account) can register a token.","","# Arguments","","* `ctx` - `UpdateMaxNativeSwapAmount` context","* `max_native_swap_amount`:","- Maximum amount of native tokens that can be swapped for this token","- on this chain."],accounts:[{name:"owner",isMut:!1,isSigner:!0,docs:["Owner of the program set in the [`SenderConfig`] account. Signer for","creating [`ForeignContract`] account."]},{name:"config",isMut:!1,isSigner:!1,docs:["Sender Config account. This program requires that the `owner` specified","in the context equals the pubkey specified in this account. Read-only."]},{name:"registeredToken",isMut:!0,isSigner:!1,docs:["Registered Token account. This account stores information about the","token, including the swap rate and max native swap amount. The program","will modify this account when the swap rate or max native swap amount","changes. Mutable."]},{name:"mint",isMut:!1,isSigner:!1,docs:["Mint info. This is the SPL token that will be bridged over to the","foreign contract."]}],args:[{name:"maxNativeSwapAmount",type:"u64"}]},{name:"setPauseForTransfers",docs:["This instruction updates the `paused` boolean in the `SenderConfig`","account. This instruction is owner-only, meaning that only the owner","of the program (defined in the [Config] account) can pause outbound","transfers.","","# Arguments","","* `ctx` - `PauseOutboundTransfers` context","* `paused` - Boolean indicating whether outbound transfers are paused."],accounts:[{name:"owner",isMut:!1,isSigner:!0,docs:["Owner of the program set in the [`SenderConfig`] account."]},{name:"config",isMut:!0,isSigner:!1,docs:["Sender Config account. This program requires that the `owner` specified","in the context equals the pubkey specified in this account. Mutable."]}],args:[{name:"paused",type:"bool"}]},{name:"submitOwnershipTransferRequest",docs:["This instruction sets the `pending_owner` field in the `OwnerConfig`","account. This instruction is owner-only, meaning that only the owner","of the program (defined in the [Config] account) can submit an","ownership transfer request.","","# Arguments","","* `ctx` - `ManageOwnership` context","* `new_owner` - Pubkey of the pending owner."],accounts:[{name:"owner",isMut:!1,isSigner:!0,docs:["Owner of the program set in the [`OwnerConfig`] account."]},{name:"ownerConfig",isMut:!0,isSigner:!1,docs:["Owner Config account. This program requires that the `owner` specified","in the context equals the pubkey specified in this account. Mutable."]}],args:[{name:"newOwner",type:"publicKey"}]},{name:"confirmOwnershipTransferRequest",docs:["This instruction confirms that the `pending_owner` is the signer of","the transaction and updates the `owner` field in the `SenderConfig`,","`RedeemerConfig`, and `OwnerConfig` accounts."],accounts:[{name:"pendingOwner",isMut:!1,isSigner:!0,docs:["Must be the pending owner of the program set in the [`OwnerConfig`]","account."]},{name:"ownerConfig",isMut:!0,isSigner:!1,docs:["Owner Config account. This program requires that the `pending_owner`","specified in the context equals the pubkey specified in this account."]},{name:"senderConfig",isMut:!0,isSigner:!1,docs:["Sender Config account. This instruction will update the `owner`","specified in this account to the `pending_owner` specified in the","[`OwnerConfig`] account. Mutable."]},{name:"redeemerConfig",isMut:!0,isSigner:!1,docs:["Redeemer Config account. This instruction will update the `owner`","specified in this account to the `pending_owner` specified in the","[`OwnerConfig`] account. Mutable."]}],args:[]},{name:"cancelOwnershipTransferRequest",docs:["This instruction cancels the ownership transfer request by setting","the `pending_owner` field in the `OwnerConfig` account to `None`.","This instruction is owner-only, meaning that only the owner of the","program (defined in the [Config] account) can cancel an ownership","transfer request."],accounts:[{name:"owner",isMut:!1,isSigner:!0,docs:["Owner of the program set in the [`OwnerConfig`] account."]},{name:"ownerConfig",isMut:!0,isSigner:!1,docs:["Owner Config account. This program requires that the `owner` specified","in the context equals the pubkey specified in this account. Mutable."]}],args:[]},{name:"updateAssistant",docs:["This instruction updates the `assistant` field in the `OwnerConfig`","account. This instruction is owner-only, meaning that only the owner","of the program (defined in the [Config] account) can update the","assistant.","","# Arguments","","* `ctx` - `ManageOwnership` context","* `new_assistant` - Pubkey of the new assistant."],accounts:[{name:"owner",isMut:!1,isSigner:!0,docs:["Owner of the program set in the [`OwnerConfig`] account."]},{name:"ownerConfig",isMut:!0,isSigner:!1,docs:["Owner Config account. This program requires that the `owner` specified","in the context equals the pubkey specified in this account. Mutable."]}],args:[{name:"newAssistant",type:"publicKey"}]},{name:"updateFeeRecipient",docs:["This instruction updates the `fee_recipient` field in the `RedeemerConfig`","account. This instruction is owner-only, meaning that only the owner","of the program (defined in the [Config] account) can update the","fee recipient.","","# Arguments","","* `ctx` - `UpdateFeeRecipient` context","* `new_fee_recipient` - Pubkey of the new fee recipient."],accounts:[{name:"owner",isMut:!1,isSigner:!0,docs:["Owner of the program set in the [`RedeemerConfig`] account."]},{name:"redeemerConfig",isMut:!0,isSigner:!1,docs:["Redeemer Config account, which saves program data useful for other","instructions, specifically for inbound transfers. Also saves the payer","of the [`initialize`](crate::initialize) instruction as the program's","owner."]}],args:[{name:"newFeeRecipient",type:"publicKey"}]},{name:"transferNativeTokensWithRelay",docs:["This instruction is used to transfer native tokens from Solana to a","foreign blockchain. The user can optionally specify a","`to_native_token_amount` to swap some of the tokens for the native","asset on the target chain. For a fee, an off-chain relayer will redeem","the transfer on the target chain. If the user is transferring native","SOL, the contract will automatically wrap the lamports into a WSOL.","","# Arguments","","* `ctx` - `TransferNativeWithRelay` context","* `amount` - Amount of tokens to send","* `to_native_token_amount`:","- Amount of tokens to swap for native assets on the target chain","* `recipient_chain` - Chain ID of the target chain","* `recipient_address` - Address of the target wallet on the target chain","* `batch_id` - Nonce of Wormhole message","* `wrap_native` - Whether to wrap native SOL"],accounts:[{name:"payer",isMut:!0,isSigner:!0,docs:["Payer will pay Wormhole fee to transfer tokens and create temporary","token account."]},{name:"payerSequence",isMut:!0,isSigner:!1,docs:["Used to keep track of payer's Wormhole sequence number."]},{name:"config",isMut:!1,isSigner:!1,docs:["Sender Config account. Acts as the signer for the Token Bridge token","transfer. Read-only."]},{name:"foreignContract",isMut:!1,isSigner:!1,docs:["Foreign Contract account. Send tokens to the contract specified in this","account. Funnily enough, the Token Bridge program does not have any","requirements for outbound transfers for the recipient chain to be","registered. This account provides extra protection against sending","tokens to an unregistered Wormhole chain ID. Read-only."]},{name:"mint",isMut:!0,isSigner:!1,docs:["Mint info. This is the SPL token that will be bridged over to the","foreign contract. Mutable."]},{name:"fromTokenAccount",isMut:!0,isSigner:!1,docs:["Payer's associated token account. We may want to make this a generic","token account in the future."]},{name:"registeredToken",isMut:!1,isSigner:!1},{name:"tmpTokenAccount",isMut:!0,isSigner:!1,docs:["Program's temporary token account. This account is created before the","instruction is invoked to temporarily take custody of the payer's","tokens. When the tokens are finally bridged out, the token account","will have zero balance and can be closed."]},{name:"tokenBridgeConfig",isMut:!1,isSigner:!1},{name:"tokenBridgeCustody",isMut:!0,isSigner:!1,docs:["account that holds this mint's balance. This account needs to be","unchecked because a token account may not have been created for this","mint yet. Mutable."]},{name:"tokenBridgeAuthoritySigner",isMut:!1,isSigner:!1},{name:"tokenBridgeCustodySigner",isMut:!1,isSigner:!1},{name:"wormholeBridge",isMut:!0,isSigner:!1},{name:"wormholeMessage",isMut:!0,isSigner:!1,docs:["tokens transferred in this account for our program. Mutable."]},{name:"tokenBridgeEmitter",isMut:!1,isSigner:!1},{name:"tokenBridgeSequence",isMut:!0,isSigner:!1},{name:"wormholeFeeCollector",isMut:!0,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1},{name:"tokenProgram",isMut:!1,isSigner:!1},{name:"wormholeProgram",isMut:!1,isSigner:!1},{name:"tokenBridgeProgram",isMut:!1,isSigner:!1},{name:"clock",isMut:!1,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1}],args:[{name:"amount",type:"u64"},{name:"toNativeTokenAmount",type:"u64"},{name:"recipientChain",type:"u16"},{name:"recipientAddress",type:{array:["u8",32]}},{name:"batchId",type:"u32"},{name:"wrapNative",type:"bool"}]},{name:"transferWrappedTokensWithRelay",docs:["This instruction is used to transfer wrapped tokens from Solana to a","foreign blockchain. The user can optionally specify a","`to_native_token_amount` to swap some of the tokens for the native","assets on the target chain. For a fee, an off-chain relayer will redeem","the transfer on the target chain. This instruction should only be called","when the user is transferring a wrapped token.","","# Arguments","","* `ctx` - `TransferWrappedWithRelay` context","* `amount` - Amount of tokens to send","* `to_native_token_amount`:","- Amount of tokens to swap for native assets on the target chain","* `recipient_chain` - Chain ID of the target chain","* `recipient_address` - Address of the target wallet on the target chain","* `batch_id` - Nonce of Wormhole message"],accounts:[{name:"payer",isMut:!0,isSigner:!0,docs:["Payer will pay Wormhole fee to transfer tokens."]},{name:"payerSequence",isMut:!0,isSigner:!1,docs:["Used to keep track of payer's Wormhole sequence number."]},{name:"config",isMut:!1,isSigner:!1,docs:["Sender Config account. Acts as the Token Bridge sender PDA. Mutable."]},{name:"foreignContract",isMut:!1,isSigner:!1,docs:["Foreign Contract account. Send tokens to the contract specified in this","account. Funnily enough, the Token Bridge program does not have any","requirements for outbound transfers for the recipient chain to be","registered. This account provides extra protection against sending","tokens to an unregistered Wormhole chain ID. Read-only."]},{name:"tokenBridgeWrappedMint",isMut:!0,isSigner:!1,docs:["Token Bridge wrapped mint info. This is the SPL token that will be","bridged to the foreign contract. The wrapped mint PDA must agree","with the native token's metadata. Mutable."]},{name:"fromTokenAccount",isMut:!0,isSigner:!1,docs:["Payer's associated token account. We may want to make this a generic","token account in the future."]},{name:"registeredToken",isMut:!1,isSigner:!1},{name:"tmpTokenAccount",isMut:!0,isSigner:!1,docs:["Program's temporary token account. This account is created before the","instruction is invoked to temporarily take custody of the payer's","tokens. When the tokens are finally bridged out, the token account","will have zero balance and can be closed."]},{name:"tokenBridgeWrappedMeta",isMut:!1,isSigner:!1,docs:["about the token from its native chain:","* Wormhole Chain ID","* Token's native contract address","* Token's native decimals"]},{name:"tokenBridgeConfig",isMut:!1,isSigner:!1},{name:"tokenBridgeAuthoritySigner",isMut:!1,isSigner:!1},{name:"wormholeBridge",isMut:!0,isSigner:!1},{name:"wormholeMessage",isMut:!0,isSigner:!1,docs:["tokens transferred in this account."]},{name:"tokenBridgeEmitter",isMut:!1,isSigner:!1},{name:"tokenBridgeSequence",isMut:!0,isSigner:!1},{name:"wormholeFeeCollector",isMut:!0,isSigner:!1},{name:"wormholeProgram",isMut:!1,isSigner:!1},{name:"tokenBridgeProgram",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1},{name:"tokenProgram",isMut:!1,isSigner:!1},{name:"clock",isMut:!1,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1}],args:[{name:"amount",type:"u64"},{name:"toNativeTokenAmount",type:"u64"},{name:"recipientChain",type:"u16"},{name:"recipientAddress",type:{array:["u8",32]}},{name:"batchId",type:"u32"}]},{name:"completeNativeTransferWithRelay",docs:["This instruction is used to redeem token transfers from foreign emitters.","It takes custody of the released native tokens and sends the tokens to the","encoded `recipient`. It pays the `fee_recipient` in the token","denomination. If requested by the user, it will perform a swap with the","off-chain relayer to provide the user with lamports. If the token","being transferred is WSOL, the contract will unwrap the WSOL and send","the lamports to the recipient and pay the relayer in lamports.","","# Arguments","","* `ctx` - `CompleteNativeWithRelay` context","* `vaa_hash` - Hash of the VAA that triggered the transfer"],accounts:[{name:"payer",isMut:!0,isSigner:!0,docs:["Payer will pay Wormhole fee to transfer tokens and create temporary","token account."]},{name:"config",isMut:!1,isSigner:!1,docs:["Redeemer Config account. Acts as the Token Bridge redeemer, which signs","for the complete transfer instruction. Read-only."]},{name:"feeRecipientTokenAccount",isMut:!0,isSigner:!1,docs:["Fee recipient's token account. Must be an associated token account. Mutable."]},{name:"foreignContract",isMut:!1,isSigner:!1,docs:["Foreign Contract account. The registered contract specified in this","account must agree with the target address for the Token Bridge's token","transfer. Read-only."]},{name:"mint",isMut:!1,isSigner:!1,docs:["Mint info. This is the SPL token that will be bridged over from the","foreign contract. This must match the token address specified in the","signed Wormhole message. Read-only."]},{name:"recipientTokenAccount",isMut:!0,isSigner:!1,docs:["Recipient associated token account. The recipient authority check","is necessary to ensure that the recipient is the intended recipient","of the bridged tokens. Mutable."]},{name:"recipient",isMut:!0,isSigner:!1,docs:["transaction. This instruction verifies that the recipient key","passed in this context matches the intended recipient in the vaa."]},{name:"registeredToken",isMut:!1,isSigner:!1},{name:"nativeRegisteredToken",isMut:!1,isSigner:!1},{name:"tmpTokenAccount",isMut:!0,isSigner:!1,docs:["Program's temporary token account. This account is created before the","instruction is invoked to temporarily take custody of the payer's","tokens. When the tokens are finally bridged in, the tokens will be","transferred to the destination token accounts. This account will have","zero balance and can be closed."]},{name:"tokenBridgeConfig",isMut:!1,isSigner:!1},{name:"vaa",isMut:!1,isSigner:!1,docs:["Verified Wormhole message account. The Wormhole program verified","signatures and posted the account data here. Read-only."]},{name:"tokenBridgeClaim",isMut:!0,isSigner:!1,docs:["is true if the bridged assets have been claimed. If the transfer has","not been redeemed, this account will not exist yet.","","NOTE: The Token Bridge program's claim account is only initialized when","a transfer is redeemed (and the boolean value `true` is written as","its data).","","The Token Bridge program will automatically fail if this transfer","is redeemed again. But we choose to short-circuit the failure as the","first evaluation of this instruction."]},{name:"tokenBridgeForeignEndpoint",isMut:!1,isSigner:!1,docs:["endpoint per chain, but the PDA allows for multiple endpoints for each","chain! We store the proper endpoint for the emitter chain."]},{name:"tokenBridgeCustody",isMut:!0,isSigner:!1,docs:["account that holds this mint's balance."]},{name:"tokenBridgeCustodySigner",isMut:!1,isSigner:!1},{name:"wormholeProgram",isMut:!1,isSigner:!1},{name:"tokenBridgeProgram",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1},{name:"tokenProgram",isMut:!1,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1}],args:[{name:"vaaHash",type:{array:["u8",32]}}]},{name:"completeWrappedTransferWithRelay",docs:["This instruction is used to redeem token transfers from foreign emitters.","It takes custody of the minted wrapped tokens and sends the tokens to the","encoded `recipient`. It pays the `fee_recipient` in the wrapped-token","denomination. If requested by the user, it will perform a swap with the","off-chain relayer to provide the user with lamports.","","# Arguments","","* `ctx` - `CompleteWrappedWithRelay` context","* `vaa_hash` - Hash of the VAA that triggered the transfer"],accounts:[{name:"payer",isMut:!0,isSigner:!0,docs:["Payer will pay Wormhole fee to transfer tokens and create temporary","token account."]},{name:"config",isMut:!1,isSigner:!1,docs:["Redeemer Config account. Acts as the Token Bridge redeemer, which signs","for the complete transfer instruction. Read-only."]},{name:"feeRecipientTokenAccount",isMut:!0,isSigner:!1,docs:["Fee recipient's token account. Must be an associated token account. Mutable."]},{name:"foreignContract",isMut:!1,isSigner:!1,docs:["Foreign Contract account. The registered contract specified in this","account must agree with the target address for the Token Bridge's token","transfer. Read-only."]},{name:"tokenBridgeWrappedMint",isMut:!0,isSigner:!1,docs:["Token Bridge wrapped mint info. This is the SPL token that will be","bridged from the foreign contract. The wrapped mint PDA must agree","with the native token's metadata in the wormhole message. Mutable."]},{name:"recipientTokenAccount",isMut:!0,isSigner:!1,docs:["Recipient associated token account. The recipient authority check","is necessary to ensure that the recipient is the intended recipient","of the bridged tokens. Mutable."]},{name:"recipient",isMut:!0,isSigner:!1,docs:["transaction. This instruction verifies that the recipient key","passed in this context matches the intended recipient in the vaa."]},{name:"registeredToken",isMut:!1,isSigner:!1},{name:"nativeRegisteredToken",isMut:!1,isSigner:!1},{name:"tmpTokenAccount",isMut:!0,isSigner:!1,docs:["Program's temporary token account. This account is created before the","instruction is invoked to temporarily take custody of the payer's","tokens. When the tokens are finally bridged in, the tokens will be","transferred to the destination token accounts. This account will have","zero balance and can be closed."]},{name:"tokenBridgeWrappedMeta",isMut:!1,isSigner:!1,docs:["about the token from its native chain:","* Wormhole Chain ID","* Token's native contract address","* Token's native decimals"]},{name:"tokenBridgeConfig",isMut:!1,isSigner:!1},{name:"vaa",isMut:!1,isSigner:!1,docs:["Verified Wormhole message account. The Wormhole program verified","signatures and posted the account data here. Read-only."]},{name:"tokenBridgeClaim",isMut:!0,isSigner:!1,docs:["is true if the bridged assets have been claimed. If the transfer has","not been redeemed, this account will not exist yet.","","NOTE: The Token Bridge program's claim account is only initialized when","a transfer is redeemed (and the boolean value `true` is written as","its data).","","The Token Bridge program will automatically fail if this transfer","is redeemed again. But we choose to short-circuit the failure as the","first evaluation of this instruction."]},{name:"tokenBridgeForeignEndpoint",isMut:!1,isSigner:!1,docs:["endpoint per chain, but the PDA allows for multiple endpoints for each","chain! We store the proper endpoint for the emitter chain."]},{name:"tokenBridgeMintAuthority",isMut:!1,isSigner:!1},{name:"wormholeProgram",isMut:!1,isSigner:!1},{name:"tokenBridgeProgram",isMut:!1,isSigner:!1},{name:"systemProgram",isMut:!1,isSigner:!1},{name:"tokenProgram",isMut:!1,isSigner:!1},{name:"rent",isMut:!1,isSigner:!1}],args:[{name:"vaaHash",type:{array:["u8",32]}}]}],accounts:[{name:"foreignContract",docs:["Foreign emitter account data."],type:{kind:"struct",fields:[{name:"chain",docs:["Emitter chain. Cannot equal `1` (Solana's Chain ID)."],type:"u16"},{name:"address",docs:["Emitter address. Cannot be zero address."],type:{array:["u8",32]}},{name:"tokenBridgeForeignEndpoint",docs:["Token Bridge program's foreign endpoint account key."],type:"publicKey"},{name:"fee",docs:["The fee that is paid to the `fee_recipient` upon redeeming a transfer.","This value is set in terms of USD and scaled by the `relayer_fee_precision`.","For example, if the `relayer_fee_precision` is `100000000` and the intended","fee is $5, then the `fee` value should be `500000000`."],type:"u64"}]}},{name:"ownerConfig",docs:["Owner account data."],type:{kind:"struct",fields:[{name:"owner",docs:["Program's owner."],type:"publicKey"},{name:"assistant",docs:["Program's assistant. Can be used to update the relayer fee and swap rate."],type:"publicKey"},{name:"pendingOwner",docs:["Intermediate storage for the pending owner. Is used to transfer ownership."],type:{option:"publicKey"}}]}},{name:"redeemerConfig",type:{kind:"struct",fields:[{name:"owner",docs:["Program's owner."],type:"publicKey"},{name:"bump",docs:["PDA bump."],type:"u8"},{name:"relayerFeePrecision",docs:["Relayer fee and swap rate precision."],type:"u32"},{name:"feeRecipient",docs:["Recipient of all relayer fees and swap proceeds."],type:"publicKey"}]}},{name:"registeredToken",docs:["Registered token account data."],type:{kind:"struct",fields:[{name:"swapRate",docs:["Token swap rate. The swap rate is the USD conversion rate of the token."],type:"u64"},{name:"maxNativeSwapAmount",docs:["Maximum amount of native SOL the contract will swap for each transfer."],type:"u64"}]}},{name:"senderConfig",type:{kind:"struct",fields:[{name:"owner",docs:["Program's owner."],type:"publicKey"},{name:"bump",docs:["PDA bump."],type:"u8"},{name:"tokenBridge",docs:["Token Bridge program's relevant addresses."],type:{defined:"OutboundTokenBridgeAddresses"}},{name:"relayerFeePrecision",docs:["Relayer fee and swap rate precision."],type:"u32"},{name:"paused",docs:["Boolean indicating whether outbound transfers are paused."],type:"bool"}]}},{name:"signerSequence",type:{kind:"struct",fields:[{name:"value",type:"u64"}]}}],types:[{name:"OutboundTokenBridgeAddresses",type:{kind:"struct",fields:[{name:"sequence",type:"publicKey"}]}},{name:"TokenBridgeRelayerMessage",docs:["Expected message types for this program. Only valid payloads are:","* `TransferWithRelay`: Payload ID == 1.","","Payload IDs are encoded as u8."],type:{kind:"enum",variants:[{name:"TransferWithRelay",fields:[{name:"target_relayer_fee",type:"u64"},{name:"to_native_token_amount",type:"u64"},{name:"recipient",type:{array:["u8",32]}}]}]}}],errors:[{code:6e3,name:"InvalidWormholeBridge",msg:"InvalidWormholeBridge"},{code:6001,name:"InvalidWormholeFeeCollector",msg:"InvalidWormholeFeeCollector"},{code:6002,name:"OwnerOnly",msg:"OwnerOnly"},{code:6003,name:"OutboundTransfersPaused",msg:"OutboundTransfersPaused"},{code:6004,name:"OwnerOrAssistantOnly",msg:"OwnerOrAssistantOnly"},{code:6005,name:"NotPendingOwner",msg:"NotPendingOwner"},{code:6006,name:"AlreadyTheOwner",msg:"AlreadyTheOwner"},{code:6007,name:"AlreadyTheAssistant",msg:"AlreadyTheAssistant"},{code:6008,name:"AlreadyTheFeeRecipient",msg:"AlreadyTheFeeRecipient"},{code:6009,name:"BumpNotFound",msg:"BumpNotFound"},{code:6010,name:"FailedToMakeImmutable",msg:"FailedToMakeImmutable"},{code:6011,name:"InvalidForeignContract",msg:"InvalidForeignContract"},{code:6012,name:"ZeroBridgeAmount",msg:"ZeroBridgeAmount"},{code:6013,name:"InvalidToNativeAmount",msg:"InvalidToNativeAmount"},{code:6014,name:"NativeMintRequired",msg:"NativeMintRequired"},{code:6015,name:"SwapsNotAllowedForNativeMint",msg:"SwapsNotAllowedForNativeMint"},{code:6016,name:"InvalidTokenBridgeConfig",msg:"InvalidTokenBridgeConfig"},{code:6017,name:"InvalidTokenBridgeAuthoritySigner",msg:"InvalidTokenBridgeAuthoritySigner"},{code:6018,name:"InvalidTokenBridgeCustodySigner",msg:"InvalidTokenBridgeCustodySigner"},{code:6019,name:"InvalidTokenBridgeEmitter",msg:"InvalidTokenBridgeEmitter"},{code:6020,name:"InvalidTokenBridgeSequence",msg:"InvalidTokenBridgeSequence"},{code:6021,name:"InvalidRecipient",msg:"InvalidRecipient"},{code:6022,name:"InvalidTransferToChain",msg:"InvalidTransferToChain"},{code:6023,name:"InvalidTransferTokenChain",msg:"InvalidTransferTokenChain"},{code:6024,name:"InvalidPrecision",msg:"InvalidPrecision"},{code:6025,name:"InvalidTransferToAddress",msg:"InvalidTransferToAddress"},{code:6026,name:"AlreadyRedeemed",msg:"AlreadyRedeemed"},{code:6027,name:"InvalidTokenBridgeForeignEndpoint",msg:"InvalidTokenBridgeForeignEndpoint"},{code:6028,name:"InvalidTokenBridgeMintAuthority",msg:"InvalidTokenBridgeMintAuthority"},{code:6029,name:"InvalidPublicKey",msg:"InvalidPublicKey"},{code:6030,name:"ZeroSwapRate",msg:"ZeroSwapRate"},{code:6031,name:"TokenNotRegistered",msg:"TokenNotRegistered"},{code:6032,name:"ChainNotRegistered",msg:"ChainNotRegistered"},{code:6033,name:"TokenAlreadyRegistered",msg:"TokenAlreadyRegistered"},{code:6034,name:"FeeCalculationError",msg:"TokenFeeCalculationError"},{code:6035,name:"InvalidSwapCalculation",msg:"InvalidSwapCalculation"},{code:6036,name:"InsufficientFunds",msg:"InsufficientFunds"}]};function st(t,e){return new s.Program(Zn,new l(t),{connection:e})}function Jn(t,e){return k.deriveAddress([s.dist.Buffer.from("seq"),new l(e).toBuffer()],t)}async function $n(t,e,n,r,i,a,o,c,d,f,y,S){const{methods:{transferNativeTokensWithRelay:b},account:{signerSequence:M}}=st(e,t),C=Jn(e,n),w=await M.fetch(C).then(({value:X})=>X).catch(X=>{var ae;if((ae=X.message)!=null&&ae.includes("Account does not exist"))return new s.BN(0);throw X}),v=Wt(e,n,w),I=Pt(new l(a),new l(n)),N=Et(e,a),Ae=Gn(e,r,i,n,v,I,a);return b(new s.BN(o.toString()),new s.BN(c.toString()),s.toChainId(f),[...d],y,S).accounts({config:Rt(e),payerSequence:C,foreignContract:$e(e,f),registeredToken:Ye(e,a),tmpTokenAccount:N,tokenBridgeProgram:new l(r),...Ae}).instruction()}async function Yn(t,e,n,r,i,a,o,c,d,f,y){const{methods:{transferWrappedTokensWithRelay:S},account:{signerSequence:b}}=st(e,t),M=Jn(e,n),C=await b.fetch(M).then(({value:ae})=>ae).catch(ae=>{var Kt;if((Kt=ae.message)!=null&&Kt.includes("Account does not exist"))return new s.BN(0);throw ae}),w=Wt(e,n,C),v=Pt(new l(a),new l(n)),{chain:I,tokenAddress:N}=await Pe(t,r,a),Ae=Et(e,a),X=jn(e,r,i,n,w,v,I,N);return S(new s.BN(o.toString()),new s.BN(c.toString()),s.toChainId(f),[...d],y).accounts({config:Rt(e),payerSequence:M,foreignContract:$e(e,f),registeredToken:Ye(e,new l(a)),tmpTokenAccount:Ae,tokenBridgeProgram:new l(r),...X}).instruction()}class it{constructor(e,n,r,i){T(this,"network");T(this,"chain");T(this,"connection");T(this,"contracts");T(this,"chainId");T(this,"coreBridge");T(this,"tokenBridge");this.network=e,this.chain=n,this.connection=r,this.contracts=i,this.chainId=s.toChainId(n);const a=i.tokenBridge;if(!a)throw new Error(`TokenBridge contract Address for chain ${n} not found`);this.tokenBridge=V(a,r),this.coreBridge=new k.SolanaWormholeCore(e,n,r,i)}static async fromRpc(e,n){const[r,i]=await P.SolanaPlatform.chainFromRpc(e),a=n[i];if(a.network!==r)throw new Error(`Network mismatch for chain ${i}: ${a.network} != ${r}`);return new it(r,i,e,a.contracts)}async isWrappedAsset(e){return Pe(this.connection,this.tokenBridge.programId,new P.SolanaAddress(e).toUint8Array()).catch(n=>null).then(n=>n!=null)}async getOriginalAsset(e){if(!await this.isWrappedAsset(e))throw s.ErrNotWrapped(e.toString());const n=new P.SolanaAddress(e).toUint8Array(),r=new l(n);try{const i=await Pe(this.connection,this.tokenBridge.programId,n);return i===null?{chain:this.chain,address:new P.SolanaAddress(r.toBytes()).toUniversalAddress()}:{chain:s.toChain(i.chain),address:new s.UniversalAddress(i.tokenAddress)}}catch{throw s.ErrNotWrapped(e.toString())}}async hasWrappedAsset(e){try{return await this.getWrappedAsset(e),!0}catch{}return!1}async getWrappedAsset(e){if(s.isNative(e.address))throw new Error("Native cannot be a wrapped asset");const n=fe(this.tokenBridge.programId,s.toChainId(e.chain),e.address.toUniversalAddress().toUint8Array());try{return await Pe(this.connection,this.tokenBridge.programId,n),s.toNative(this.chain,n.toBase58())}catch{}throw s.ErrNotWrapped(`${n}: ${e.address.toUniversalAddress().toString()}`)}async isTransferCompleted(e){return k.getClaim(this.connection,this.tokenBridge.programId,e.emitterAddress.toUint8Array(),s.toChainId(e.emitterChain),e.sequence,this.connection.commitment).catch(()=>!1)}async getWrappedNative(){return s.toNative(this.chain,te.toBase58())}async*createAttestation(e,n){if(!n)throw new Error("Payer required to create attestation");const r=new P.SolanaAddress(n).unwrap(),i=0,a=await this.coreBridge.getMessageFee(),o=k.createBridgeFeeTransferInstruction(this.coreBridge.coreBridge.programId,r,a),c=ne.generate(),d=xn(this.connection,this.tokenBridge.programId,this.coreBridge.address,r,new P.SolanaAddress(e).unwrap(),c.publicKey,i),f=new q().add(o,d);f.feePayer=r,yield this.createUnsignedTx({transaction:f,signers:[c]},"Solana.AttestToken")}async*submitAttestation(e,n){if(!n)throw new Error("Payer required to create attestation");const r=new P.SolanaAddress(n).unwrap();yield*this.coreBridge.postVaa(r,e);const i=new q().add(Un(this.connection,this.tokenBridge.programId,this.coreBridge.address,r,e));i.feePayer=r,yield this.createUnsignedTx({transaction:i},"Solana.CreateWrapped")}async transferSol(e,n,r,i){const a=new P.SolanaAddress(e).unwrap(),o=a,c=n.address.toUniversalAddress().toUint8Array(),d=s.toChainId(n.chain),f=0,y=0n,S=ne.generate(),b=ne.generate(),M=await jt(this.connection),C=K.createAccount({fromPubkey:o,newAccountPubkey:b.publicKey,lamports:M,space:j,programId:W}),w=K.transfer({fromPubkey:o,lamports:r,toPubkey:b.publicKey}),v=Qt(b.publicKey,te,o),I=ft(this.tokenBridge.programId,b.publicKey,o,r),N=i?pt(this.connection,this.tokenBridge.programId,this.coreBridge.address,a,S.publicKey,b.publicKey,te,f,r,c,d,i):mt(this.connection,this.tokenBridge.programId,this.coreBridge.address,a,S.publicKey,b.publicKey,te,f,r,y,c,d),Ae=Gt(b.publicKey,o,o),X=new q;return X.feePayer=o,X.add(C,w,v,I,N,Ae),this.createUnsignedTx({transaction:X,signers:[S,b]},"TokenBridge.TransferNative")}async*transfer(e,n,r,i,a){if(s.isNative(r)){yield await this.transferSol(e,n,i,a);return}const o=new P.SolanaAddress(r).unwrap(),c=new P.SolanaAddress(e).unwrap(),d=await Zt(o,c),f=n.address.toUniversalAddress().toUint8Array(),y=s.toChainId(n.chain),S=0,b=0n,M=!await this.isWrappedAsset(r),C=ne.generate();let w;if(M)w=a?pt(this.connection,this.tokenBridge.programId,this.coreBridge.address,c,C.publicKey,d,o,S,i,f,y,a):mt(this.connection,this.tokenBridge.programId,this.coreBridge.address,c,C.publicKey,d,o,S,i,b,f,y);else{const N=await this.getOriginalAsset(r);if(s.isNative(N.address))throw new Error("Native cannot be an original asset");w=a?Hn(this.connection,this.tokenBridge.programId,this.coreBridge.address,c,C.publicKey,d,c,s.toChainId(N.chain),N.address.toUint8Array(),S,i,f,y,a):Dn(this.connection,this.tokenBridge.programId,this.coreBridge.address,c,C.publicKey,d,c,s.toChainId(N.chain),N.address.toUint8Array(),S,i,b,f,y)}const v=ft(this.tokenBridge.programId,d,c,i),I=new q().add(v,w);I.feePayer=c,yield this.createUnsignedTx({transaction:I,signers:[C]},"TokenBridge.TransferTokens")}async*redeemAndUnwrap(e,n){const r=new P.SolanaAddress(e).unwrap(),i=new P.SolanaAddress(n.payload.to.address).unwrap(),a=await Qr(this.connection,te).then(C=>n.payload.token.amount*BigInt(Math.pow(10,C.decimals-8))),o=await jt(this.connection),c=ne.generate(),d=gt(this.connection,this.tokenBridge.programId,this.coreBridge.address,r,n),f=K.createAccount({fromPubkey:r,newAccountPubkey:c.publicKey,lamports:o,space:j,programId:W}),y=Qt(c.publicKey,te,r),S=_s(i,c.publicKey,r,a.valueOf()),b=Gt(c.publicKey,r,r),M=new q;M.feePayer=r,M.add(d,f,y,S,b),yield this.createUnsignedTx({transaction:M,signers:[c]},"TokenBridge.RedeemAndUnwrap")}async*createAta(e,n){const r=new P.SolanaAddress(e).unwrap(),i=new P.SolanaAddress(n).unwrap(),a=await Zt(i,r);if(await this.connection.getAccountInfo(a)===null){const c=new q().add(Bn(r,a,r,i));c.feePayer=r,yield this.createUnsignedTx({transaction:c},"Redeem.CreateATA")}}async*redeem(e,n,r=!0){const i=n.payload.token.chain===this.chain?n.payload.token.address:(await this.getWrappedAsset(n.payload.token)).toUniversalAddress();if(yield*this.createAta(e,i),yield*this.coreBridge.postVaa(e,n),r){const d=new P.SolanaAddress(await this.getWrappedNative());if(s.bytes.equals(i.toUint8Array(),d.toUint8Array())){yield*this.redeemAndUnwrap(e,n);return}}const a=new P.SolanaAddress(e).unwrap(),o=n.payload.token.chain==this.chain?gt:Nn,c=new q().add(o(this.connection,this.tokenBridge.programId,this.coreBridge.address,a,n));c.feePayer=a,yield this.createUnsignedTx({transaction:c},"Solana.RedeemTransfer")}createUnsignedTx(e,n,r=!1){return new P.SolanaUnsignedTransaction(e,this.network,this.chain,n,r)}}const oi={Testnet:["7VPWjBhCXrpYYBiRKZh1ubh9tLZZNkZGp2ReRphEV4Mc","3WK3mEDNPrNuQReBvM28NcsqrExMnPxD9pPJmgrUeKKH","BaGfF51MQ3a61papTRDYaNefBgTQ9ywnVne5fCff4bxT","ACbmcQxbbhiXWM1GmapUSMmBYKMvnFLfAAXKqdo8xKwo","GQtMXZxnuacCFTXVeTvyHi6P9F6chbtzhVc8JgD8hv7c","3Ftc5hTz9sG4huk79onufGiebJNDMZNL8HYgdMJ9E7JR","DMw2tLaq1bVoAEKtkoUtieSk9bfCPUvubYLatTMsSVop","84F2QX9278ToDmA98u4A86xSV9hz1ovazr8zwGaX6qjS","So11111111111111111111111111111111111111112","8987WGkYa5viiZ9DD8sS3PB5XghKmWjkEgmzvwDuoAEc","BJZ72CjPQojVoH68mzrd4VQ4nr6KuhbAGnhZEZCujKxY"],Mainnet:["7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs","A9mUU4qviSctJVPJdBJWkb28deg915LYJKrzQ19ji3FM","Dn4noZ5jgGfkntzcQSUZ8czkreiZ1ForXYoV2H8Dm7S1","3NZ9JMVBmGAqocybic2c7LQCJScmgsAZ6vQqTDzcqmJh","9gP2kCy3wA1ctvYWQk75guqXuHfrEomqydHLtcTCqiLa","Gz7VkD4MacbEB6yC5XD3HcumEiYx2EtDYYrfikGsvopG","KgV1GvrHQmRBY8sHQQeUKwTm2r2h8t4C8qt12Cw1HVE","DRQBDBEWmwWGK13fRTLhSPzjbvMSUavhV6nW4RUH8W6T","9kvAcwQbqejuJMd59mKuw2bfSsLRaQ7zuvaTVHEeBBec","7ixSaXGsHAFy34wogPk2YXiUX3BMmQMFdercdaHLnBby","G1vJEgzepqhnVu35BN4jrkv3wVwkujYWFFCxhbEZ1CZr","So11111111111111111111111111111111111111112"],Devnet:[]},he=9,Me=new s.BN(10),ge=new s.BN(1e8);class at{constructor(e,n,r,i){T(this,"network");T(this,"chain");T(this,"connection");T(this,"contracts");T(this,"chainId");T(this,"coreBridgeProgramId");T(this,"tokenBridgeProgramId");T(this,"tokenBridgeRelayer");this.network=e,this.chain=n,this.connection=r,this.contracts=i,this.chainId=s.toChainId(n);const a=i.tokenBridgeRelayer;if(!a)throw new Error(`TokenBridge contract Address for chain ${n} not found`);this.tokenBridgeRelayer=st(a,r),this.tokenBridgeProgramId=new l(i.tokenBridge),this.coreBridgeProgramId=new l(i.coreBridge)}static async fromRpc(e,n){const[r,i]=await P.SolanaPlatform.chainFromRpc(e),a=n[i];if(a.network!==r)throw new Error(`Network mismatch for chain ${i}: ${a.network} != ${r}`);return new at(r,i,e,a.contracts)}async*transfer(e,n,r,i,a){const c=new P.SolanaAddress(e).unwrap(),d=n.address.toUniversalAddress().toUint8Array(),f=this.mintAddress(r),y=new q;if(s.isNative(r)){const C=Pt(f,c);try{await $r(this.connection,C)}catch(w){if(w instanceof Ct){const v=Bn(c,C,c,f);y.add(v)}else throw w}}const S=a||0n,b=s.isNative(r),M=b?await $n(this.connection,this.tokenBridgeRelayer.programId,c,this.tokenBridgeProgramId,this.coreBridgeProgramId,f,i,S,d,n.chain,0,b):await Yn(this.connection,this.tokenBridgeRelayer.programId,c,this.tokenBridgeProgramId,this.coreBridgeProgramId,f,i,S,d,n.chain,0);y.add(M),y.feePayer=c,yield this.createUnsignedTx({transaction:y},"AutomaticTokenBridge.Transfer")}async*redeem(e,n){const r=new q;throw yield this.createUnsignedTx({transaction:r},"AutomaticTokenBridge.Redeem"),new Error("Method not implemented.")}async getRelayerFee(e,n){const r=this.mintAddress(n),[{fee:i},{swapRate:a},{relayerFeePrecision:o}]=await Promise.all([this.getForeignContract(e),this.getRegisteredToken(r),this.getRedeemerConfig()]),c=Number(await P.SolanaPlatform.getDecimals(this.chain,this.connection,n)),d=Me.pow(new s.BN(c)).mul(i).mul(ge).div(new s.BN(o).mul(a));return BigInt(d.toString())}async maxSwapAmount(e){const n=this.mintAddress(e),[{swapRate:r,maxNativeSwapAmount:i},{swapRate:a}]=await Promise.all([this.getRegisteredToken(n),this.getRegisteredToken(te)]),o=Number(await P.SolanaPlatform.getDecimals(this.chain,this.connection,e)),c=this.calculateNativeSwapRate(a,r),d=o>he?i.mul(c).mul(Me.pow(new s.BN(o-he))).div(ge):i.mul(c).div(Me.pow(new s.BN(he-o)).mul(ge));return BigInt(d.toString())}async nativeTokenAmount(e,n){if(n===0n)return 0n;const r=this.mintAddress(e),i=Number(await P.SolanaPlatform.getDecimals(this.chain,this.connection,e)),[{swapRate:a},{swapRate:o}]=await Promise.all([this.getRegisteredToken(r),this.getRegisteredToken(te)]),c=this.calculateNativeSwapRate(o,a),d=i>he?ge.mul(new s.BN(n.toString())).div(c.mul(Me.pow(new s.BN(i-he)))):ge.mul(new s.BN(n.toString())).mul(Me.pow(new s.BN(he-i))).div(c);return BigInt(d.toString())}async isRegisteredToken(e){var r;const n=this.mintAddress(e);try{return await this.getRegisteredToken(n),!0}catch(i){if((r=i.message)!=null&&r.includes("Account does not exist"))return!1;throw i}}mintAddress(e){return s.isNative(e)?new l(te):new P.SolanaAddress(e).unwrap()}async getRegisteredTokens(){return oi[this.network].map(e=>s.toNative(this.chain,e))}calculateNativeSwapRate(e,n){return ge.mul(e).div(n)}async getForeignContract(e){return await this.tokenBridgeRelayer.account.foreignContract.fetch($e(this.tokenBridgeRelayer.programId,e))}async getRegisteredToken(e){return await this.tokenBridgeRelayer.account.registeredToken.fetch(Ye(this.tokenBridgeRelayer.programId,e))}async getRedeemerConfig(){return await this.tokenBridgeRelayer.account.redeemerConfig.fetch(In(this.tokenBridgeRelayer.programId))}createUnsignedTx(e,n,r=!1){return new P.SolanaUnsignedTransaction(e,this.network,this.chain,n,r)}}tn.registerProtocol(P._platform,"TokenBridge",it);tn.registerProtocol(P._platform,"AutomaticTokenBridge",at);exports.CreateMetadataAccountArgs=xe;exports.Creator=re;exports.Data=Oe;exports.EndpointRegistration=Qe;exports.Metadata=rt;exports.SolanaAutomaticTokenBridge=at;exports.SolanaTokenBridge=it;exports.SplTokenMetadataProgram=we;exports.TOKEN_BRIDGE_IDL=xt;exports.TOKEN_BRIDGE_RELAYER_IDL=Zn;exports.TokenBridgeConfig=Xe;exports.WrappedMeta=nt;exports.coder=Wn;exports.createApproveAuthoritySignerInstruction=ft;exports.createAttestTokenInstruction=xn;exports.createCompleteTransferNativeInstruction=gt;exports.createCompleteTransferWrappedInstruction=Nn;exports.createCreateWrappedInstruction=Un;exports.createInitializeInstruction=ti;exports.createReadOnlyTokenBridgeProgramInterface=V;exports.createRegisterChainInstruction=ni;exports.createTokenBridgeProgramInterface=En;exports.createTokenBridgeRelayerProgramInterface=st;exports.createTransferNativeInstruction=mt;exports.createTransferNativeTokensWithRelayInstruction=$n;exports.createTransferNativeWithPayloadInstruction=pt;exports.createTransferWrappedInstruction=Dn;exports.createTransferWrappedTokensWithRelayInstruction=Yn;exports.createTransferWrappedWithPayloadInstruction=Hn;exports.createUpgradeContractInstruction=ri;exports.deriveAuthoritySignerKey=le;exports.deriveCustodyKey=Ue;exports.deriveCustodySignerKey=ke;exports.deriveEndpointKey=de;exports.deriveForeignContractAddress=$e;exports.deriveMintAuthorityKey=ze;exports.deriveRedeemerAccountKey=tt;exports.deriveRedeemerConfigAddress=In;exports.deriveRegisteredTokenAddress=Ye;exports.deriveSenderAccountKey=et;exports.deriveSenderConfigAddress=Rt;exports.deriveSplTokenMetadataKey=Fe;exports.deriveTmpTokenAccountAddress=Et;exports.deriveTokenBridgeConfigKey=z;exports.deriveTokenTransferMessageAddress=Wt;exports.deriveWrappedMetaKey=ie;exports.deriveWrappedMintKey=fe;exports.getAttestTokenAccounts=ht;exports.getCompleteTransferNativeAccounts=_n;exports.getCompleteTransferNativeWithPayloadCpiAccounts=ii;exports.getCompleteTransferWrappedAccounts=Kn;exports.getCompleteTransferWrappedWithPayloadCpiAccounts=ai;exports.getCreateWrappedAccounts=zn;exports.getEndpointRegistration=Ks;exports.getInitializeAccounts=On;exports.getMetadata=ei;exports.getRegisterChainAccounts=Fn;exports.getTokenBridgeConfig=Ns;exports.getTokenBridgeDerivedAccounts=si;exports.getTransferNativeAccounts=qn;exports.getTransferNativeWithPayloadAccounts=_t;exports.getTransferNativeWithPayloadCpiAccounts=Gn;exports.getTransferWrappedAccounts=Vn;exports.getTransferWrappedWithPayloadAccounts=Nt;exports.getTransferWrappedWithPayloadCpiAccounts=jn;exports.getUpgradeContractAccounts=Ln;exports.getWrappedMeta=Pe;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var U=Object.defineProperty;var R=(T,n,e)=>n in T?U(T,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):T[n]=e;var A=(T,n,e)=>(R(T,typeof n!="symbol"?n+"":n,e),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./index-BBtf8VGl.js"),t=require("./index-Tl7zYqHL.js"),c=require("./algorand-BDR3KPTJ.js"),q=require("./chain-BT07YJHt.js"),W=t.ABIMethod.fromSignature("portal_transfer(byte[])byte[]"),g=class g{constructor(n,e,r,s){A(this,"network");A(this,"chain");A(this,"connection");A(this,"contracts");A(this,"chainId");A(this,"coreBridge");A(this,"coreAppId");A(this,"coreAppAddress");A(this,"tokenBridgeAppId");A(this,"tokenBridgeAddress");if(this.network=n,this.chain=e,this.connection=r,this.contracts=s,this.chainId=t.toChainId(e),!s.coreBridge)throw new Error(`Core contract address for chain ${e} not found`);const i=BigInt(s.coreBridge);if(this.coreAppId=i,this.coreAppAddress=t.getApplicationAddress(i),this.coreBridge=new p.AlgorandWormholeCore(n,e,r,s),!s.tokenBridge)throw new Error(`TokenBridge contract address for chain ${e} not found`);const a=BigInt(s.tokenBridge);this.tokenBridgeAppId=a,this.tokenBridgeAddress=t.getApplicationAddress(a)}static async fromRpc(n,e){const[r,s]=await c.AlgorandPlatform.chainFromRpc(n),i=e[s];if(i.network!==r)throw new Error(`Network mismatch: ${i.network} != ${r}`);return new g(r,s,n,i.contracts)}async isWrappedAsset(n){const e=new c.AlgorandAddress(n).toInt();if(e===0)return!1;const r=await this.connection.getAssetByID(e).do(),i=t.Asset.from_obj_for_encoding(r).params.creator,a=await this.connection.accountInformation(i).exclude("all").do(),o=t.Account.from_obj_for_encoding(a);return(o==null?void 0:o.authAddr)===this.tokenBridgeAddress}async getOriginalAsset(n){const e=new c.AlgorandAddress(n).toInt(),r=await this.connection.getAssetByID(e).do(),s=t.Asset.from_obj_for_encoding(r),i=await p.StorageLogicSig.decodeLocalState(this.connection,this.tokenBridgeAppId,s.params.creator);if(i.length<94)throw new Error("Invalid local state data");const a=i.slice(92,94),o=t.toChain(t.bignum.decode(a)),l=new t.UniversalAddress(i.slice(60,92));return{chain:o,address:l}}async getWrappedAsset(n){const e=p.StorageLogicSig.forWrappedAsset(this.tokenBridgeAppId,n),r=await p.StorageLogicSig.decodeLocalState(this.connection,this.tokenBridgeAppId,e.address());if(r.length<8)throw new Error("Invalid wrapped asset data");return t.toNative(this.chain,t.bignum.decode(r.slice(0,8)).toString())}async hasWrappedAsset(n){try{return await this.getWrappedAsset(n),!0}catch{}return!1}async getWrappedNative(){return t.toNative(this.chain,"0")}async isTransferCompleted(n){const e=p.StorageLogicSig.forMessageId(this.tokenBridgeAppId,{sequence:n.sequence,chain:n.emitterChain,emitter:n.emitterAddress});try{return await p.StorageLogicSig.checkBitsSet(this.connection,this.tokenBridgeAppId,e.address(),n.sequence)}catch{}return!1}async*createAttestation(n,e){if(!e)throw new Error("Payer required to create attestation");const r=new c.AlgorandAddress(e).toString(),s=new c.AlgorandAddress(n).toInt(),i=[],a=await this.connection.getTransactionParams().do(),o=p.StorageLogicSig.forEmitter(this.coreAppId,new c.AlgorandAddress(this.tokenBridgeAddress).toUint8Array()),{accounts:[l],txs:x}=await p.AlgorandWormholeCore.maybeCreateStorageTx(this.connection,r,this.coreAppId,o,a);i.push(...x);let f="",d;if(s!==0){const I=await this.connection.getAssetByID(s).do(),S=t.Asset.from_obj_for_encoding(I),C=await this.connection.accountInformation(S.params.creator).do();if(d=t.Account.from_obj_for_encoding(C),d.authAddr===this.tokenBridgeAddress.toString())throw new Error("Cannot re-attest wormhole assets")}const w=p.StorageLogicSig.forNativeAsset(this.tokenBridgeAppId,BigInt(s)),k=await p.AlgorandWormholeCore.maybeCreateStorageTx(this.connection,r,this.tokenBridgeAppId,w);f=k.accounts[0],i.push(...k.txs);const u=t.makeApplicationCallTxnFromObject({from:r,appIndex:c.safeBigIntToNumber(this.tokenBridgeAppId),onComplete:t.OnApplicationComplete.NoOpOC,appArgs:[g.noop],suggestedParams:a});i.push({tx:u});const m=await this.coreBridge.getMessageFee();if(m>BigInt(0)){const I=t.makePaymentTxnWithSuggestedParamsFromObject({from:r,suggestedParams:a,to:this.tokenBridgeAddress,amount:m});i.push({tx:I})}let b=[l,f,this.coreAppAddress];d&&b.push(d.address);let h=t.makeApplicationCallTxnFromObject({appArgs:[g.attestToken,t.bignum.toBytes(s,8)],accounts:b,appIndex:c.safeBigIntToNumber(this.tokenBridgeAppId),foreignApps:[c.safeBigIntToNumber(this.coreAppId)],foreignAssets:[s],from:r,onComplete:t.OnApplicationComplete.NoOpOC,suggestedParams:a});m>BigInt(0)?h.fee*=3:h.fee*=2,i.push({tx:h});for(const I of i)yield this.createUnsignedTx(I,"TokenBridge.createAttestation",!0)}async*submitAttestation(n,e,r){if(!e)throw new Error("Sender required to submit attestation");r||(r=await this.connection.getTransactionParams().do());const s=e.toString(),a=p.StorageLogicSig.forWrappedAsset(this.tokenBridgeAppId,n.payload.token).address(),o=[],l=[],x=await p.StorageLogicSig.decodeLocalState(this.connection,this.tokenBridgeAppId,a);x.length>8&&l.push(new c.AlgorandAddress(x.slice(0,8)).toInt()),o.push({tx:t.makePaymentTxnWithSuggestedParamsFromObject({from:s,to:a,amount:1e5,suggestedParams:r})});let f=new Uint8Array(1);f[0]=1,o.push({tx:t.makeApplicationCallTxnFromObject({appArgs:[g.noop,f],appIndex:c.safeBigIntToNumber(this.tokenBridgeAppId),from:s,onComplete:t.OnApplicationComplete.NoOpOC,suggestedParams:r})}),f=new Uint8Array(1),f[0]=2,o.push({tx:t.makeApplicationCallTxnFromObject({appArgs:[g.noop,f],appIndex:c.safeBigIntToNumber(this.tokenBridgeAppId),from:s,onComplete:t.OnApplicationComplete.NoOpOC,suggestedParams:r})}),o.push({tx:t.makeApplicationCallTxnFromObject({accounts:[],appArgs:[g.receiveAttest,t.serialize(n)],appIndex:c.safeBigIntToNumber(this.tokenBridgeAppId),foreignAssets:l,from:s,onComplete:t.OnApplicationComplete.NoOpOC,suggestedParams:r})}),o[o.length-1].tx.fee=o[o.length-1].tx.fee*2;for(const d of o)yield this.createUnsignedTx(d,"TokenBridge.submitAttestation",!0)}async*transfer(n,e,r,s,i){const a=n.toString(),o=t.isNative(r)?0:new c.AlgorandAddress(r).toInt(),l=s,x=t.toChainId(e.chain),f=e.address.toUniversalAddress().toUint8Array(),d=await this.connection.getTransactionParams().do(),w=BigInt(0),k=p.StorageLogicSig.fromData({appId:this.coreAppId,appAddress:t.decodeAddress(this.coreAppAddress).publicKey,idx:BigInt(0),address:t.decodeAddress(this.tokenBridgeAddress).publicKey}),u=[],{accounts:[m],txs:b}=await p.AlgorandWormholeCore.maybeCreateStorageTx(this.connection,a,this.coreAppId,k,d);u.push(...b);let h="",I,S=!1;if(o!==0){const B=await this.connection.getAssetByID(o).do();h=t.Asset.from_obj_for_encoding(B).params.creator;const O=await this.connection.accountInformation(h).do();I=t.Account.from_obj_for_encoding(O),S=I.authAddr===this.tokenBridgeAddress.toString()}const C=await this.coreBridge.getMessageFee();if(C>0&&u.push({tx:t.makePaymentTxnWithSuggestedParamsFromObject({from:a,to:this.tokenBridgeAddress,amount:C,suggestedParams:d})}),!S){const B=p.StorageLogicSig.forNativeAsset(this.tokenBridgeAppId,BigInt(o)),{accounts:[y],txs:O}=await p.AlgorandWormholeCore.maybeCreateStorageTx(this.connection,a,this.tokenBridgeAppId,B,d);h=y,O.push(...O)}if(o!==0&&!await g.isOptedInToAsset(this.connection,h,o)){const B=t.makePaymentTxnWithSuggestedParamsFromObject({from:a,to:h,amount:1e5,suggestedParams:d});let y=t.makeApplicationCallTxnFromObject({from:a,appIndex:c.safeBigIntToNumber(this.tokenBridgeAppId),onComplete:t.OnApplicationComplete.NoOpOC,appArgs:[g.optIn,t.bigIntToBytes(o,8)],foreignAssets:[o],accounts:[h],suggestedParams:d});y.fee*=2,u.unshift({tx:B},{tx:y})}const P=t.makeApplicationCallTxnFromObject({from:a,appIndex:c.safeBigIntToNumber(this.tokenBridgeAppId),onComplete:t.OnApplicationComplete.NoOpOC,appArgs:[g.noop],suggestedParams:d});u.push({tx:P});let j=[];if(o===0){const B=t.makePaymentTxnWithSuggestedParamsFromObject({from:a,to:h,amount:l,suggestedParams:d});u.push({tx:B}),j=[m,h,h]}else{const B=t.makeAssetTransferTxnWithSuggestedParamsFromObject({from:a,to:h,amount:l,assetIndex:o,suggestedParams:d});u.push({tx:B}),j=I!=null&&I.address?[m,h,I.address]:[m,h]}const F=[g.sendTransfer,t.bignum.toBytes(o,8),t.bignum.toBytes(l,8),f,t.bignum.toBytes(x,8),t.bignum.toBytes(w,8)];i&&F.push(i);const L=t.makeApplicationCallTxnFromObject({from:a,appIndex:c.safeBigIntToNumber(this.tokenBridgeAppId),onComplete:t.OnApplicationComplete.NoOpOC,appArgs:F,foreignApps:[c.safeBigIntToNumber(this.coreAppId)],foreignAssets:[o],accounts:j,suggestedParams:d});L.fee*=2,u.push({tx:L});for(const B of u)yield this.createUnsignedTx(B,"TokenBridge.transfer",!0)}async*redeem(n,e,r=!0,s){s||(s=await this.connection.getTransactionParams().do());const i=new c.AlgorandAddress(n).toString(),{accounts:a,txs:o}=await p.AlgorandWormholeCore.submitVAAHeader(this.connection,this.coreAppId,this.tokenBridgeAppId,e,i);let l,x="",f=[],d=0;if(e.payload.token.chain!==this.chain){l=p.StorageLogicSig.forWrappedAsset(this.tokenBridgeAppId,e.payload.token),x=l.address();const m=await p.StorageLogicSig.decodeLocalState(this.connection,this.tokenBridgeAppId,x);d=new c.AlgorandAddress(m.slice(0,8)).toInt()}else{const m=new c.AlgorandAddress(e.payload.token.address).toBigInt();l=p.StorageLogicSig.forNativeAsset(this.tokenBridgeAppId,m),x=l.address(),d=c.safeBigIntToNumber(m)}a.push(x);let w=0,k="";if(e.payloadName==="TransferWithPayload"?(w=new c.AlgorandAddress(e.payload.to.address).toInt(),k=t.getApplicationAddress(w)):k=new c.AlgorandAddress(e.payload.to.address.toUint8Array()).toString(),a.push(k),d!==0&&(f.push(d),!await g.isOptedInToAsset(this.connection,k,d))){if(i!=k)throw new Error("Cannot ASA optin for somebody else (asset "+d.toString()+")");o.unshift({tx:t.makeAssetTransferTxnWithSuggestedParamsFromObject({amount:0,assetIndex:d,from:i,suggestedParams:s,to:i})})}const u={accounts:a,appArgs:[g.completeTransfer,t.serialize(e)],appIndex:c.safeBigIntToNumber(this.tokenBridgeAppId),foreignAssets:f,from:i,onComplete:t.OnApplicationComplete.NoOpOC,suggestedParams:s};o.push({tx:t.makeApplicationCallTxnFromObject(u)}),o[o.length-1].tx.fee=o[o.length-1].tx.fee*(e.payloadName==="Transfer"&&e.payload.fee!==void 0&&e.payload.fee===0n?2:3),e.payloadName==="TransferWithPayload"&&(o[o.length-1].tx.appForeignApps=[w],o.push({tx:t.makeApplicationCallTxnFromObject({appArgs:[W.getSelector(),W.args[0].type.encode(t.serialize(e))],appIndex:w,foreignAssets:f,from:i,onComplete:t.OnApplicationComplete.NoOpOC,suggestedParams:s})}));for(const m of o)yield this.createUnsignedTx(m,"TokenBridge.redeem",!0)}static async isOptedInToAsset(n,e,r){var s;try{const i=await n.accountAssetInformation(e,r).do();return(((s=t.AccountAssetResponse.from_obj_for_encoding(i).assetHolding)==null?void 0:s.amount)??0)>0}catch{}return!1}createUnsignedTx(n,e,r=!0){return new p.AlgorandUnsignedTransaction(n,this.network,this.chain,e,r)}};A(g,"sendTransfer",t.bytes.encode("sendTransfer")),A(g,"attestToken",t.bytes.encode("attestToken")),A(g,"noop",t.bytes.encode("nop")),A(g,"optIn",t.bytes.encode("optin")),A(g,"completeTransfer",t.bytes.encode("completeTransfer")),A(g,"receiveAttest",t.bytes.encode("receiveAttest"));let N=g;q.registerProtocol(c._platform,"TokenBridge",N);exports.AlgorandTokenBridge=N;exports.TransferMethodSelector=W;
|
|
1
|
+
"use strict";var U=Object.defineProperty;var R=(T,n,e)=>n in T?U(T,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):T[n]=e;var A=(T,n,e)=>(R(T,typeof n!="symbol"?n+"":n,e),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./index-CYRY8C8f.js"),t=require("./index-C1oy9Lkm.js"),c=require("./algorand-BizCMnCe.js"),q=require("./chain-BteoJHpg.js"),W=t.ABIMethod.fromSignature("portal_transfer(byte[])byte[]"),g=class g{constructor(n,e,r,s){A(this,"network");A(this,"chain");A(this,"connection");A(this,"contracts");A(this,"chainId");A(this,"coreBridge");A(this,"coreAppId");A(this,"coreAppAddress");A(this,"tokenBridgeAppId");A(this,"tokenBridgeAddress");if(this.network=n,this.chain=e,this.connection=r,this.contracts=s,this.chainId=t.toChainId(e),!s.coreBridge)throw new Error(`Core contract address for chain ${e} not found`);const i=BigInt(s.coreBridge);if(this.coreAppId=i,this.coreAppAddress=t.getApplicationAddress(i),this.coreBridge=new p.AlgorandWormholeCore(n,e,r,s),!s.tokenBridge)throw new Error(`TokenBridge contract address for chain ${e} not found`);const a=BigInt(s.tokenBridge);this.tokenBridgeAppId=a,this.tokenBridgeAddress=t.getApplicationAddress(a)}static async fromRpc(n,e){const[r,s]=await c.AlgorandPlatform.chainFromRpc(n),i=e[s];if(i.network!==r)throw new Error(`Network mismatch: ${i.network} != ${r}`);return new g(r,s,n,i.contracts)}async isWrappedAsset(n){const e=new c.AlgorandAddress(n).toInt();if(e===0)return!1;const r=await this.connection.getAssetByID(e).do(),i=t.Asset.from_obj_for_encoding(r).params.creator,a=await this.connection.accountInformation(i).exclude("all").do(),o=t.Account.from_obj_for_encoding(a);return(o==null?void 0:o.authAddr)===this.tokenBridgeAddress}async getOriginalAsset(n){const e=new c.AlgorandAddress(n).toInt(),r=await this.connection.getAssetByID(e).do(),s=t.Asset.from_obj_for_encoding(r),i=await p.StorageLogicSig.decodeLocalState(this.connection,this.tokenBridgeAppId,s.params.creator);if(i.length<94)throw new Error("Invalid local state data");const a=i.slice(92,94),o=t.toChain(t.bignum.decode(a)),l=new t.UniversalAddress(i.slice(60,92));return{chain:o,address:l}}async getWrappedAsset(n){const e=p.StorageLogicSig.forWrappedAsset(this.tokenBridgeAppId,n),r=await p.StorageLogicSig.decodeLocalState(this.connection,this.tokenBridgeAppId,e.address());if(r.length<8)throw new Error("Invalid wrapped asset data");return t.toNative(this.chain,t.bignum.decode(r.slice(0,8)).toString())}async hasWrappedAsset(n){try{return await this.getWrappedAsset(n),!0}catch{}return!1}async getWrappedNative(){return t.toNative(this.chain,"0")}async isTransferCompleted(n){const e=p.StorageLogicSig.forMessageId(this.tokenBridgeAppId,{sequence:n.sequence,chain:n.emitterChain,emitter:n.emitterAddress});try{return await p.StorageLogicSig.checkBitsSet(this.connection,this.tokenBridgeAppId,e.address(),n.sequence)}catch{}return!1}async*createAttestation(n,e){if(!e)throw new Error("Payer required to create attestation");const r=new c.AlgorandAddress(e).toString(),s=new c.AlgorandAddress(n).toInt(),i=[],a=await this.connection.getTransactionParams().do(),o=p.StorageLogicSig.forEmitter(this.coreAppId,new c.AlgorandAddress(this.tokenBridgeAddress).toUint8Array()),{accounts:[l],txs:x}=await p.AlgorandWormholeCore.maybeCreateStorageTx(this.connection,r,this.coreAppId,o,a);i.push(...x);let f="",d;if(s!==0){const I=await this.connection.getAssetByID(s).do(),S=t.Asset.from_obj_for_encoding(I),C=await this.connection.accountInformation(S.params.creator).do();if(d=t.Account.from_obj_for_encoding(C),d.authAddr===this.tokenBridgeAddress.toString())throw new Error("Cannot re-attest wormhole assets")}const w=p.StorageLogicSig.forNativeAsset(this.tokenBridgeAppId,BigInt(s)),k=await p.AlgorandWormholeCore.maybeCreateStorageTx(this.connection,r,this.tokenBridgeAppId,w);f=k.accounts[0],i.push(...k.txs);const u=t.makeApplicationCallTxnFromObject({from:r,appIndex:c.safeBigIntToNumber(this.tokenBridgeAppId),onComplete:t.OnApplicationComplete.NoOpOC,appArgs:[g.noop],suggestedParams:a});i.push({tx:u});const m=await this.coreBridge.getMessageFee();if(m>BigInt(0)){const I=t.makePaymentTxnWithSuggestedParamsFromObject({from:r,suggestedParams:a,to:this.tokenBridgeAddress,amount:m});i.push({tx:I})}let b=[l,f,this.coreAppAddress];d&&b.push(d.address);let h=t.makeApplicationCallTxnFromObject({appArgs:[g.attestToken,t.bignum.toBytes(s,8)],accounts:b,appIndex:c.safeBigIntToNumber(this.tokenBridgeAppId),foreignApps:[c.safeBigIntToNumber(this.coreAppId)],foreignAssets:[s],from:r,onComplete:t.OnApplicationComplete.NoOpOC,suggestedParams:a});m>BigInt(0)?h.fee*=3:h.fee*=2,i.push({tx:h});for(const I of i)yield this.createUnsignedTx(I,"TokenBridge.createAttestation",!0)}async*submitAttestation(n,e,r){if(!e)throw new Error("Sender required to submit attestation");r||(r=await this.connection.getTransactionParams().do());const s=e.toString(),a=p.StorageLogicSig.forWrappedAsset(this.tokenBridgeAppId,n.payload.token).address(),o=[],l=[],x=await p.StorageLogicSig.decodeLocalState(this.connection,this.tokenBridgeAppId,a);x.length>8&&l.push(new c.AlgorandAddress(x.slice(0,8)).toInt()),o.push({tx:t.makePaymentTxnWithSuggestedParamsFromObject({from:s,to:a,amount:1e5,suggestedParams:r})});let f=new Uint8Array(1);f[0]=1,o.push({tx:t.makeApplicationCallTxnFromObject({appArgs:[g.noop,f],appIndex:c.safeBigIntToNumber(this.tokenBridgeAppId),from:s,onComplete:t.OnApplicationComplete.NoOpOC,suggestedParams:r})}),f=new Uint8Array(1),f[0]=2,o.push({tx:t.makeApplicationCallTxnFromObject({appArgs:[g.noop,f],appIndex:c.safeBigIntToNumber(this.tokenBridgeAppId),from:s,onComplete:t.OnApplicationComplete.NoOpOC,suggestedParams:r})}),o.push({tx:t.makeApplicationCallTxnFromObject({accounts:[],appArgs:[g.receiveAttest,t.serialize(n)],appIndex:c.safeBigIntToNumber(this.tokenBridgeAppId),foreignAssets:l,from:s,onComplete:t.OnApplicationComplete.NoOpOC,suggestedParams:r})}),o[o.length-1].tx.fee=o[o.length-1].tx.fee*2;for(const d of o)yield this.createUnsignedTx(d,"TokenBridge.submitAttestation",!0)}async*transfer(n,e,r,s,i){const a=n.toString(),o=t.isNative(r)?0:new c.AlgorandAddress(r).toInt(),l=s,x=t.toChainId(e.chain),f=e.address.toUniversalAddress().toUint8Array(),d=await this.connection.getTransactionParams().do(),w=BigInt(0),k=p.StorageLogicSig.fromData({appId:this.coreAppId,appAddress:t.decodeAddress(this.coreAppAddress).publicKey,idx:BigInt(0),address:t.decodeAddress(this.tokenBridgeAddress).publicKey}),u=[],{accounts:[m],txs:b}=await p.AlgorandWormholeCore.maybeCreateStorageTx(this.connection,a,this.coreAppId,k,d);u.push(...b);let h="",I,S=!1;if(o!==0){const B=await this.connection.getAssetByID(o).do();h=t.Asset.from_obj_for_encoding(B).params.creator;const O=await this.connection.accountInformation(h).do();I=t.Account.from_obj_for_encoding(O),S=I.authAddr===this.tokenBridgeAddress.toString()}const C=await this.coreBridge.getMessageFee();if(C>0&&u.push({tx:t.makePaymentTxnWithSuggestedParamsFromObject({from:a,to:this.tokenBridgeAddress,amount:C,suggestedParams:d})}),!S){const B=p.StorageLogicSig.forNativeAsset(this.tokenBridgeAppId,BigInt(o)),{accounts:[y],txs:O}=await p.AlgorandWormholeCore.maybeCreateStorageTx(this.connection,a,this.tokenBridgeAppId,B,d);h=y,O.push(...O)}if(o!==0&&!await g.isOptedInToAsset(this.connection,h,o)){const B=t.makePaymentTxnWithSuggestedParamsFromObject({from:a,to:h,amount:1e5,suggestedParams:d});let y=t.makeApplicationCallTxnFromObject({from:a,appIndex:c.safeBigIntToNumber(this.tokenBridgeAppId),onComplete:t.OnApplicationComplete.NoOpOC,appArgs:[g.optIn,t.bigIntToBytes(o,8)],foreignAssets:[o],accounts:[h],suggestedParams:d});y.fee*=2,u.unshift({tx:B},{tx:y})}const P=t.makeApplicationCallTxnFromObject({from:a,appIndex:c.safeBigIntToNumber(this.tokenBridgeAppId),onComplete:t.OnApplicationComplete.NoOpOC,appArgs:[g.noop],suggestedParams:d});u.push({tx:P});let j=[];if(o===0){const B=t.makePaymentTxnWithSuggestedParamsFromObject({from:a,to:h,amount:l,suggestedParams:d});u.push({tx:B}),j=[m,h,h]}else{const B=t.makeAssetTransferTxnWithSuggestedParamsFromObject({from:a,to:h,amount:l,assetIndex:o,suggestedParams:d});u.push({tx:B}),j=I!=null&&I.address?[m,h,I.address]:[m,h]}const F=[g.sendTransfer,t.bignum.toBytes(o,8),t.bignum.toBytes(l,8),f,t.bignum.toBytes(x,8),t.bignum.toBytes(w,8)];i&&F.push(i);const L=t.makeApplicationCallTxnFromObject({from:a,appIndex:c.safeBigIntToNumber(this.tokenBridgeAppId),onComplete:t.OnApplicationComplete.NoOpOC,appArgs:F,foreignApps:[c.safeBigIntToNumber(this.coreAppId)],foreignAssets:[o],accounts:j,suggestedParams:d});L.fee*=2,u.push({tx:L});for(const B of u)yield this.createUnsignedTx(B,"TokenBridge.transfer",!0)}async*redeem(n,e,r=!0,s){s||(s=await this.connection.getTransactionParams().do());const i=new c.AlgorandAddress(n).toString(),{accounts:a,txs:o}=await p.AlgorandWormholeCore.submitVAAHeader(this.connection,this.coreAppId,this.tokenBridgeAppId,e,i);let l,x="",f=[],d=0;if(e.payload.token.chain!==this.chain){l=p.StorageLogicSig.forWrappedAsset(this.tokenBridgeAppId,e.payload.token),x=l.address();const m=await p.StorageLogicSig.decodeLocalState(this.connection,this.tokenBridgeAppId,x);d=new c.AlgorandAddress(m.slice(0,8)).toInt()}else{const m=new c.AlgorandAddress(e.payload.token.address).toBigInt();l=p.StorageLogicSig.forNativeAsset(this.tokenBridgeAppId,m),x=l.address(),d=c.safeBigIntToNumber(m)}a.push(x);let w=0,k="";if(e.payloadName==="TransferWithPayload"?(w=new c.AlgorandAddress(e.payload.to.address).toInt(),k=t.getApplicationAddress(w)):k=new c.AlgorandAddress(e.payload.to.address.toUint8Array()).toString(),a.push(k),d!==0&&(f.push(d),!await g.isOptedInToAsset(this.connection,k,d))){if(i!=k)throw new Error("Cannot ASA optin for somebody else (asset "+d.toString()+")");o.unshift({tx:t.makeAssetTransferTxnWithSuggestedParamsFromObject({amount:0,assetIndex:d,from:i,suggestedParams:s,to:i})})}const u={accounts:a,appArgs:[g.completeTransfer,t.serialize(e)],appIndex:c.safeBigIntToNumber(this.tokenBridgeAppId),foreignAssets:f,from:i,onComplete:t.OnApplicationComplete.NoOpOC,suggestedParams:s};o.push({tx:t.makeApplicationCallTxnFromObject(u)}),o[o.length-1].tx.fee=o[o.length-1].tx.fee*(e.payloadName==="Transfer"&&e.payload.fee!==void 0&&e.payload.fee===0n?2:3),e.payloadName==="TransferWithPayload"&&(o[o.length-1].tx.appForeignApps=[w],o.push({tx:t.makeApplicationCallTxnFromObject({appArgs:[W.getSelector(),W.args[0].type.encode(t.serialize(e))],appIndex:w,foreignAssets:f,from:i,onComplete:t.OnApplicationComplete.NoOpOC,suggestedParams:s})}));for(const m of o)yield this.createUnsignedTx(m,"TokenBridge.redeem",!0)}static async isOptedInToAsset(n,e,r){var s;try{const i=await n.accountAssetInformation(e,r).do();return(((s=t.AccountAssetResponse.from_obj_for_encoding(i).assetHolding)==null?void 0:s.amount)??0)>0}catch{}return!1}createUnsignedTx(n,e,r=!0){return new p.AlgorandUnsignedTransaction(n,this.network,this.chain,e,r)}};A(g,"sendTransfer",t.bytes.encode("sendTransfer")),A(g,"attestToken",t.bytes.encode("attestToken")),A(g,"noop",t.bytes.encode("nop")),A(g,"optIn",t.bytes.encode("optin")),A(g,"completeTransfer",t.bytes.encode("completeTransfer")),A(g,"receiveAttest",t.bytes.encode("receiveAttest"));let N=g;q.registerProtocol(c._platform,"TokenBridge",N);exports.AlgorandTokenBridge=N;exports.TransferMethodSelector=W;
|