@wormhole-foundation/wormhole-connect 2.5.0-beta.0-development → 2.5.0-beta.1-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.
Files changed (131) hide show
  1. package/dist/assets/{aptos-DvAOSqnD.js → aptos-Cepohe0c.js} +1 -1
  2. package/dist/assets/{aptos-t5JANz4b.js → aptos-DLxgkT5W.js} +3 -3
  3. package/dist/assets/{blake2b-CzqSqyTv.js → blake2b-BwI-z5NJ.js} +1 -1
  4. package/dist/assets/{ccip-4EBcfi6P.js → ccip-Bs93R44a.js} +1 -1
  5. package/dist/assets/{chunk-IMTC3J2M-Cms0K4gx.js → chunk-IMTC3J2M-CWE1FuDc.js} +1 -1
  6. package/dist/assets/{evm-8e-eySdo.js → evm-CuAzYJaD.js} +2 -2
  7. package/dist/assets/{evm-CYjbe4kH.js → evm-CxlqE7UV.js} +4 -4
  8. package/dist/assets/index-4BxLiF2M.js +1 -0
  9. package/dist/assets/{index-BcX-2q-J.js → index-4bNkfrlF.js} +1 -1
  10. package/dist/assets/{index-BKj7Inys.js → index-55oWJrMY.js} +1 -1
  11. package/dist/assets/{index-Ced_GF9G.js → index-6z4IDTS8.js} +1 -1
  12. package/dist/assets/{index-Dl17aI3S.js → index-8LfOenBd.js} +1 -1
  13. package/dist/assets/{index-DALVDBZq.js → index-BP8gdgNH.js} +1 -1
  14. package/dist/assets/{index-CSHmWPOV.js → index-C1f05Vbe.js} +1 -1
  15. package/dist/assets/{index-CwGBYrGm.js → index-CR4K0-mn.js} +1 -1
  16. package/dist/assets/index-CR_EuCZh.js +1 -0
  17. package/dist/assets/{index-CqA1lXp5.js → index-CZTnhsmR.js} +1 -1
  18. package/dist/assets/{index-C0rvraea.js → index-Cc4sWidw.js} +1 -1
  19. package/dist/assets/{index-D9U4BOHM.js → index-Cn7Zb7-T.js} +1 -1
  20. package/dist/assets/{index-DmaqQuhH.js → index-CyxmcHOs.js} +1 -1
  21. package/dist/assets/{index-Chd_bwGM.js → index-DizukMyh.js} +1 -1
  22. package/dist/assets/index-DyI3oKqt.js +1 -0
  23. package/dist/assets/{index-BgVVAYar.js → index-IzL7XNn3.js} +1 -1
  24. package/dist/assets/{index-SO_H3W5I.js → index-QjsZkUzh.js} +1 -1
  25. package/dist/assets/{index-CcMXeWAX.js → index-YqzS8F8M.js} +2 -2
  26. package/dist/assets/{index-M2j4uONF.js → index-e6M9UpWM.js} +1 -1
  27. package/dist/assets/{index-JtvUouOr.js → index-m0NseVbx.js} +1 -1
  28. package/dist/assets/{index.es-Bzsluoyw.js → index.es-BSz0aeDf.js} +1 -1
  29. package/dist/assets/{solana-BHeUantu.js → solana-Cl8jthtC.js} +2 -2
  30. package/dist/assets/solana-D2ghQqy6.js +2 -0
  31. package/dist/assets/{solanaEmbed.esm-B7A7qKmk.js → solanaEmbed.esm-LTv0oYB9.js} +1 -1
  32. package/dist/assets/{sui-CLrvrAHM.js → sui-Ck-FZzH_.js} +1 -1
  33. package/dist/assets/sui-Ko5G1-gz.js +2 -0
  34. package/dist/assets/unsignedTransaction-arVvzoJx.js +1 -0
  35. package/dist/main.js +62 -62
  36. package/dist/src/AppRouter.d.ts.map +1 -1
  37. package/dist/src/utils/coingecko.d.ts.map +1 -1
  38. package/lib/{aptos-D7X5GMcO.js → aptos-8KMeJE-o.js} +2 -2
  39. package/lib/{aptos-C3Ph4uY9.mjs → aptos-BbifmBP0.mjs} +5 -5
  40. package/lib/{aptos-Cs46Nns5.mjs → aptos-CKydVwjD.mjs} +2 -2
  41. package/lib/{aptos-By3qLiAP.js → aptos-DSqOSKNb.js} +1 -1
  42. package/lib/{base64-B-n8C-1n.js → base64-CpFecuyA.js} +1 -1
  43. package/lib/{base64-DxqKuhqD.mjs → base64-qaCqMb_l.mjs} +1 -1
  44. package/lib/{ccip-DgwbitdX.mjs → ccip-CVtTRfyn.mjs} +1 -1
  45. package/lib/{ccip-BoG9ZHRV.js → ccip-D51RTC0u.js} +1 -1
  46. package/lib/{chunk-IMTC3J2M-DfLEkM5Z.js → chunk-IMTC3J2M-BxB1b0q0.js} +1 -1
  47. package/lib/{chunk-IMTC3J2M-w136PyXJ.mjs → chunk-IMTC3J2M-CKg3oVWr.mjs} +3 -3
  48. package/lib/{evm-BwXOj4Er.js → evm-BLoyv9Lm.js} +3 -3
  49. package/lib/{evm--NPB9x1d.mjs → evm-CHVaneje.mjs} +5 -5
  50. package/lib/{evm-OXQXmbRf.mjs → evm-CQZ0vIa8.mjs} +6 -6
  51. package/lib/{evm-Bta1KBsb.js → evm-RNshiiFP.js} +2 -2
  52. package/lib/{index-Bpx_Rf1J.js → index-2z8NsIQ8.js} +1 -1
  53. package/lib/{index-1WX3nZoM.mjs → index-B2bLjM93.mjs} +3 -3
  54. package/lib/{index-BEHglvs0.js → index-B43BfOtT.js} +1 -1
  55. package/lib/{index-CKtZvS3X.mjs → index-BBanb5ap.mjs} +2 -2
  56. package/lib/{index-B3smMSuW.js → index-BKVRZX9z.js} +1 -1
  57. package/lib/{index-ByicGRKs.mjs → index-BK_P-oYC.mjs} +2 -2
  58. package/lib/{index-0m16n7L7.js → index-BOiSCkY4.js} +1 -1
  59. package/lib/{index-C2jvFfvC.js → index-BS2i3Ksw.js} +1 -1
  60. package/lib/index-BU-5OQwh.js +1 -0
  61. package/lib/{index-CksJcNrV.mjs → index-B_YK6ETC.mjs} +3 -3
  62. package/lib/{index-BXc3l4Br.mjs → index-BfTnUr7T.mjs} +2 -2
  63. package/lib/{index-m0543tB2.mjs → index-BoceUAkG.mjs} +20959 -32801
  64. package/lib/{index-CDwpyfnd.mjs → index-BuqYv7Vr.mjs} +2 -2
  65. package/lib/index-Bz1QpdKk.mjs +75 -0
  66. package/lib/{index-Bi6PAFR8.mjs → index-C1e-lwCm.mjs} +2 -2
  67. package/lib/{index-wsfzS6PN.js → index-C41PgJpW.js} +120 -120
  68. package/lib/{index-Cslbrg97.js → index-C4r2UzcB.js} +1 -1
  69. package/lib/{index-CWffCIQl.js → index-CO4tNP9_.js} +1 -1
  70. package/lib/{index-BLxoZ8qT.js → index-COs1joOZ.js} +1 -1
  71. package/lib/index-CbZQJETK.mjs +654 -0
  72. package/lib/{index-BGqNMVpQ.js → index-CkBBICIC.js} +1 -1
  73. package/lib/{index-C5tynAhb.mjs → index-Cnb3Fj6a.mjs} +1 -1
  74. package/lib/{index-NTAse-vE.js → index-CtC0u7hr.js} +1 -1
  75. package/lib/{index-cyTUScMF.js → index-CxoYsIft.js} +1 -1
  76. package/lib/index-D-0atbSn.js +1 -0
  77. package/lib/{index-bDliG7yg.mjs → index-D3vUo86P.mjs} +4 -4
  78. package/lib/index-D7jGbtAx.js +1 -0
  79. package/lib/{index-CoEGiDGu.js → index-D9urvMDV.js} +1 -1
  80. package/lib/{index-50mhIuON.mjs → index-DFk1H3Sj.mjs} +2 -2
  81. package/lib/{index-DPM7TGSv.mjs → index-DSsxt-9e.mjs} +11 -2
  82. package/lib/{index-CANn2DFq.mjs → index-DVVD_hZm.mjs} +1 -1
  83. package/lib/{index-CGbtcED2.mjs → index-Dep8pAGA.mjs} +2 -2
  84. package/lib/{index-PnMJX4OC.mjs → index-DlqDGm7R.mjs} +1 -1
  85. package/lib/{index-hFtbBndd.js → index-DrarHdDr.js} +1 -1
  86. package/lib/{index-FGc8swXY.mjs → index-DsN7YSP1.mjs} +1 -1
  87. package/lib/{index-CoX_24Ky.mjs → index-DszDWeYi.mjs} +1 -1
  88. package/lib/{index-MytorfyK.mjs → index-Dv60e2W9.mjs} +2 -2
  89. package/lib/index-Dwhn5PEn.mjs +191 -0
  90. package/lib/{index-zMaT9P4V.mjs → index-GVu1wMwM.mjs} +1 -1
  91. package/lib/{index-B5z5oFY1.js → index-MHSosKrJ.js} +1 -1
  92. package/lib/{index-DLiQpgMj.js → index-Y_57HCqM.js} +1 -1
  93. package/lib/{index-Dt0J9sau.js → index-j1N8J-Fe.js} +1 -1
  94. package/lib/{index-DSejRtdA.js → index-l9KU7K7P.js} +1 -1
  95. package/lib/{index-ILKgpNXM.js → index-myqdl1wW.js} +1 -1
  96. package/lib/{index-C86P0A0Y.mjs → index-xYxy17zb.mjs} +1 -1
  97. package/lib/{index-DlW1-aGm.js → index-zBPInGXF.js} +1 -1
  98. package/lib/{index.es-Bh1QXm67.mjs → index.es-Ba4xhwJc.mjs} +5 -5
  99. package/lib/{index.es-DIL345_I.js → index.es-W0q91zRy.js} +2 -2
  100. package/lib/index.js +1 -1
  101. package/lib/index.mjs +19 -19
  102. package/lib/{signer-Br2-fgMa.js → signer-BbJbZn8Y.js} +1 -1
  103. package/lib/{signer-CeNONJjb.mjs → signer-D0QgWaj3.mjs} +1 -1
  104. package/lib/solana-B4XQWl46.js +1 -0
  105. package/lib/solana-Dc2NjQX4.mjs +17 -0
  106. package/lib/{solana-C5lAA_Eh.mjs → solana-h6jJreZX.mjs} +4 -4
  107. package/lib/{solana-Bwwk-8HE.js → solana-vP3qaiqp.js} +1 -1
  108. package/lib/{solanaEmbed.esm-BMTrlSVI.js → solanaEmbed.esm-CQIYNDBD.js} +1 -1
  109. package/lib/{solanaEmbed.esm-_NPc8tZC.mjs → solanaEmbed.esm-auVokEYr.mjs} +1 -1
  110. package/lib/src/AppRouter.d.ts.map +1 -1
  111. package/lib/src/utils/coingecko.d.ts.map +1 -1
  112. package/lib/{sui-zLYQBpSC.js → sui-BCWyy1OH.js} +1 -1
  113. package/lib/sui-CCReavtD.mjs +585 -0
  114. package/lib/{sui-X62i5q3_.mjs → sui-CxwKTlzx.mjs} +1 -1
  115. package/lib/sui-EheQCqu3.js +1 -0
  116. package/package.json +17 -17
  117. package/dist/assets/index-BRtMY3at.js +0 -1
  118. package/dist/assets/index-BUlVFUMr.js +0 -1
  119. package/dist/assets/index-RBS_ALc7.js +0 -1
  120. package/dist/assets/solana-BEFCVrXa.js +0 -2
  121. package/dist/assets/sui-C1wbtvIC.js +0 -2
  122. package/lib/index-CNkTJOH_.js +0 -1
  123. package/lib/index-DN6dWOSB.js +0 -1
  124. package/lib/index-DUOnxuE_.mjs +0 -252
  125. package/lib/index-DqFY4i5u.js +0 -1
  126. package/lib/index-Eomc9IwB.mjs +0 -936
  127. package/lib/index-fkzogQYE.mjs +0 -376
  128. package/lib/solana-4Qcfxe9o.js +0 -1
  129. package/lib/solana-DM9nG3cQ.mjs +0 -17
  130. package/lib/sui-BvJu9wTN.mjs +0 -701
  131. package/lib/sui-pGBefbTJ.js +0 -1
@@ -1 +0,0 @@
1
- var j=Object.defineProperty;var B=(i,e,t)=>e in i?j(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var o=(i,e,t)=>B(i,typeof e!="symbol"?e+"":e,t);import{S as U,T}from"./sui-C1wbtvIC.js";import{cz as S,aM as g,dh as N,dr as A,aN as F,bp as R,aO as D,aQ as O,aR as z,aT as P,aU as C,aV as q,aX as L,dq as V,cu as W,cs as J,ct as y,cv as x,cn as Q}from"../main.js";import"./blake2b-CzqSqyTv.js";import"./index-DmaqQuhH.js";const I="::",E="0x2::sui::SUI",X=i=>/^(0x)?[0-9a-fA-F]+::\w+::\w+$/.test(i);function M(i){return i=i.startsWith("0x")?i.slice(2):i,i=i.length%2===0?i:"0"+i,`0x${i.length===64?i:g.encode(N.zpad(g.decode(i),32))}`}const h=class h{constructor(e){o(this,"address");o(this,"module");if(h.instanceof(e))this.address=e.address,this.module=e.module;else if(S.instanceof(e))this.address=e.toUint8Array();else if(typeof e=="string"){if(X(e)){const t=e.split(I);this.module=t.slice(1).join(I),e=t[0]}if(e=M(e),!g.valid(e))throw new Error("Invalid Sui address: "+e);this.address=g.decode(e)}else this.address=e}unwrap(){const e=this.getPackageId(),t=this.module?I+this.module:"";return`${e}${t}`}toString(){return this.unwrap()}toNative(){return this}toUint8Array(){return this.address}toUniversalAddress(){return new S(this.toUint8Array())}getPackageId(){return M(g.encode(this.address))}getCoinType(){if(this.module==="sui::SUI")return E;if(!this.module)throw new Error("No module present in Sui token address");return this.unwrap()}static instanceof(e){return e.constructor.platform===h.platform}equals(e){return h.instanceof(e)?e.unwrap()===this.unwrap():this.toUniversalAddress().equals(e)}};o(h,"byteSize",32),o(h,"platform","Sui");let f=h;A("Sui",f);class G{constructor(e,t,n,s,r=!1){o(this,"transaction");o(this,"network");o(this,"chain");o(this,"description");o(this,"parallelizable");this.transaction=e,this.network=t,this.chain=n,this.description=s,this.parallelizable=r}}class H extends F{}const _="Sui",K=i=>{var t;const e=(t=i.data)==null?void 0:t.content;return e&&e.dataType==="moveObject"?e.fields:null},Y=async(i,e)=>{if(!R(e))throw new Error(`Invalid object ID: ${e}`);const t=await i.getObject({id:e,options:{showContent:!0}});return K(t)},u=class u extends D{constructor(e,t){super(e,t??O(e,u._platform))}getRpc(e){if(e in this.config)return new U({url:this.config[e].rpc});throw new Error("No configuration available for chain: "+e)}getChain(e){if(e in this.config)return new H(e,this);throw new Error("No configuration available for chain: "+e)}static nativeTokenId(e,t){if(!u.isSupportedChain(t))throw new Error(`invalid chain for ${_}: ${t}`);return z.tokenId(t,E)}static isNativeTokenId(e,t,n){return!u.isSupportedChain(t)||n.chain!==t?!1:this.nativeTokenId(e,t)===n}static isSupportedChain(e){return P(e)===u._platform}static async getDecimals(e,t,n){if(C(n))return q(u._platform);const s=new f(n);try{const a=await Y(t,s.toString());if(a&&"decimals"in a)return a.decimals}catch{}const r=await t.getCoinMetadata({coinType:s.toString()});if(r===null)throw new Error(`Can't fetch decimals for token ${s.toString()}`);return r.decimals}static async getCoins(e,t,n){let s=[],r=null;const a=new f(t).toString();do{const c=await e.getCoins({owner:a,coinType:n,cursor:r});s=[...s,...c.data],r=c.hasNextPage?c.nextCursor:null}while(r);return s}static async getBalance(e,t,n,s){if(C(s)){const{totalBalance:a}=await t.getBalance({owner:n});return BigInt(a)}const{totalBalance:r}=await t.getBalance({owner:n,coinType:s.toString()});return BigInt(r)}static async getBalances(e,t,n,s){return(await Promise.all(s.map(async a=>{const c=await this.getBalance(e,t,n,a);return{[C(a)?"native":new f(a).toString()]:c}}))).reduce((a,c)=>Object.assign(a,c),{})}static async sendWait(e,t,n){const s=[];for(const r of n){const a=await t.executeTransactionBlock(r);await t.waitForTransaction({digest:a.digest}),s.push(a.digest)}return s}static async getLatestBlock(e){return Number(await e.getLatestCheckpointSequenceNumber())}static async getLatestFinalizedBlock(e){return this.getLatestBlock(e)}static chainFromChainId(e){const t=L(u._platform,e);if(t===void 0)throw new Error(`Unknown native chain id ${e}`);const[n,s]=t;return[n,s]}static async chainFromRpc(e){const t=await e.call("sui_getChainIdentifier",[]);return this.chainFromChainId(t)}};o(u,"_platform",_);let b=u;const Z=[["Testnet",{tokenMessengerState:"0x5252abd1137094ed1db3e0d75bc36abcd287aee4bc310f8e047727ef5682e7c2",messageTransmitterState:"0x98234bd0fa9ac12cc0a20a144a22e36d6a32f7e0a97baaeaf9c76cdc6d122d2e",usdcTreasury:"0x7170137d4a6431bf83351ac025baf462909bffe2877d87716374fb42b9629ebe"}],["Mainnet",{tokenMessengerState:"0x45993eecc0382f37419864992c12faee2238f5cfe22b98ad3bf455baf65c8a2f",messageTransmitterState:"0xf68268c3d9b1df3215f2439400c1c4ea08ac4ef4bb7d6f3ca6a2a239e17510af",usdcTreasury:"0x57d6725e7a8b49a7b2a612f6bd66ab5f39fc95332ca48be421c3229d514a6de7"}]],ee=V(Z,[0,1]);class k{constructor(e,t,n,s){o(this,"network");o(this,"chain");o(this,"provider");o(this,"contracts");o(this,"usdcId");o(this,"usdcTreasuryId");o(this,"tokenMessengerId");o(this,"tokenMessengerStateId");o(this,"messageTransmitterId");o(this,"messageTransmitterStateId");var m,l,p,w;if(this.network=e,this.chain=t,this.provider=n,this.contracts=s,e==="Devnet")throw new Error("CircleBridge not supported on Devnet");const r=W.get(this.network,this.chain);if(!r)throw new Error(`No USDC contract configured for network=${this.network} chain=${this.chain}`);const{tokenMessengerState:a,messageTransmitterState:c,usdcTreasury:d}=ee(e);if(!((m=s.cctp)!=null&&m.tokenMessenger))throw new Error(`Circle Token Messenger contract for domain ${t} not found`);if(!((l=s.cctp)!=null&&l.messageTransmitter))throw new Error(`Circle Message Transmitter contract for domain ${t} not found`);this.usdcId=r,this.usdcTreasuryId=d,this.tokenMessengerId=(p=s.cctp)==null?void 0:p.tokenMessenger,this.messageTransmitterId=(w=s.cctp)==null?void 0:w.messageTransmitter,this.tokenMessengerStateId=a,this.messageTransmitterStateId=c}async*transfer(e,t,n){const s=new T,r=J.get(this.network,t.chain),[a,...c]=await b.getCoins(this.provider,e,this.usdcId);if(a===void 0)throw new Error("No USDC in wallet");const d=s.object(a.coinObjectId);c.length>0&&s.mergeCoins(d,c.map(l=>s.object(l.coinObjectId)));const[m]=s.splitCoins(d,[n]);s.moveCall({target:`${this.tokenMessengerId}::deposit_for_burn::deposit_for_burn`,arguments:[m,s.pure.u32(r),s.pure.address(t.address.toUniversalAddress().toString()),s.object(this.tokenMessengerStateId),s.object(this.messageTransmitterStateId),s.object("0x403"),s.object(this.usdcTreasuryId)],typeArguments:[this.usdcId]}),yield this.createUnsignedTx(s,"Sui.CircleBridge.Transfer")}async isTransferCompleted(e){const t=new T;t.moveCall({target:`${this.messageTransmitterId}::state::is_nonce_used`,arguments:[t.object(this.messageTransmitterStateId),t.pure.u32(e.sourceDomain),t.pure.u64(e.nonce)]});const n=await this.provider.devInspectTransactionBlock({sender:"0x0000000000000000000000000000000000000000000000000000000000000000",transactionBlock:t});try{return!!n.results[0].returnValues[0][0][0]}catch(s){return console.error(`Error reading if nonce was used: ${s}`),!1}}async*redeem(e,t,n){const s=new T,[r]=s.moveCall({target:`${this.messageTransmitterId}::receive_message::receive_message`,arguments:[s.pure.vector("u8",y.serialize(t)),s.pure.vector("u8",g.decode(n)),s.object(this.messageTransmitterStateId)]});if(!r)throw new Error("Failed to produce receipt");const[a]=s.moveCall({target:`${this.tokenMessengerId}::handle_receive_message::handle_receive_message`,arguments:[r,s.object(this.tokenMessengerStateId),s.object("0x403"),s.object(this.usdcTreasuryId)],typeArguments:[this.usdcId]});if(!a)throw new Error("Failed to produce stamp receipt ticket with burn message");const[c]=s.moveCall({target:`${this.tokenMessengerId}::handle_receive_message::deconstruct_stamp_receipt_ticket_with_burn_message`,arguments:[a]});if(!c)throw new Error("Failed to produce stamp receipt ticket");const[d]=s.moveCall({target:`${this.messageTransmitterId}::receive_message::stamp_receipt`,arguments:[c,s.object(this.messageTransmitterStateId)],typeArguments:[`${this.tokenMessengerId}::message_transmitter_authenticator::MessageTransmitterAuthenticator`]});if(!d)throw new Error("Failed to produce stamped receipt");s.moveCall({target:`${this.messageTransmitterId}::receive_message::complete_receive_message`,arguments:[d,s.object(this.messageTransmitterStateId)]}),yield this.createUnsignedTx(s,"Sui.CircleBridge.Redeem")}async parseTransactionDetails(e){var v;const t=await this.provider.waitForTransaction({digest:e,options:{showEvents:!0,showEffects:!0,showInput:!0}});if(!t)throw new Error("Transaction not found");if(!t.events)throw new Error("Transaction events not found");const n=(v=t.events)==null?void 0:v.find($=>$.type.includes("send_message::MessageSent"));if(!n)throw new Error("No MessageSent event found");const s=new Uint8Array((n==null?void 0:n.parsedJson).message),[r,a]=y.deserialize(s),{payload:c}=r,d=c.messageSender,m=c.mintRecipient,l=x(this.network,r.sourceDomain),p=x(this.network,r.destinationDomain),w={chain:l,address:c.burnToken};return{from:{chain:l,address:d},to:{chain:p,address:m},token:w,amount:c.amount,message:r,id:{hash:a}}}static async fromRpc(e,t){const[n,s]=await b.chainFromRpc(e),r=t[s];if(r.network!==n)throw new Error(`Network mismatch: ${r.network} != ${n}`);return new k(n,s,e,r.contracts)}createUnsignedTx(e,t,n=!1){return new G(e,this.network,this.chain,t,n)}}Q("Sui","CircleBridge",k);export{k as SuiCircleBridge};
@@ -1 +0,0 @@
1
- var he=Object.defineProperty;var pe=(s,e,t)=>e in s?he(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var g=(s,e,t)=>pe(s,typeof e!="symbol"?e+"":e,t);import{T,S as we,a as O,b as q}from"./sui-C1wbtvIC.js";import{cz as z,aM as B,dh as ne,bm as ye,dr as me,aN as ke,bp as be,bl as oe,ds as ae,aO as Ie,aQ as je,aR as ve,aT as Ce,aU as v,aV as Te,aX as Be,cd as Ee,cy as J,ci as _e,cb as E,cf as Ae,cE as X,cB as Oe,cj as K,d4 as Y,dt as Se,cn as se}from"../main.js";import"./index-BRtMY3at.js";import"./blake2b-CzqSqyTv.js";import"./index-DmaqQuhH.js";const P="::",W="0x2::sui::SUI",R=s=>/^(0x)?[0-9a-fA-F]+::\w+::\w+$/.test(s),U=s=>s.replace(/(0x)(0*)/g,"0x");function Z(s){return s=s.startsWith("0x")?s.slice(2):s,s=s.length%2===0?s:"0"+s,`0x${s.length===64?s:B.encode(ne.zpad(B.decode(s),32))}`}const ee=s=>{const e=s.split(P);if(e.length!==3)throw new Error(`Invalid Sui type: ${s}`);return[ye(e[0]),e[1],e[2]].join(P)},$e=s=>new m(s).getCoinType(),ie=s=>new m(s).getPackageId(),ce=s=>{const e=U(s).match(/0x2::table::Table<(.*)>/);if(!e)throw new Error(`Invalid table type: ${s}`);if(e.length<2)throw new Error(`Invalid table type: ${s}`);const[t]=e[1].split(",");if(!t||!R(t))throw new Error(`Invalid key type: ${t}`);return t},S=class S{constructor(e){g(this,"address");g(this,"module");if(S.instanceof(e))this.address=e.address,this.module=e.module;else if(z.instanceof(e))this.address=e.toUint8Array();else if(typeof e=="string"){if(R(e)){const t=e.split(P);this.module=t.slice(1).join(P),e=t[0]}if(e=Z(e),!B.valid(e))throw new Error("Invalid Sui address: "+e);this.address=B.decode(e)}else this.address=e}unwrap(){const e=this.getPackageId(),t=this.module?P+this.module:"";return`${e}${t}`}toString(){return this.unwrap()}toNative(){return this}toUint8Array(){return this.address}toUniversalAddress(){return new z(this.toUint8Array())}getPackageId(){return Z(B.encode(this.address))}getCoinType(){if(this.module==="sui::SUI")return W;if(!this.module)throw new Error("No module present in Sui token address");return this.unwrap()}static instanceof(e){return e.constructor.platform===S.platform}equals(e){return S.instanceof(e)?e.unwrap()===this.unwrap():this.toUniversalAddress().equals(e)}};g(S,"byteSize",32),g(S,"platform","Sui");let m=S;me("Sui",m);class de{constructor(e,t,n,r,o=!1){g(this,"transaction");g(this,"network");g(this,"chain");g(this,"description");g(this,"parallelizable");this.transaction=e,this.network=t,this.chain=n,this.description=r,this.parallelizable=o}}class xe extends ke{}const te="Sui",N=s=>{var t;const e=(t=s.data)==null?void 0:t.content;return e&&e.dataType==="moveObject"?e.fields:null},le=(s,e)=>{try{return ee(s)===ee(e)}catch{return!1}},L=s=>(s==null?void 0:s.type)==="created",Ue=s=>(s==null?void 0:s.type)==="published";function Pe(s){return Array.isArray(s)}function b(s){return!Array.isArray(s)&&typeof s=="object"&&"fields"in s&&"type"in s}function F(s){return typeof s=="object"&&!Pe(s)&&!b(s)}function Fe(s){return typeof s=="object"&&"id"in s}const Re=async(s,e)=>{const{data:t,error:n}=await s.getObject({id:e,options:{showContent:!0}});if(n)throw new Error("Error getting object: "+n);if(!t||!b(t.content))throw new Error(`Cannot get oject for state id ${e}: `+t);return ie(t.content.type)},M=async(s,e)=>{if(!be(e))throw new Error(`Invalid object ID: ${e}`);const t=await s.getObject({id:e,options:{showContent:!0}});return N(t)},V=async(s,e)=>{let t,n;do{const i=await s.getDynamicFields({parentId:e,cursor:n});t=i.data.find(a=>a.name.type.endsWith("CurrentPackage")),n=i.hasNextPage?i.nextCursor:null}while(n&&!t);if(!t)throw new Error("CurrentPackage not found");const r=await s.getObject({id:t.objectId,options:{showContent:!0}}),o=N(r);if(!o||!F(o))throw new Error("Unable to get fields from object response");if(!("value"in o)||!b(o.value))throw new Error("Unable to get package id");return o.value.fields.package},Ne=async(s,e,t)=>{let n=null,r=null,o=null,i;do{if(o=await s.getOwnedObjects({owner:t,filter:{StructType:`${e}::emitter::EmitterCap`},options:{showContent:!0},cursor:i}),!o||!o.data)throw Error("Failed to get owned objects");for(const a of o.data){if(!a.data)continue;const{version:c,objectId:u}=a.data;(n===null||c<n)&&(n=c,r=u)}i=o.hasNextPage?o.nextCursor:void 0}while(i);return r},Me=async(s,e)=>{const t=new T,[n]=t.publish({modules:s.modules.map(r=>Array.from(ae.decode(r))),dependencies:s.dependencies.map(r=>oe(r))});return t.transferObjects([n],t.pure.address(e)),t},C=class C extends Ie{constructor(e,t){super(e,t??je(e,C._platform))}getRpc(e){if(e in this.config)return new we({url:this.config[e].rpc});throw new Error("No configuration available for chain: "+e)}getChain(e){if(e in this.config)return new xe(e,this);throw new Error("No configuration available for chain: "+e)}static nativeTokenId(e,t){if(!C.isSupportedChain(t))throw new Error(`invalid chain for ${te}: ${t}`);return ve.tokenId(t,W)}static isNativeTokenId(e,t,n){return!C.isSupportedChain(t)||n.chain!==t?!1:this.nativeTokenId(e,t)===n}static isSupportedChain(e){return Ce(e)===C._platform}static async getDecimals(e,t,n){if(v(n))return Te(C._platform);const r=new m(n);try{const i=await M(t,r.toString());if(i&&"decimals"in i)return i.decimals}catch{}const o=await t.getCoinMetadata({coinType:r.toString()});if(o===null)throw new Error(`Can't fetch decimals for token ${r.toString()}`);return o.decimals}static async getCoins(e,t,n){let r=[],o=null;const i=new m(t).toString();do{const a=await e.getCoins({owner:i,coinType:n,cursor:o});r=[...r,...a.data],o=a.hasNextPage?a.nextCursor:null}while(o);return r}static async getBalance(e,t,n,r){if(v(r)){const{totalBalance:i}=await t.getBalance({owner:n});return BigInt(i)}const{totalBalance:o}=await t.getBalance({owner:n,coinType:r.toString()});return BigInt(o)}static async getBalances(e,t,n,r){return(await Promise.all(r.map(async i=>{const a=await this.getBalance(e,t,n,i);return{[v(i)?"native":new m(i).toString()]:a}}))).reduce((i,a)=>Object.assign(i,a),{})}static async sendWait(e,t,n){const r=[];for(const o of n){const i=await t.executeTransactionBlock(o);await t.waitForTransaction({digest:i.digest}),r.push(i.digest)}return r}static async getLatestBlock(e){return Number(await e.getLatestCheckpointSequenceNumber())}static async getLatestFinalizedBlock(e){return this.getLatestBlock(e)}static chainFromChainId(e){const t=Be(C._platform,e);if(t===void 0)throw new Error(`Unknown native chain id ${e}`);const[n,r]=t;return[n,r]}static async chainFromRpc(e){const t=await e.call("sui_getChainIdentifier",[]);return this.chainFromChainId(t)}};g(C,"_platform",te);let I=C;const re=async(s,e,t)=>{var i,a,c;if(!R(t))throw new Error(`Invalid Sui type: ${t}`);const n=await M(s,e);if(!n)throw new Error(`Unable to fetch object fields from token bridge state. Object ID: ${e}`);const r=(a=(i=n.token_registry.fields)==null?void 0:i.id)==null?void 0:a.id;if(!r)throw new Error("Unable to fetch token registry object ID");const o=ie((c=n.token_registry)==null?void 0:c.type);if(!o)throw new Error("Unable to fetch token registry package ID");return s.getDynamicFieldObject({parentId:r,name:{type:`${o}::token_registry::Key<${t}>`,value:{dummy_field:!1}}})},D=async(s,e,t,n)=>{var d,h,p,y;const r=await M(s,e);if(!r)throw new Error("Unable to fetch object fields from token bridge state");const o=(h=(d=r.token_registry)==null?void 0:d.fields)==null?void 0:h.coin_types,i=(y=(p=o==null?void 0:o.fields)==null?void 0:p.id)==null?void 0:y.id;if(!i)throw new Error("Unable to fetch coin types");const a=ce(o==null?void 0:o.type);if(!a)throw new Error("Unable to get key type");const c=await s.getDynamicFieldObject({parentId:i,name:{type:a,value:{addr:[...t],chain:n}}});if(c.error){if(c.error.code==="dynamicFieldNotFound")return null;throw new Error(`Unexpected getDynamicFieldObject response ${c.error}`)}const u=N(c);if(!u)return null;if(!F(u))throw new Error("What?");return"value"in u?U(u.value):null};class H{constructor(e,t,n,r){g(this,"network");g(this,"chain");g(this,"provider");g(this,"contracts");g(this,"coreBridgeObjectId");g(this,"tokenBridgeObjectId");g(this,"chainId");this.network=e,this.chain=t,this.provider=n,this.contracts=r,this.chainId=Ee.get(e,t);const o=this.contracts.tokenBridge;if(!o)throw new Error(`Wormhole Token Bridge contract for domain ${t} not found`);const i=this.contracts.coreBridge;if(!i)throw new Error(`Wormhole Token Bridge contract for domain ${t} not found`);this.tokenBridgeObjectId=o,this.coreBridgeObjectId=i}static async fromRpc(e,t){const[n,r]=await I.chainFromRpc(e),o=t[r];if(o.network!==n)throw new Error(`Network mismatch: ${o.network} != ${n}`);return new H(n,r,e,o.contracts)}async isWrappedAsset(e){try{return await this.getOriginalAsset(e),!0}catch{return!1}}async getOriginalAsset(e){let t=e.getCoinType();if(!R(t))throw new Error(`Invalid Sui type: ${t}`);const n=await re(this.provider,this.tokenBridgeObjectId,t),r=N(n);if(!r)throw J(t);if(!F(r))throw new Error("Expected fields to be a MoveStruct");if(!("value"in r))throw new Error("Expected a `value` key in fields of MoveStruct");const o=r.value;if(!b(o))throw new Error("Expected fields to be a MoveStruct");const i=U(o.type);if(t=U(t),i.includes(`wrapped_asset::WrappedAsset<${t}>`)){const a=o.fields.info;if(!b(a))throw new Error("Expected fields to be a MoveStruct");const c=a.fields.token_address;if(!b(c))throw new Error("Expected fields to be a MoveStruct");if(!F(c.fields))throw new Error("Expected address data to be a MoveObject");if(!("value"in c.fields))throw new Error("Expected a `value` key in fields of MoveStruct");const u=c.fields.value;if(!b(u))throw new Error("Expected fields to be a MoveStruct");const d=new Uint8Array(u.fields.data);return{chain:_e(Number(a.fields.token_chain)),address:new z(d)}}throw J(t)}async getTokenUniversalAddress(e){let t=e.getCoinType();if(!R(t))throw new Error(`Invalid Sui type: ${t}`);const n=await re(this.provider,this.tokenBridgeObjectId,t),r=N(n);if(!r)throw new Error(`Token of type ${t} has not been registered with the token bridge. Has it been attested?`);if(!F(r))throw new Error("Expected fields to be a MoveStruct");if(!("value"in r))throw new Error("Expected a `value` key in fields of MoveStruct");const o=r.value;if(!b(o))throw new Error("Expected fields to be a MoveStruct");const i=U(o.type);if(t=U(t),i.includes(`native_asset::NativeAsset<${t}>`)){const a=o.fields.token_address;if(!b(a))throw new Error("Expected fields to be a MoveStruct");if(!("value"in a.fields))throw new Error("Expected a `value` key in fields of MoveStruct");const c=a.fields.value;if(!b(c))throw new Error("Expected fields to be a MoveStruct");const u=new Uint8Array(c.fields.data);return new z(u)}throw new Error(`Token of type ${t} is not a native asset`)}async getTokenNativeAddress(e,t){const n=await D(this.provider,this.tokenBridgeObjectId,t.toUint8Array(),E(e));if(!n)throw new Error(`Token ${t.toString()} not found in token registry`);return new m(n)}async hasWrappedAsset(e){try{return await this.getWrappedAsset(e),!0}catch{}return!1}async getWrappedAsset(e){if(v(e.address))throw new Error("Token Address required, 'native' literal not supported");const t=await D(this.provider,this.tokenBridgeObjectId,e.address.toUniversalAddress().toUint8Array(),E(e.chain));if(!t)throw J(Ae(e));return X(this.chain,t)}async isTransferCompleted(e){var a,c,u,d,h,p,y,k;const t=await M(this.provider,this.tokenBridgeObjectId);if(!t)throw new Error("Unable to fetch object fields from token bridge state");const n=(c=(a=t.consumed_vaas)==null?void 0:a.fields)==null?void 0:c.hashes,r=ce((d=(u=n==null?void 0:n.fields)==null?void 0:u.items)==null?void 0:d.type);if(!r)throw new Error("Unable to get key type");const o=(k=(y=(p=(h=n==null?void 0:n.fields)==null?void 0:h.items)==null?void 0:p.fields)==null?void 0:y.id)==null?void 0:k.id;if(!o)throw new Error("Unable to fetch consumed VAAs table");const i=await this.provider.getDynamicFieldObject({parentId:o,name:{type:r,value:{data:[...Oe(e.hash)]}}});if(!i.error)return!0;if(i.error.code==="dynamicFieldNotFound")return!1;throw new Error(`Unexpected getDynamicFieldObject response ${i.error}`)}async*createAttestation(e){const t=0n,r=e.toString(),o=await this.provider.getCoinMetadata({coinType:r});if(o===null||o.id===null)throw new Error(`Coin metadata ID for type ${r} not found`);const[i,a]=await this.getPackageIds(),c=new T,[u]=c.splitCoins(c.gas,[c.pure.u64(t)]),[d]=c.moveCall({target:`${a}::attest_token::attest_token`,arguments:[c.object(this.tokenBridgeObjectId),c.object(o.id),c.pure.u32(0)],typeArguments:[r]});c.moveCall({target:`${i}::publish_message::publish_message`,arguments:[c.object(this.coreBridgeObjectId),u,d,c.object(O)]}),yield this.createUnsignedTx(c,"Sui.TokenBridge.CreateAttestation")}async*submitAttestation(e,t){const[n,r]=await this.getPackageIds(),o=t.toString(),i=Math.min(e.payload.decimals,8),a=await this.getCoinBuildOutput(n,r,i),c=await Me(a,o);yield this.createUnsignedTx(c,"Sui.TokenBridge.PrepareCreateWrapped");let u="",d="",h="",p="",y="",k=!1;for(;!k;){await new Promise(w=>setTimeout(w,500));const _=await this.provider.queryTransactionBlocks({filter:{FromAddress:o},options:{showObjectChanges:!0},limit:3});for(const w of _.data)if("objectChanges"in w){for(const f of w.objectChanges)Ue(f)&&f.packageId!==void 0?u=f.packageId:L(f)&&f.objectType.includes("WrappedAssetSetup")?(d=f.objectId,y=f.objectType.split(", ")[1].replace(">","")):L(f)&&f.objectType.includes("UpgradeCap")?h=f.objectId:L(f)&&f.objectType.includes("CoinMetadata")&&(p=f.objectId);if(u!==""&&d!==""&&h!==""&&p!==""){k=!0;break}else u="",d="",h="",p=""}}const j=$e(u),l=new T,[$]=l.moveCall({target:`${n}::vaa::parse_and_verify`,arguments:[l.object(this.coreBridgeObjectId),l.pure.vector("u8",K(e)),l.object(O)]}),[x]=l.moveCall({target:`${r}::vaa::verify_only_once`,arguments:[l.object(this.tokenBridgeObjectId),$]});l.moveCall({target:`${r}::create_wrapped::complete_registration`,arguments:[l.object(this.tokenBridgeObjectId),l.object(p),l.object(d),l.object(h),x],typeArguments:[j,y]}),yield this.createUnsignedTx(l,"Sui.TokenBridge.SubmitAttestation")}async*transfer(e,t,n,r,o){const i=0n,a=0n,u=e.toString(),d=(v(n)?q:n).toString(),h=await I.getCoins(this.provider,e,d),[p,...y]=h.filter(w=>le(w.coinType,d));if(p===void 0)throw new Error(`Coins array doesn't contain any coins of type ${d}`);const[k,j]=await this.getPackageIds(),l=new T,[$]=(()=>{if(d===q)return l.splitCoins(l.gas,[l.pure.u64(r)]);{const w=l.object(p.coinObjectId);return y.length&&l.mergeCoins(w,y.map(f=>l.object(f.coinObjectId))),l.splitCoins(w,[l.pure.u64(r)])}})(),[x]=l.splitCoins(l.gas,[l.pure.u64(i)]),[_]=l.moveCall({target:`${j}::state::verified_asset`,arguments:[l.object(this.tokenBridgeObjectId)],typeArguments:[d]});if(o){if(!u)throw new Error("senderAddress is required for transfer with payload");let w=!1;const f=await(async()=>{const Q=await Ne(this.provider,k,u);if(Q!==null)return l.object(Q);{const[fe]=l.moveCall({target:`${k}::emitter::new`,arguments:[l.object(this.coreBridgeObjectId)]});return w=!0,fe}})(),[A,ue]=l.moveCall({target:`${j}::transfer_tokens_with_payload::prepare_transfer`,arguments:[f,_,$,l.pure.u16(E(t.chain)),l.pure.vector("u8",t.address.toUint8Array()),l.pure.vector("u8",o),l.pure.u32(0)],typeArguments:[d]});l.moveCall({target:`${j}::coin_utils::return_nonzero`,arguments:[ue],typeArguments:[d]});const[ge]=l.moveCall({target:`${j}::transfer_tokens_with_payload::transfer_tokens_with_payload`,arguments:[l.object(this.tokenBridgeObjectId),A],typeArguments:[d]});l.moveCall({target:`${k}::publish_message::publish_message`,arguments:[l.object(this.coreBridgeObjectId),x,ge,l.object(O)]}),w&&l.transferObjects([f],l.pure.address(u)),yield this.createUnsignedTx(l,"Sui.TokenBridge.TransferWithPayload")}else{const[w,f]=l.moveCall({target:`${j}::transfer_tokens::prepare_transfer`,arguments:[_,$,l.pure.u16(E(t.chain)),l.pure.vector("u8",t.address.toUint8Array()),l.pure.u64(a),l.pure.u32(0)],typeArguments:[d]});l.moveCall({target:`${j}::coin_utils::return_nonzero`,arguments:[f],typeArguments:[d]});const[A]=l.moveCall({target:`${j}::transfer_tokens::transfer_tokens`,arguments:[l.object(this.tokenBridgeObjectId),w],typeArguments:[d]});l.moveCall({target:`${k}::publish_message::publish_message`,arguments:[l.object(this.coreBridgeObjectId),x,A,l.object(O)]}),yield this.createUnsignedTx(l,"Sui.TokenBridge.Transfer")}}async*redeem(e,t,n=!0){const r=await D(this.provider,this.tokenBridgeObjectId,t.payload.token.address.toUint8Array(),E(t.payload.token.chain));if(!r)throw new Error("Unable to fetch token coinType");const[o,i]=await this.getPackageIds(),a=new T,[c]=a.moveCall({target:`${o}::vaa::parse_and_verify`,arguments:[a.object(this.coreBridgeObjectId),a.pure.vector("u8",K(t)),a.object(O)]}),[u]=a.moveCall({target:`${i}::vaa::verify_only_once`,arguments:[a.object(this.tokenBridgeObjectId),c]}),[d]=a.moveCall({target:`${i}::complete_transfer::authorize_transfer`,arguments:[a.object(this.tokenBridgeObjectId),u],typeArguments:[r]}),[h]=a.moveCall({target:`${i}::complete_transfer::redeem_relayer_payout`,arguments:[d],typeArguments:[r]});a.moveCall({target:`${i}::coin_utils::return_nonzero`,arguments:[h],typeArguments:[r]}),yield this.createUnsignedTx(a,"Sui.TokenBridge.Redeem")}async getWrappedNative(){return X(this.chain,q)}async getPackageIds(){return Promise.all([V(this.provider,this.coreBridgeObjectId),V(this.provider,this.tokenBridgeObjectId)])}async getCoinBuildOutput(e,t,n){var a;if(n>8)throw new Error("Decimals is capped at 8");const r=(a=await Re(this.provider,this.tokenBridgeObjectId))==null?void 0:a.replace("0x","");if(!r)throw new Error(`Original token bridge package ID not found for object ID ${this.tokenBridgeObjectId}`);const o="a11ceb0b060000000901000a020a14031e1704350405392d07669f01088502600ae502050cea02160004010b010c0205020d000002000201020003030c020001000104020700000700010001090801010c020a050600030803040202000302010702080007080100020800080303090002070801010b020209000901010608010105010b0202080008030209000504434f494e095478436f6e7465787408565f5f305f325f3011577261707065644173736574536574757004636f696e0e6372656174655f777261707065640b64756d6d795f6669656c6404696e697414707265706172655f726567697374726174696f6e0f7075626c69635f7472616e736665720673656e646572087472616e736665720a74785f636f6e746578740f76657273696f6e5f636f6e74726f6c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002"+r+"00020106010000000001090b0031"+n.toString(16).padStart(2,"0")+"0a0138000b012e110238010200";return{modules:[ae.encode(B.decode(o))],dependencies:["0x1","0x2",t,e].map(c=>oe(c))}}createUnsignedTx(e,t,n=!1){return new de(e,this.network,this.chain,t,n)}}class G{constructor(e,t,n,r){g(this,"network");g(this,"chain");g(this,"connection");g(this,"contracts");g(this,"tokenBridgeRelayerObjectId");g(this,"coreBridgeObjectId");g(this,"tokenBridgeObjectId");g(this,"fields");this.network=e,this.chain=t,this.connection=n,this.contracts=r;const{tokenBridge:o,tokenBridgeRelayer:i,coreBridge:a}=r;if(!o||!i||!a)throw new Error(`Some object IDs for ${t} Automatic Token Bridge not found`);this.tokenBridgeRelayerObjectId=i,this.tokenBridgeObjectId=o,this.coreBridgeObjectId=a}static async fromRpc(e,t){const[n,r]=await I.chainFromRpc(e),o=t[r];if(o.network!==n)throw new Error(`Network mismatch for chain ${r}: ${o.network} != ${n}`);return new G(n,r,e,o.contracts)}async*transfer(e,t,n,r,o){const a=new m(v(n)?I.nativeTokenId(this.network,this.chain).address:n).getCoinType(),{coreBridge:c,tokenBridge:u}=await this.getPackageIds(),d=new T,h=BigInt(0),[p]=d.splitCoins(d.gas,[d.pure.u64(h)]),[y]=await(async()=>{if(v(n))return d.splitCoins(d.gas,[d.pure.u64(r)]);{const x=await I.getCoins(this.connection,e,a),[_,...w]=x.filter(A=>A.coinType===a);if(_===void 0)throw new Error(`Coins array doesn't contain any coins of type ${a}`);const f=d.object(_.coinObjectId);return w.length&&d.mergeCoins(f,w.map(A=>d.object(A.coinObjectId))),d.splitCoins(f,[d.pure.u64(r)])}})(),[k]=d.moveCall({target:`${u}::state::verified_asset`,arguments:[d.object(this.tokenBridgeObjectId)],typeArguments:[a]}),j=await this.getPackageId(),[l]=d.moveCall({target:`${j}::transfer::transfer_tokens_with_relay`,arguments:[d.object(this.tokenBridgeRelayerObjectId),y,k,d.pure.u64(o??0n),d.pure.u16(E(t.chain)),d.pure.address(B.encode(t.address.toUint8Array(),!0)),d.pure.u32(123)],typeArguments:[a]}),[$]=d.moveCall({target:`${u}::transfer_tokens_with_payload::transfer_tokens_with_payload`,arguments:[d.object(this.tokenBridgeObjectId),l],typeArguments:[a]});d.moveCall({target:`${c}::publish_message::publish_message`,arguments:[d.object(this.coreBridgeObjectId),p,$,d.object(O)]}),yield this.createUnsignedTx(d,"AutomaticTokenBridge.transfer")}async*redeem(e,t){const{coreBridge:n,tokenBridge:r}=await this.getPackageIds(),{address:o,chain:i}=t.payload.token,a=await D(this.connection,this.tokenBridgeObjectId,o.toUniversalAddress().toUint8Array(),E(i));if(!a)throw new Error("Unable to fetch token coinType");const c=new T,[u]=c.moveCall({target:`${n}::vaa::parse_and_verify`,arguments:[c.object(this.coreBridgeObjectId),c.pure.vector("u8",K(t)),c.object(O)]}),[d]=c.moveCall({target:`${r}::vaa::verify_only_once`,arguments:[c.object(this.tokenBridgeObjectId),u]}),[h]=c.moveCall({target:`${r}::complete_transfer_with_payload::authorize_transfer`,arguments:[c.object(this.tokenBridgeObjectId),d],typeArguments:[a]}),p=await this.getPackageId();c.moveCall({target:`${p}::redeem::complete_transfer`,arguments:[c.object(this.tokenBridgeRelayerObjectId),h],typeArguments:[a]}),yield this.createUnsignedTx(c,"AutomaticTokenBridge.redeem")}async getRelayerFee(e,t){const n=v(t)?I.nativeTokenId(this.network,this.chain):t,r=await this.getTokenInfo(n.toString());if(r===null)throw new Error("Unsupported token for relay");const o=await this.getFields(),i=await this.connection.getDynamicFieldObject({parentId:this.tokenBridgeRelayerObjectId,name:{type:"vector<u8>",value:Array.from(ne.encode("relayer_fees"))}});if(!i.data||!i.data.content)throw i.error?new Error("Failed to get relayer fees: "+JSON.stringify(i.error)):new Error("Unable to compute relayer fee");const{content:a}=i.data;if(!b(a)||!Fe(a.fields.id))throw new Error("Unable to compute relayer fee");const c=await this.connection.getDynamicFieldObject({parentId:a.fields.id.id,name:{type:"u16",value:E(e)}});if(!c.data||!c.data.content)throw c.error?new Error("Failed to get relayer fees: "+JSON.stringify(i.error)):new Error("Unable to compute relayer fee");const{content:u}=c.data;if(!b(u))throw new Error("Unable to compute relayer fee");const d=await I.getDecimals(this.chain,this.connection,t.toString()),h=r.swap_rate,p=o.relayer_fee_precision,y=o.swap_rate_precision,k=u.fields.value;return 10n**BigInt(d)*BigInt(k)*BigInt(y)/(BigInt(h)*BigInt(p))}async maxSwapAmount(e){var c,u;const n=(v(e)?I.nativeTokenId(this.network,this.chain):e).toString(),r=await this.connection.getCoinMetadata({coinType:n});if(!r)throw new Error("metadata is null");const o=await this.getPackageId(),i=new T;i.moveCall({target:`${o}::redeem::calculate_max_swap_amount_in`,arguments:[i.object(this.tokenBridgeRelayerObjectId),i.pure.u8(r.decimals)],typeArguments:[n]});const a=await this.connection.devInspectTransactionBlock({transactionBlock:i,sender:B.encode(new Uint8Array(32))});if(!a.results||a.results.length==0||!((c=a.results[0])!=null&&c.returnValues)||((u=a.results[0])==null?void 0:u.returnValues.length)!==1)throw Error("swap rate not set");return Y.decode(new Uint8Array(a.results[0].returnValues[0][0].toReversed()))}async nativeTokenAmount(e,t){var u,d;const r=(v(e)?I.nativeTokenId(this.network,this.chain):e).toString(),o=await this.connection.getCoinMetadata({coinType:r});if(!o)throw new Error("metadata is null");const i=await this.getPackageId(),a=new T;a.moveCall({target:`${i}::redeem::calculate_native_swap_amount_out`,arguments:[a.object(this.tokenBridgeRelayerObjectId),a.pure.u64(t),a.pure.u8(o.decimals)],typeArguments:[r]});const c=await this.connection.devInspectTransactionBlock({transactionBlock:a,sender:B.encode(new Uint8Array(32))});if(!c.results||c.results.length==0||!((u=c.results[0])!=null&&u.returnValues)||((d=c.results[0])==null?void 0:d.returnValues.length)!==1)throw Error("swap rate not set");return Y.decode(new Uint8Array(c.results[0].returnValues[0][0].toReversed()))}async getRegisteredTokens(){const t=(await this.getFields()).registered_tokens.fields.id.id;return(await this.connection.getDynamicFields({parentId:t})).data.map(o=>{const{address:i,module:a,name:c}=Se(o.objectType);return new m([i,a,c].join(P))})}async isRegisteredToken(e){const t=new m(v(e)?I.nativeTokenId(this.network,this.chain).address:e).unwrap();try{return await this.getTokenInfo(t)!==null}catch(n){console.error(n)}return!1}async getTokenInfo(e){var c;const t=await this.getFields(),r=new m(t.registered_tokens.type).getPackageId(),o=t.registered_tokens.fields.id.id,i=new m(e),a=le(W,i.unwrap())?W:i.getCoinType();try{const u=await this.connection.getDynamicFieldObject({parentId:o,name:{type:`${r}::registered_tokens::Key<${a}>`,value:{dummy_field:!1}}});if(u.error)throw new Error("Failed to get token info: "+JSON.stringify(u.error));if(!u.data||!u.data.content)throw new Error("Failed to get token info: "+JSON.stringify(u));const{content:d}=u.data;return b(d)&&b(d.fields.value)?d.fields.value.fields:null}catch(u){if((u==null?void 0:u.code)===-32e3&&((c=u.message)!=null&&c.includes("RPC Error")))return console.error(u),null;throw u}}async getFields(){if(!this.fields){const e=await M(this.connection,this.tokenBridgeRelayerObjectId);if(e===null)throw new Error("Failed to get fields from token bridge relayer state");this.fields=e}return this.fields}async getPackageId(){const e=await this.getFields();return new m(e.registered_tokens.type).getPackageId()}async getPackageIds(){const[e,t]=await Promise.all([V(this.connection,this.coreBridgeObjectId),V(this.connection,this.tokenBridgeObjectId)]);return{coreBridge:e,tokenBridge:t}}createUnsignedTx(e,t,n=!1){return new de(e,this.network,this.chain,t,n)}}se("Sui","TokenBridge",H);se("Sui","AutomaticTokenBridge",G);export{G as SuiAutomaticTokenBridge,H as SuiTokenBridge,D as getTokenCoinType,re as getTokenFromTokenRegistry};
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["main.js","main.css","assets/index-CwGBYrGm.js","assets/index-D9U4BOHM.js","assets/index-JtvUouOr.js"])))=>i.map(i=>d[i]);
2
- import{aC as i,_ as o,aD as e,aE as t,aA as n,aF as d}from"../main.js";import{g as s}from"./signer-Bqv2nxHC.js";const m={Address:t,Platform:e,getSigner:s,protocols:{WormholeCore:()=>o(()=>import("../main.js").then(a=>a.dv),__vite__mapDeps([0,1])),TokenBridge:()=>o(()=>import("./index-CwGBYrGm.js"),__vite__mapDeps([2,0,1])),CircleBridge:()=>o(()=>import("./index-D9U4BOHM.js"),__vite__mapDeps([3,0,1])),TBTCBridge:()=>o(()=>import("./index-JtvUouOr.js"),__vite__mapDeps([4,0,1,2]))},getChain:(a,r,_)=>new i(r,new e(a,n(a,d,{[r]:_})))};export{m as default};
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BRtMY3at.js","main.js","main.css","assets/blake2b-CzqSqyTv.js","assets/index-DmaqQuhH.js","assets/index-RBS_ALc7.js","assets/index-BUlVFUMr.js"])))=>i.map(i=>d[i]);
2
- var mn=Object.defineProperty;var yn=(r,e,t)=>e in r?mn(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var le=(r,e,t)=>yn(r,typeof e!="symbol"?e+"":e,t);import{be as bn,bf as At,bg as nt,bh as z,bi as ze,bj as A,bk as Pt,bl as ie,bm as k,bn as wn,bo as fr,bp as ne,bq as Ze,br as Yt,aY as vn,a_ as pr,a$ as gr,bb as ee,aN as Sn,aO as kn,aQ as En,aR as On,bs as In,aT as Tn,aU as ft,aV as jn,bt as Xe,aX as Cn,_ as pt,aA as _n}from"../main.js";import{b as st}from"./blake2b-CzqSqyTv.js";import{m as Mn}from"./index-DmaqQuhH.js";function it(r){let e=[],t=0;if(r===0)return[0];for(;r>0;)e[t]=r&127,(r>>=7)&&(e[t]|=128),t+=1;return e}function xn(r){let e=0,t=0,n=0;for(;;){let s=r[n];if(n+=1,e|=(s&127)<<t,!(s&128))break;t+=7}return{value:e,length:n}}class An{constructor(e){this.bytePosition=0,this.dataView=new DataView(e.buffer)}shift(e){return this.bytePosition+=e,this}read8(){let e=this.dataView.getUint8(this.bytePosition);return this.shift(1),e}read16(){let e=this.dataView.getUint16(this.bytePosition,!0);return this.shift(2),e}read32(){let e=this.dataView.getUint32(this.bytePosition,!0);return this.shift(4),e}read64(){let e=this.read32(),n=this.read32().toString(16)+e.toString(16).padStart(8,"0");return BigInt("0x"+n).toString(10)}read128(){let e=BigInt(this.read64()),n=BigInt(this.read64()).toString(16)+e.toString(16).padStart(16,"0");return BigInt("0x"+n).toString(10)}read256(){let e=BigInt(this.read128()),n=BigInt(this.read128()).toString(16)+e.toString(16).padStart(32,"0");return BigInt("0x"+n).toString(10)}readBytes(e){let t=this.bytePosition+this.dataView.byteOffset,n=new Uint8Array(this.dataView.buffer,t,e);return this.shift(e),n}readULEB(){let e=this.bytePosition+this.dataView.byteOffset,t=new Uint8Array(this.dataView.buffer,e),{value:n,length:s}=xn(t);return this.shift(s),n}readVec(e){let t=this.readULEB(),n=[];for(let s=0;s<t;s++)n.push(e(this,s,t));return n}}class Pn{constructor({initialSize:e=1024,maxSize:t=1/0,allocateSize:n=1024}={}){this.bytePosition=0,this.size=e,this.maxSize=t,this.allocateSize=n,this.dataView=new DataView(new ArrayBuffer(e))}ensureSizeOrGrow(e){const t=this.bytePosition+e;if(t>this.size){const n=Math.min(this.maxSize,this.size+this.allocateSize);if(t>n)throw new Error(`Attempting to serialize to BCS, but buffer does not have enough size. Allocated size: ${this.size}, Max size: ${this.maxSize}, Required size: ${t}`);this.size=n;const s=new ArrayBuffer(this.size);new Uint8Array(s).set(new Uint8Array(this.dataView.buffer)),this.dataView=new DataView(s)}}shift(e){return this.bytePosition+=e,this}write8(e){return this.ensureSizeOrGrow(1),this.dataView.setUint8(this.bytePosition,Number(e)),this.shift(1)}write16(e){return this.ensureSizeOrGrow(2),this.dataView.setUint16(this.bytePosition,Number(e),!0),this.shift(2)}write32(e){return this.ensureSizeOrGrow(4),this.dataView.setUint32(this.bytePosition,Number(e),!0),this.shift(4)}write64(e){return gt(BigInt(e),8).forEach(t=>this.write8(t)),this}write128(e){return gt(BigInt(e),16).forEach(t=>this.write8(t)),this}write256(e){return gt(BigInt(e),32).forEach(t=>this.write8(t)),this}writeULEB(e){return it(e).forEach(t=>this.write8(t)),this}writeVec(e,t){return this.writeULEB(e.length),Array.from(e).forEach((n,s)=>t(this,n,s,e.length)),this}*[Symbol.iterator](){for(let e=0;e<this.bytePosition;e++)yield this.dataView.getUint8(e);return this.toBytes()}toBytes(){return new Uint8Array(this.dataView.buffer.slice(0,this.bytePosition))}toString(e){return bn(this.toBytes(),e)}}function gt(r,e){let t=new Uint8Array(e),n=0;for(;r>0;)t[n]=Number(r%BigInt(256)),r=r/BigInt(256),n+=1;return t}var mr=r=>{throw TypeError(r)},yr=(r,e,t)=>e.has(r)||mr("Cannot "+t),G=(r,e,t)=>(yr(r,e,"read from private field"),t?t.call(r):e.get(r)),at=(r,e,t)=>e.has(r)?mr("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),ot=(r,e,t,n)=>(yr(r,e,"write to private field"),e.set(r,t),t),ve,Ae,Qe,ce;const Un=class br{constructor(e){at(this,ve),at(this,Ae),this.name=e.name,this.read=e.read,this.serializedSize=e.serializedSize??(()=>null),ot(this,ve,e.write),ot(this,Ae,e.serialize??((t,n)=>{const s=new Pn({initialSize:this.serializedSize(t)??void 0,...n});return G(this,ve).call(this,t,s),s.toBytes()})),this.validate=e.validate??(()=>{})}write(e,t){this.validate(e),G(this,ve).call(this,e,t)}serialize(e,t){return this.validate(e),new $n(this,G(this,Ae).call(this,e,t))}parse(e){const t=new An(e);return this.read(t)}fromHex(e){return this.parse(At(e))}fromBase58(e){return this.parse(nt(e))}fromBase64(e){return this.parse(z(e))}transform({name:e,input:t,output:n,validate:s}){return new br({name:e??this.name,read:i=>n?n(this.read(i)):this.read(i),write:(i,o)=>G(this,ve).call(this,t?t(i):i,o),serializedSize:i=>this.serializedSize(t?t(i):i),serialize:(i,o)=>G(this,Ae).call(this,t?t(i):i,o),validate:i=>{s==null||s(i),this.validate(t?t(i):i)}})}};ve=new WeakMap;Ae=new WeakMap;let H=Un;const wr=Symbol.for("@mysten/serialized-bcs");function Ut(r){return!!r&&typeof r=="object"&&r[wr]===!0}class $n{constructor(e,t){at(this,Qe),at(this,ce),ot(this,Qe,e),ot(this,ce,t)}get[wr](){return!0}toBytes(){return G(this,ce)}toHex(){return ze(G(this,ce))}toBase64(){return A(G(this,ce))}toBase58(){return Pt(G(this,ce))}parse(){return G(this,Qe).parse(G(this,ce))}}Qe=new WeakMap;ce=new WeakMap;function ct({size:r,...e}){return new H({...e,serializedSize:()=>r})}function mt({readMethod:r,writeMethod:e,...t}){return ct({...t,read:n=>n[r](),write:(n,s)=>s[e](n),validate:n=>{var s;if(n<0||n>t.maxValue)throw new TypeError(`Invalid ${t.name} value: ${n}. Expected value in range 0-${t.maxValue}`);(s=t.validate)==null||s.call(t,n)}})}function yt({readMethod:r,writeMethod:e,...t}){return ct({...t,read:n=>n[r](),write:(n,s)=>s[e](BigInt(n)),validate:n=>{var i;const s=BigInt(n);if(s<0||s>t.maxValue)throw new TypeError(`Invalid ${t.name} value: ${s}. Expected value in range 0-${t.maxValue}`);(i=t.validate)==null||i.call(t,s)}})}function Bn({serialize:r,...e}){const t=new H({...e,serialize:r,write:(n,s)=>{for(const i of t.serialize(n).toBytes())s.write8(i)}});return t}function Rn({toBytes:r,fromBytes:e,...t}){return new H({...t,read:n=>{const s=n.readULEB(),i=n.readBytes(s);return e(i)},write:(n,s)=>{const i=r(n);s.writeULEB(i.length);for(let o=0;o<i.length;o++)s.write8(i[o])},serialize:n=>{const s=r(n),i=it(s.length),o=new Uint8Array(i.length+s.length);return o.set(i,0),o.set(s,i.length),o},validate:n=>{var s;if(typeof n!="string")throw new TypeError(`Invalid ${t.name} value: ${n}. Expected string`);(s=t.validate)==null||s.call(t,n)}})}function Nn(r){let e=null;function t(){return e||(e=r()),e}return new H({name:"lazy",read:n=>t().read(n),serializedSize:n=>t().serializedSize(n),write:(n,s)=>t().write(n,s),serialize:(n,s)=>t().serialize(n,s).toBytes()})}const a={u8(r){return mt({name:"u8",readMethod:"read8",writeMethod:"write8",size:1,maxValue:2**8-1,...r})},u16(r){return mt({name:"u16",readMethod:"read16",writeMethod:"write16",size:2,maxValue:2**16-1,...r})},u32(r){return mt({name:"u32",readMethod:"read32",writeMethod:"write32",size:4,maxValue:2**32-1,...r})},u64(r){return yt({name:"u64",readMethod:"read64",writeMethod:"write64",size:8,maxValue:2n**64n-1n,...r})},u128(r){return yt({name:"u128",readMethod:"read128",writeMethod:"write128",size:16,maxValue:2n**128n-1n,...r})},u256(r){return yt({name:"u256",readMethod:"read256",writeMethod:"write256",size:32,maxValue:2n**256n-1n,...r})},bool(r){return ct({name:"bool",size:1,read:e=>e.read8()===1,write:(e,t)=>t.write8(e?1:0),...r,validate:e=>{var t;if((t=r==null?void 0:r.validate)==null||t.call(r,e),typeof e!="boolean")throw new TypeError(`Expected boolean, found ${typeof e}`)}})},uleb128(r){return Bn({name:"uleb128",read:e=>e.readULEB(),serialize:e=>Uint8Array.from(it(e)),...r})},bytes(r,e){return ct({name:`bytes[${r}]`,size:r,read:t=>t.readBytes(r),write:(t,n)=>{const s=new Uint8Array(t);for(let i=0;i<r;i++)n.write8(s[i]??0)},...e,validate:t=>{var n;if((n=e==null?void 0:e.validate)==null||n.call(e,t),!t||typeof t!="object"||!("length"in t))throw new TypeError(`Expected array, found ${typeof t}`);if(t.length!==r)throw new TypeError(`Expected array of length ${r}, found ${t.length}`)}})},byteVector(r){return new H({name:"bytesVector",read:e=>{const t=e.readULEB();return e.readBytes(t)},write:(e,t)=>{const n=new Uint8Array(e);t.writeULEB(n.length);for(let s=0;s<n.length;s++)t.write8(n[s]??0)},...r,serializedSize:e=>{const t="length"in e?e.length:null;return t==null?null:it(t).length+t},validate:e=>{var t;if((t=r==null?void 0:r.validate)==null||t.call(r,e),!e||typeof e!="object"||!("length"in e))throw new TypeError(`Expected array, found ${typeof e}`)}})},string(r){return Rn({name:"string",toBytes:e=>new TextEncoder().encode(e),fromBytes:e=>new TextDecoder().decode(e),...r})},fixedArray(r,e,t){return new H({name:`${e.name}[${r}]`,read:n=>{const s=new Array(r);for(let i=0;i<r;i++)s[i]=e.read(n);return s},write:(n,s)=>{for(const i of n)e.write(i,s)},...t,validate:n=>{var s;if((s=t==null?void 0:t.validate)==null||s.call(t,n),!n||typeof n!="object"||!("length"in n))throw new TypeError(`Expected array, found ${typeof n}`);if(n.length!==r)throw new TypeError(`Expected array of length ${r}, found ${n.length}`)}})},option(r){return a.enum(`Option<${r.name}>`,{None:null,Some:r}).transform({input:e=>e==null?{None:!0}:{Some:e},output:e=>e.$kind==="Some"?e.Some:null})},vector(r,e){return new H({name:`vector<${r.name}>`,read:t=>{const n=t.readULEB(),s=new Array(n);for(let i=0;i<n;i++)s[i]=r.read(t);return s},write:(t,n)=>{n.writeULEB(t.length);for(const s of t)r.write(s,n)},...e,validate:t=>{var n;if((n=e==null?void 0:e.validate)==null||n.call(e,t),!t||typeof t!="object"||!("length"in t))throw new TypeError(`Expected array, found ${typeof t}`)}})},tuple(r,e){return new H({name:`(${r.map(t=>t.name).join(", ")})`,serializedSize:t=>{let n=0;for(let s=0;s<r.length;s++){const i=r[s].serializedSize(t[s]);if(i==null)return null;n+=i}return n},read:t=>{const n=[];for(const s of r)n.push(s.read(t));return n},write:(t,n)=>{for(let s=0;s<r.length;s++)r[s].write(t[s],n)},...e,validate:t=>{var n;if((n=e==null?void 0:e.validate)==null||n.call(e,t),!Array.isArray(t))throw new TypeError(`Expected array, found ${typeof t}`);if(t.length!==r.length)throw new TypeError(`Expected array of length ${r.length}, found ${t.length}`)}})},struct(r,e,t){const n=Object.entries(e);return new H({name:r,serializedSize:s=>{let i=0;for(const[o,u]of n){const c=u.serializedSize(s[o]);if(c==null)return null;i+=c}return i},read:s=>{const i={};for(const[o,u]of n)i[o]=u.read(s);return i},write:(s,i)=>{for(const[o,u]of n)u.write(s[o],i)},...t,validate:s=>{var i;if((i=t==null?void 0:t.validate)==null||i.call(t,s),typeof s!="object"||s==null)throw new TypeError(`Expected object, found ${typeof s}`)}})},enum(r,e,t){const n=Object.entries(e);return new H({name:r,read:s=>{const i=s.readULEB(),o=n[i];if(!o)throw new TypeError(`Unknown value ${i} for enum ${r}`);const[u,c]=o;return{[u]:(c==null?void 0:c.read(s))??!0,$kind:u}},write:(s,i)=>{const[o,u]=Object.entries(s).filter(([c])=>Object.hasOwn(e,c))[0];for(let c=0;c<n.length;c++){const[g,l]=n[c];if(g===o){i.writeULEB(c),l==null||l.write(u,i);return}}},...t,validate:s=>{var u;if((u=t==null?void 0:t.validate)==null||u.call(t,s),typeof s!="object"||s==null)throw new TypeError(`Expected object, found ${typeof s}`);const i=Object.keys(s).filter(c=>s[c]!==void 0&&Object.hasOwn(e,c));if(i.length!==1)throw new TypeError(`Expected object with one key, but found ${i.length} for type ${r}}`);const[o]=i;if(!Object.hasOwn(e,o))throw new TypeError(`Invalid enum variant ${o}`)}})},map(r,e){return a.vector(a.tuple([r,e])).transform({name:`Map<${r.name}, ${e.name}>`,input:t=>[...t.entries()],output:t=>{const n=new Map;for(const[s,i]of t)n.set(s,i);return n}})},lazy(r){return Nn(r)}},Dn=/^(?!.*(^(?!@)|[-.@])($|[-.@]))(?:[a-z0-9-]{0,63}(?:\.[a-z0-9-]{0,63})*)?@[a-z0-9-]{0,63}$/i,zn=/^(?!.*(^|[-.])($|[-.]))(?:[a-z0-9-]{0,63}\.)+sui$/i;function Vn(r,e="at"){const t=r.toLowerCase();let n;if(t.includes("@")){if(!Dn.test(t))throw new Error(`Invalid SuiNS name ${r}`);const[s,i]=t.split("@");n=[...s?s.split("."):[],i]}else{if(!zn.test(t))throw new Error(`Invalid SuiNS name ${r}`);n=t.split(".").slice(0,-1)}return e==="dot"?`${n.join(".")}.sui`:`${n.slice(0,-1).join(".")}@${n[n.length-1]}`}BigInt(1e9);const qn="0x1",vr="0x2",ca=ie("0x6"),Gn=`${vr}::sui::SUI`;ie("0x5");const Kn=/^vector<(.+)>$/,Fn=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;class J{static parseFromStr(e,t=!1){if(e==="address")return{address:null};if(e==="bool")return{bool:null};if(e==="u8")return{u8:null};if(e==="u16")return{u16:null};if(e==="u32")return{u32:null};if(e==="u64")return{u64:null};if(e==="u128")return{u128:null};if(e==="u256")return{u256:null};if(e==="signer")return{signer:null};const n=e.match(Kn);if(n)return{vector:J.parseFromStr(n[1],t)};const s=e.match(Fn);if(s)return{struct:{address:t?k(s[1]):s[1],module:s[2],name:s[3],typeParams:s[5]===void 0?[]:J.parseStructTypeArgs(s[5],t)}};throw new Error(`Encountered unexpected token when parsing type args for ${e}`)}static parseStructTypeArgs(e,t=!1){return wn(e).map(n=>J.parseFromStr(n,t))}static tagToString(e){if("bool"in e)return"bool";if("u8"in e)return"u8";if("u16"in e)return"u16";if("u32"in e)return"u32";if("u64"in e)return"u64";if("u128"in e)return"u128";if("u256"in e)return"u256";if("address"in e)return"address";if("signer"in e)return"signer";if("vector"in e)return`vector<${J.tagToString(e.vector)}>`;if("struct"in e){const t=e.struct,n=t.typeParams.map(J.tagToString).join(", ");return`${t.address}::${t.module}::${t.name}${n?`<${n}>`:""}`}throw new Error("Invalid TypeTag")}}function Ln(r){return a.u64({name:"unsafe_u64",...r}).transform({input:e=>e,output:e=>Number(e)})}function Wn(r){return a.enum("Option",{None:null,Some:r})}const j=a.bytes(fr).transform({validate:r=>{const e=typeof r=="string"?r:ze(r);if(!e||!ne(k(e)))throw new Error(`Invalid Sui address ${e}`)},input:r=>typeof r=="string"?At(k(r)):r,output:r=>k(ze(r))}),L=a.vector(a.u8()).transform({name:"ObjectDigest",input:r=>nt(r),output:r=>Pt(new Uint8Array(r)),validate:r=>{if(nt(r).length!==32)throw new Error("ObjectDigest must be 32 bytes")}}),N=a.struct("SuiObjectRef",{objectId:j,version:a.u64(),digest:L}),Sr=a.struct("SharedObjectRef",{objectId:j,initialSharedVersion:a.u64(),mutable:a.bool()}),kr=a.enum("ObjectArg",{ImmOrOwnedObject:N,SharedObject:Sr,Receiving:N}),Er=a.enum("CallArg",{Pure:a.struct("Pure",{bytes:a.vector(a.u8()).transform({input:r=>typeof r=="string"?z(r):r,output:r=>A(new Uint8Array(r))})}),Object:kr}),$t=a.enum("TypeTag",{bool:null,u8:null,u64:null,u128:null,address:null,signer:null,vector:a.lazy(()=>$t),struct:a.lazy(()=>_r),u16:null,u32:null,u256:null}),Bt=$t.transform({input:r=>typeof r=="string"?J.parseFromStr(r,!0):r,output:r=>J.tagToString(r)}),W=a.enum("Argument",{GasCoin:null,Input:a.u16(),Result:a.u16(),NestedResult:a.tuple([a.u16(),a.u16()])}),Or=a.struct("ProgrammableMoveCall",{package:j,module:a.string(),function:a.string(),typeArguments:a.vector(Bt),arguments:a.vector(W)}),Ir=a.enum("Command",{MoveCall:Or,TransferObjects:a.struct("TransferObjects",{objects:a.vector(W),address:W}),SplitCoins:a.struct("SplitCoins",{coin:W,amounts:a.vector(W)}),MergeCoins:a.struct("MergeCoins",{destination:W,sources:a.vector(W)}),Publish:a.struct("Publish",{modules:a.vector(a.vector(a.u8()).transform({input:r=>typeof r=="string"?z(r):r,output:r=>A(new Uint8Array(r))})),dependencies:a.vector(j)}),MakeMoveVec:a.struct("MakeMoveVec",{type:Wn(Bt).transform({input:r=>r===null?{None:!0}:{Some:r},output:r=>r.Some??null}),elements:a.vector(W)}),Upgrade:a.struct("Upgrade",{modules:a.vector(a.vector(a.u8()).transform({input:r=>typeof r=="string"?z(r):r,output:r=>A(new Uint8Array(r))})),dependencies:a.vector(j),package:j,ticket:W})}),Tr=a.struct("ProgrammableTransaction",{inputs:a.vector(Er),commands:a.vector(Ir)}),jr=a.enum("TransactionKind",{ProgrammableTransaction:Tr,ChangeEpoch:null,Genesis:null,ConsensusCommitPrologue:null}),Cr=a.enum("TransactionExpiration",{None:null,Epoch:Ln()}),_r=a.struct("StructTag",{address:j,module:a.string(),name:a.string(),typeParams:a.vector($t)}),Mr=a.struct("GasData",{payment:a.vector(N),owner:j,price:a.u64(),budget:a.u64()}),xr=a.struct("TransactionDataV1",{kind:jr,sender:j,gasData:Mr,expiration:Cr}),Ar=a.enum("TransactionData",{V1:xr}),Pr=a.enum("IntentScope",{TransactionData:null,TransactionEffects:null,CheckpointSummary:null,PersonalMessage:null}),Ur=a.enum("IntentVersion",{V0:null}),$r=a.enum("AppId",{Sui:null}),Br=a.struct("Intent",{scope:Pr,version:Ur,appId:$r});function Rr(r){return a.struct(`IntentMessage<${r.name}>`,{intent:Br,value:r})}const Nr=a.enum("CompressedSignature",{ED25519:a.fixedArray(64,a.u8()),Secp256k1:a.fixedArray(64,a.u8()),Secp256r1:a.fixedArray(64,a.u8()),ZkLogin:a.vector(a.u8())}),Dr=a.enum("PublicKey",{ED25519:a.fixedArray(32,a.u8()),Secp256k1:a.fixedArray(33,a.u8()),Secp256r1:a.fixedArray(33,a.u8()),ZkLogin:a.vector(a.u8())}),zr=a.struct("MultiSigPkMap",{pubKey:Dr,weight:a.u8()}),Vr=a.struct("MultiSigPublicKey",{pk_map:a.vector(zr),threshold:a.u16()}),Hn=a.struct("MultiSig",{sigs:a.vector(Nr),bitmap:a.u16(),multisig_pk:Vr}),Jn=a.vector(a.u8()).transform({input:r=>typeof r=="string"?z(r):r,output:r=>A(new Uint8Array(r))}),qr=a.struct("SenderSignedTransaction",{intentMessage:Rr(Ar),txSignatures:a.vector(Jn)}),Zn=a.vector(qr,{name:"SenderSignedData"}),Yn=a.struct("PasskeyAuthenticator",{authenticatorData:a.vector(a.u8()),clientDataJson:a.string(),userSignature:a.vector(a.u8())}),Xn=a.enum("PackageUpgradeError",{UnableToFetchPackage:a.struct("UnableToFetchPackage",{packageId:j}),NotAPackage:a.struct("NotAPackage",{objectId:j}),IncompatibleUpgrade:null,DigestDoesNotMatch:a.struct("DigestDoesNotMatch",{digest:a.vector(a.u8())}),UnknownUpgradePolicy:a.struct("UnknownUpgradePolicy",{policy:a.u8()}),PackageIDDoesNotMatch:a.struct("PackageIDDoesNotMatch",{packageId:j,ticketId:j})}),Qn=a.struct("ModuleId",{address:j,name:a.string()}),Xt=a.struct("MoveLocation",{module:Qn,function:a.u16(),instruction:a.u16(),functionName:a.option(a.string())}),es=a.enum("CommandArgumentError",{TypeMismatch:null,InvalidBCSBytes:null,InvalidUsageOfPureArg:null,InvalidArgumentToPrivateEntryFunction:null,IndexOutOfBounds:a.struct("IndexOutOfBounds",{idx:a.u16()}),SecondaryIndexOutOfBounds:a.struct("SecondaryIndexOutOfBounds",{resultIdx:a.u16(),secondaryIdx:a.u16()}),InvalidResultArity:a.struct("InvalidResultArity",{resultIdx:a.u16()}),InvalidGasCoinUsage:null,InvalidValueUsage:null,InvalidObjectByValue:null,InvalidObjectByMutRef:null,SharedObjectOperationNotAllowed:null}),ts=a.enum("TypeArgumentError",{TypeNotFound:null,ConstraintNotSatisfied:null}),rs=a.enum("ExecutionFailureStatus",{InsufficientGas:null,InvalidGasObject:null,InvariantViolation:null,FeatureNotYetSupported:null,MoveObjectTooBig:a.struct("MoveObjectTooBig",{objectSize:a.u64(),maxObjectSize:a.u64()}),MovePackageTooBig:a.struct("MovePackageTooBig",{objectSize:a.u64(),maxObjectSize:a.u64()}),CircularObjectOwnership:a.struct("CircularObjectOwnership",{object:j}),InsufficientCoinBalance:null,CoinBalanceOverflow:null,PublishErrorNonZeroAddress:null,SuiMoveVerificationError:null,MovePrimitiveRuntimeError:a.option(Xt),MoveAbort:a.tuple([Xt,a.u64()]),VMVerificationOrDeserializationError:null,VMInvariantViolation:null,FunctionNotFound:null,ArityMismatch:null,TypeArityMismatch:null,NonEntryFunctionInvoked:null,CommandArgumentError:a.struct("CommandArgumentError",{argIdx:a.u16(),kind:es}),TypeArgumentError:a.struct("TypeArgumentError",{argumentIdx:a.u16(),kind:ts}),UnusedValueWithoutDrop:a.struct("UnusedValueWithoutDrop",{resultIdx:a.u16(),secondaryIdx:a.u16()}),InvalidPublicFunctionReturnType:a.struct("InvalidPublicFunctionReturnType",{idx:a.u16()}),InvalidTransferObject:null,EffectsTooLarge:a.struct("EffectsTooLarge",{currentSize:a.u64(),maxSize:a.u64()}),PublishUpgradeMissingDependency:null,PublishUpgradeDependencyDowngrade:null,PackageUpgradeError:a.struct("PackageUpgradeError",{upgradeError:Xn}),WrittenObjectsTooLarge:a.struct("WrittenObjectsTooLarge",{currentSize:a.u64(),maxSize:a.u64()}),CertificateDenied:null,SuiMoveVerificationTimedout:null,SharedObjectOperationNotAllowed:null,InputObjectDeleted:null,ExecutionCancelledDueToSharedObjectCongestion:a.struct("ExecutionCancelledDueToSharedObjectCongestion",{congestedObjects:a.vector(j)}),AddressDeniedForCoin:a.struct("AddressDeniedForCoin",{address:j,coinType:a.string()}),CoinTypeGlobalPause:a.struct("CoinTypeGlobalPause",{coinType:a.string()}),ExecutionCancelledDueToRandomnessUnavailable:null}),Gr=a.enum("ExecutionStatus",{Success:null,Failed:a.struct("ExecutionFailed",{error:rs,command:a.option(a.u64())})}),Kr=a.struct("GasCostSummary",{computationCost:a.u64(),storageCost:a.u64(),storageRebate:a.u64(),nonRefundableStorageFee:a.u64()}),Se=a.enum("Owner",{AddressOwner:j,ObjectOwner:j,Shared:a.struct("Shared",{initialSharedVersion:a.u64()}),Immutable:null}),ns=a.struct("TransactionEffectsV1",{status:Gr,executedEpoch:a.u64(),gasUsed:Kr,modifiedAtVersions:a.vector(a.tuple([j,a.u64()])),sharedObjects:a.vector(N),transactionDigest:L,created:a.vector(a.tuple([N,Se])),mutated:a.vector(a.tuple([N,Se])),unwrapped:a.vector(a.tuple([N,Se])),deleted:a.vector(N),unwrappedThenDeleted:a.vector(N),wrapped:a.vector(N),gasObject:a.tuple([N,Se]),eventsDigest:a.option(L),dependencies:a.vector(L)}),Rt=a.tuple([a.u64(),L]),ss=a.enum("ObjectIn",{NotExist:null,Exist:a.tuple([Rt,Se])}),is=a.enum("ObjectOut",{NotExist:null,ObjectWrite:a.tuple([L,Se]),PackageWrite:Rt}),as=a.enum("IDOperation",{None:null,Created:null,Deleted:null}),os=a.struct("EffectsObjectChange",{inputState:ss,outputState:is,idOperation:as}),cs=a.enum("UnchangedSharedKind",{ReadOnlyRoot:Rt,MutateDeleted:a.u64(),ReadDeleted:a.u64(),Cancelled:a.u64(),PerEpochConfig:null}),us=a.struct("TransactionEffectsV2",{status:Gr,executedEpoch:a.u64(),gasUsed:Kr,transactionDigest:L,gasObjectIndex:a.option(a.u32()),eventsDigest:a.option(L),dependencies:a.vector(L),lamportVersion:a.u64(),changedObjects:a.vector(a.tuple([j,os])),unchangedSharedObjects:a.vector(a.tuple([j,cs])),auxDataDigest:a.option(L)}),ls=a.enum("TransactionEffects",{V1:ns,V2:us});function $e(r){switch(r){case"u8":return a.u8();case"u16":return a.u16();case"u32":return a.u32();case"u64":return a.u64();case"u128":return a.u128();case"u256":return a.u256();case"bool":return a.bool();case"string":return a.string();case"id":case"address":return j}const e=r.match(/^(vector|option)<(.+)>$/);if(e){const[t,n]=e.slice(1);return t==="vector"?a.vector($e(n)):a.option($e(n))}throw new Error(`Invalid Pure type name: ${r}`)}const y={...a,U8:a.u8(),U16:a.u16(),U32:a.u32(),U64:a.u64(),U128:a.u128(),U256:a.u256(),ULEB128:a.uleb128(),Bool:a.bool(),String:a.string(),Address:j,AppId:$r,Argument:W,CallArg:Er,CompressedSignature:Nr,GasData:Mr,Intent:Br,IntentMessage:Rr,IntentScope:Pr,IntentVersion:Ur,MultiSig:Hn,MultiSigPkMap:zr,MultiSigPublicKey:Vr,ObjectArg:kr,ObjectDigest:L,ProgrammableMoveCall:Or,ProgrammableTransaction:Tr,PublicKey:Dr,SenderSignedData:Zn,SenderSignedTransaction:qr,SharedObjectRef:Sr,StructTag:_r,SuiObjectRef:N,Command:Ir,TransactionData:Ar,TransactionDataV1:xr,TransactionExpiration:Cr,TransactionKind:jr,TypeTag:Bt,TransactionEffects:ls,PasskeyAuthenticator:Yn},ds="1.21.2",hs="1.43.0",fs={"-32700":"ParseError","-32701":"OversizedRequest","-32702":"OversizedResponse","-32600":"InvalidRequest","-32601":"MethodNotFound","-32602":"InvalidParams","-32603":"InternalError","-32604":"ServerBusy","-32000":"CallExecutionFailed","-32001":"UnknownError","-32003":"SubscriptionClosed","-32004":"SubscriptionClosedWithError","-32005":"BatchesNotSupported","-32006":"TooManySubscriptions","-32050":"TransientError","-32002":"TransactionExecutionClientError"};class Fr extends Error{}class Lr extends Fr{constructor(e,t){super(e),this.code=t,this.type=fs[t]??"ServerError"}}class ps extends Fr{constructor(e,t,n){super(e),this.status=t,this.statusText=n}}var Wr=r=>{throw TypeError(r)},Nt=(r,e,t)=>e.has(r)||Wr("Cannot "+t),_=(r,e,t)=>(Nt(r,e,"read from private field"),t?t.call(r):e.get(r)),de=(r,e,t)=>e.has(r)?Wr("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),Ee=(r,e,t,n)=>(Nt(r,e,"write to private field"),e.set(r,t),t),Hr=(r,e,t)=>(Nt(r,e,"access private method"),t),gs=(r,e,t,n)=>({set _(s){Ee(r,e,s)},get _(){return _(r,e,n)}}),pe,Be,se,me,Ve,Oe,ut,Jr,Zr;function ms(r){const e=new URL(r);return e.protocol=e.protocol.replace("http","ws"),e.toString()}const ys={WebSocketConstructor:typeof WebSocket<"u"?WebSocket:void 0,callTimeout:3e4,reconnectTimeout:3e3,maxReconnects:5};class bs{constructor(e,t={}){if(de(this,ut),de(this,pe,0),de(this,Be,0),de(this,se,null),de(this,me,null),de(this,Ve,new Set),de(this,Oe,new Map),this.endpoint=e,this.options={...ys,...t},!this.options.WebSocketConstructor)throw new Error("Missing WebSocket constructor");this.endpoint.startsWith("http")&&(this.endpoint=ms(this.endpoint))}async makeRequest(e,t){const n=await Hr(this,ut,Jr).call(this);return new Promise((s,i)=>{Ee(this,pe,_(this,pe)+1),_(this,Oe).set(_(this,pe),{resolve:s,reject:i,timeout:setTimeout(()=>{_(this,Oe).delete(_(this,pe)),i(new Error(`Request timeout: ${e}`))},this.options.callTimeout)}),n.send(JSON.stringify({jsonrpc:"2.0",id:_(this,pe),method:e,params:t}))}).then(({error:s,result:i})=>{if(s)throw new Lr(s.message,s.code);return i})}async subscribe(e){const t=new ws(e);return _(this,Ve).add(t),await t.subscribe(this),()=>t.unsubscribe(this)}}pe=new WeakMap;Be=new WeakMap;se=new WeakMap;me=new WeakMap;Ve=new WeakMap;Oe=new WeakMap;ut=new WeakSet;Jr=function(){return _(this,me)?_(this,me):(Ee(this,me,new Promise(r=>{var e;(e=_(this,se))==null||e.close(),Ee(this,se,new this.options.WebSocketConstructor(this.endpoint)),_(this,se).addEventListener("open",()=>{Ee(this,Be,0),r(_(this,se))}),_(this,se).addEventListener("close",()=>{gs(this,Be)._++,_(this,Be)<=this.options.maxReconnects&&setTimeout(()=>{Hr(this,ut,Zr).call(this)},this.options.reconnectTimeout)}),_(this,se).addEventListener("message",({data:t})=>{let n;try{n=JSON.parse(t)}catch(s){console.error(new Error(`Failed to parse RPC message: ${t}`,{cause:s}));return}if("id"in n&&n.id!=null&&_(this,Oe).has(n.id)){const{resolve:s,timeout:i}=_(this,Oe).get(n.id);clearTimeout(i),s(n)}else if("params"in n){const{params:s}=n;_(this,Ve).forEach(i=>{i.subscriptionId===s.subscription&&s.subscription===i.subscriptionId&&i.onMessage(s.result)})}})})),_(this,me))};Zr=async function(){var r;return(r=_(this,se))==null||r.close(),Ee(this,me,null),Promise.allSettled([..._(this,Ve)].map(e=>e.subscribe(this)))};class ws{constructor(e){this.subscriptionId=null,this.subscribed=!1,this.input=e}onMessage(e){this.subscribed&&this.input.onMessage(e)}async unsubscribe(e){const{subscriptionId:t}=this;return this.subscribed=!1,t==null?!1:(this.subscriptionId=null,e.makeRequest(this.input.unsubscribe,[t]))}async subscribe(e){this.subscriptionId=null,this.subscribed=!0;const t=await e.makeRequest(this.input.method,this.input.params);this.subscribed&&(this.subscriptionId=t)}}var Yr=r=>{throw TypeError(r)},Dt=(r,e,t)=>e.has(r)||Yr("Cannot "+t),D=(r,e,t)=>(Dt(r,e,"read from private field"),t?t.call(r):e.get(r)),Ye=(r,e,t)=>e.has(r)?Yr("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),kt=(r,e,t,n)=>(Dt(r,e,"write to private field"),e.set(r,t),t),vs=(r,e,t)=>(Dt(r,e,"access private method"),t),Pe,K,Re,Et,Xr;class Ss{constructor(e){Ye(this,Et),Ye(this,Pe,0),Ye(this,K),Ye(this,Re),kt(this,K,e)}fetch(e,t){const n=D(this,K).fetch??fetch;if(!n)throw new Error("The current environment does not support fetch, you can provide a fetch implementation in the options for SuiHTTPTransport.");return n(e,t)}async request(e){var s,i;kt(this,Pe,D(this,Pe)+1);const t=await this.fetch(((s=D(this,K).rpc)==null?void 0:s.url)??D(this,K).url,{method:"POST",headers:{"Content-Type":"application/json","Client-Sdk-Type":"typescript","Client-Sdk-Version":ds,"Client-Target-Api-Version":hs,"Client-Request-Method":e.method,...(i=D(this,K).rpc)==null?void 0:i.headers},body:JSON.stringify({jsonrpc:"2.0",id:D(this,Pe),method:e.method,params:e.params})});if(!t.ok)throw new ps(`Unexpected status code: ${t.status}`,t.status,t.statusText);const n=await t.json();if("error"in n&&n.error!=null)throw new Lr(n.error.message,n.error.code);return n.result}async subscribe(e){const t=await vs(this,Et,Xr).call(this).subscribe(e);return async()=>!!await t()}}Pe=new WeakMap;K=new WeakMap;Re=new WeakMap;Et=new WeakSet;Xr=function(){var r;if(!D(this,Re)){const e=D(this,K).WebSocketConstructor??WebSocket;if(!e)throw new Error("The current environment does not support WebSocket, you can provide a WebSocketConstructor in the options for SuiHTTPTransport.");kt(this,Re,new bs(((r=D(this,K).websocket)==null?void 0:r.url)??D(this,K).url,{WebSocketConstructor:e,...D(this,K).websocket}))}return D(this,Re)};const ks="object",Es="ID",Os="ascii",Is="String",Ts="string",js="String",Cs="option",_s="Option";function Ms(r){const e=typeof r.body=="object"&&"datatype"in r.body?r.body.datatype:null;return!!e&&k(e.package)===k("0x2")&&e.module==="tx_context"&&e.type==="TxContext"}function Ot(r){if(typeof r=="string")switch(r){case"address":return y.Address;case"bool":return y.Bool;case"u8":return y.U8;case"u16":return y.U16;case"u32":return y.U32;case"u64":return y.U64;case"u128":return y.U128;case"u256":return y.U256;default:throw new Error(`Unknown type signature ${r}`)}if("vector"in r){if(r.vector==="u8")return y.vector(y.U8).transform({input:t=>typeof t=="string"?new TextEncoder().encode(t):t,output:t=>t});const e=Ot(r.vector);return e?y.vector(e):null}if("datatype"in r){const e=k(r.datatype.package);if(e===k(qn)){if(r.datatype.module===Os&&r.datatype.type===Is||r.datatype.module===Ts&&r.datatype.type===js)return y.String;if(r.datatype.module===Cs&&r.datatype.type===_s){const t=Ot(r.datatype.typeParameters[0]);return t?y.vector(t):null}}if(e===k(vr)&&r.datatype.module===ks&&r.datatype.type===Es)return y.Address}return null}function xs(r){return typeof r=="object"&&"Reference"in r?{ref:"&",body:Ne(r.Reference)}:typeof r=="object"&&"MutableReference"in r?{ref:"&mut",body:Ne(r.MutableReference)}:{ref:null,body:Ne(r)}}function Ne(r){if(typeof r=="string")switch(r){case"Address":return"address";case"Bool":return"bool";case"U8":return"u8";case"U16":return"u16";case"U32":return"u32";case"U64":return"u64";case"U128":return"u128";case"U256":return"u256";default:throw new Error(`Unexpected type ${r}`)}if("Vector"in r)return{vector:Ne(r.Vector)};if("Struct"in r)return{datatype:{package:r.Struct.address,module:r.Struct.module,type:r.Struct.name,typeParameters:r.Struct.typeArguments.map(Ne)}};if("TypeParameter"in r)return{typeParameter:r.TypeParameter};throw new Error(`Unexpected type ${JSON.stringify(r)}`)}function As(r){return{$kind:"Pure",Pure:{bytes:r instanceof Uint8Array?A(r):r.toBase64()}}}const ae={Pure:As,ObjectRef({objectId:r,digest:e,version:t}){return{$kind:"Object",Object:{$kind:"ImmOrOwnedObject",ImmOrOwnedObject:{digest:e,version:t,objectId:k(r)}}}},SharedObjectRef({objectId:r,mutable:e,initialSharedVersion:t}){return{$kind:"Object",Object:{$kind:"SharedObject",SharedObject:{mutable:e,initialSharedVersion:t,objectId:k(r)}}}},ReceivingRef({objectId:r,digest:e,version:t}){return{$kind:"Object",Object:{$kind:"Receiving",Receiving:{digest:e,version:t,objectId:k(r)}}}}};var Y;function Ps(r){return{lang:(r==null?void 0:r.lang)??(Y==null?void 0:Y.lang),message:r==null?void 0:r.message,abortEarly:(r==null?void 0:r.abortEarly)??(Y==null?void 0:Y.abortEarly),abortPipeEarly:(r==null?void 0:r.abortPipeEarly)??(Y==null?void 0:Y.abortPipeEarly)}}var bt;function Us(r){return bt==null?void 0:bt.get(r)}var wt;function $s(r){return wt==null?void 0:wt.get(r)}var vt;function Bs(r,e){var t;return(t=vt==null?void 0:vt.get(r))==null?void 0:t.get(e)}function Qr(r){var t,n;const e=typeof r;return e==="string"?`"${r}"`:e==="number"||e==="bigint"||e==="boolean"?`${r}`:e==="object"||e==="function"?(r&&((n=(t=Object.getPrototypeOf(r))==null?void 0:t.constructor)==null?void 0:n.name))??"null":e}function R(r,e,t,n,s){const i=s&&"input"in s?s.input:t.value,o=(s==null?void 0:s.expected)??r.expects??null,u=(s==null?void 0:s.received)??Qr(i),c={kind:r.kind,type:r.type,input:i,expected:o,received:u,message:`Invalid ${e}: ${o?`Expected ${o} but r`:"R"}eceived ${u}`,requirement:r.requirement,path:s==null?void 0:s.path,issues:s==null?void 0:s.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},g=r.kind==="schema",l=(s==null?void 0:s.message)??r.message??Bs(r.reference,c.lang)??(g?$s(c.lang):null)??n.message??Us(c.lang);l&&(c.message=typeof l=="function"?l(c):l),g&&(t.typed=!1),t.issues?t.issues.push(c):t.issues=[c]}function Rs(r,e){return Object.hasOwn(r,e)&&e!=="__proto__"&&e!=="prototype"&&e!=="constructor"}var Ns=class extends Error{constructor(e){super(e[0].message);le(this,"issues");this.name="ValiError",this.issues=e}};function We(r,e){return{kind:"validation",type:"check",reference:We,async:!1,expects:null,requirement:r,message:e,_run(t,n){return t.typed&&!this.requirement(t.value)&&R(this,"input",t,n),t}}}function x(r){return{kind:"validation",type:"integer",reference:x,async:!1,expects:null,requirement:Number.isInteger,message:r,_run(e,t){return e.typed&&!this.requirement(e.value)&&R(this,"integer",e,t),e}}}function dt(r){return{kind:"transformation",type:"transform",reference:dt,async:!1,operation:r,_run(e){return e.value=this.operation(e.value),e}}}function zt(r,e,t){return typeof r.default=="function"?r.default(e,t):r.default}function It(r,e){return!r._run({typed:!1,value:e},{abortEarly:!0}).issues}function f(r,e){return{kind:"schema",type:"array",reference:f,expects:"Array",async:!1,item:r,message:e,_run(t,n){var i;const s=t.value;if(Array.isArray(s)){t.typed=!0,t.value=[];for(let o=0;o<s.length;o++){const u=s[o],c=this.item._run({typed:!1,value:u},n);if(c.issues){const g={type:"array",origin:"value",input:s,key:o,value:u};for(const l of c.issues)l.path?l.path.unshift(g):l.path=[g],(i=t.issues)==null||i.push(l);if(t.issues||(t.issues=c.issues),n.abortEarly){t.typed=!1;break}}c.typed||(t.typed=!1),t.value.push(c.value)}}else R(this,"type",t,n);return t}}}function Vt(r){return{kind:"schema",type:"bigint",reference:Vt,expects:"bigint",async:!1,message:r,_run(e,t){return typeof e.value=="bigint"?e.typed=!0:R(this,"type",e,t),e}}}function ht(r){return{kind:"schema",type:"boolean",reference:ht,expects:"boolean",async:!1,message:r,_run(e,t){return typeof e.value=="boolean"?e.typed=!0:R(this,"type",e,t),e}}}function qe(r){return{kind:"schema",type:"lazy",reference:qe,expects:"unknown",async:!1,getter:r,_run(e,t){return this.getter(e.value)._run(e,t)}}}function p(r,e){return{kind:"schema",type:"literal",reference:p,expects:Qr(r),async:!1,literal:r,message:e,_run(t,n){return t.value===this.literal?t.typed=!0:R(this,"type",t,n),t}}}function v(r,...e){const t={kind:"schema",type:"nullable",reference:v,expects:`${r.expects} | null`,async:!1,wrapped:r,_run(n,s){return n.value===null&&("default"in this&&(n.value=zt(this,n,s)),n.value===null)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in e&&(t.default=e[0]),t}function Te(r,...e){const t={kind:"schema",type:"nullish",reference:Te,expects:`${r.expects} | null | undefined`,async:!1,wrapped:r,_run(n,s){return(n.value===null||n.value===void 0)&&("default"in this&&(n.value=zt(this,n,s)),n.value===null||n.value===void 0)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in e&&(t.default=e[0]),t}function C(r){return{kind:"schema",type:"number",reference:C,expects:"number",async:!1,message:r,_run(e,t){return typeof e.value=="number"&&!isNaN(e.value)?e.typed=!0:R(this,"type",e,t),e}}}function d(r,e){return{kind:"schema",type:"object",reference:d,expects:"Object",async:!1,entries:r,message:e,_run(t,n){var i;const s=t.value;if(s&&typeof s=="object"){t.typed=!0,t.value={};for(const o in this.entries){const u=s[o],c=this.entries[o]._run({typed:!1,value:u},n);if(c.issues){const g={type:"object",origin:"value",input:s,key:o,value:u};for(const l of c.issues)l.path?l.path.unshift(g):l.path=[g],(i=t.issues)==null||i.push(l);if(t.issues||(t.issues=c.issues),n.abortEarly){t.typed=!1;break}}c.typed||(t.typed=!1),(c.value!==void 0||o in s)&&(t.value[o]=c.value)}}else R(this,"type",t,n);return t}}}function U(r,...e){const t={kind:"schema",type:"optional",reference:U,expects:`${r.expects} | undefined`,async:!1,wrapped:r,_run(n,s){return n.value===void 0&&("default"in this&&(n.value=zt(this,n,s)),n.value===void 0)?(n.typed=!0,n):this.wrapped._run(n,s)}};return 0 in e&&(t.default=e[0]),t}function Ge(r,e,t){return{kind:"schema",type:"record",reference:Ge,expects:"Object",async:!1,key:r,value:e,message:t,_run(n,s){var o,u;const i=n.value;if(i&&typeof i=="object"){n.typed=!0,n.value={};for(const c in i)if(Rs(i,c)){const g=i[c],l=this.key._run({typed:!1,value:c},s);if(l.issues){const I={type:"object",origin:"key",input:i,key:c,value:g};for(const O of l.issues)O.path=[I],(o=n.issues)==null||o.push(O);if(n.issues||(n.issues=l.issues),s.abortEarly){n.typed=!1;break}}const h=this.value._run({typed:!1,value:g},s);if(h.issues){const I={type:"object",origin:"value",input:i,key:c,value:g};for(const O of h.issues)O.path?O.path.unshift(I):O.path=[I],(u=n.issues)==null||u.push(O);if(n.issues||(n.issues=h.issues),s.abortEarly){n.typed=!1;break}}(!l.typed||!h.typed)&&(n.typed=!1),l.typed&&(n.value[l.value]=h.value)}}else R(this,"type",n,s);return n}}}function m(r){return{kind:"schema",type:"string",reference:m,expects:"string",async:!1,message:r,_run(e,t){return typeof e.value=="string"?e.typed=!0:R(this,"type",e,t),e}}}function qt(r,e){return{kind:"schema",type:"tuple",reference:qt,expects:"Array",async:!1,items:r,message:e,_run(t,n){var i;const s=t.value;if(Array.isArray(s)){t.typed=!0,t.value=[];for(let o=0;o<this.items.length;o++){const u=s[o],c=this.items[o]._run({typed:!1,value:u},n);if(c.issues){const g={type:"array",origin:"value",input:s,key:o,value:u};for(const l of c.issues)l.path?l.path.unshift(g):l.path=[g],(i=t.issues)==null||i.push(l);if(t.issues||(t.issues=c.issues),n.abortEarly){t.typed=!1;break}}c.typed||(t.typed=!1),t.value.push(c.value)}}else R(this,"type",t,n);return t}}}function Qt(r){let e;if(r)for(const t of r)e?e.push(...t.issues):e=t.issues;return e}function P(r,e){return{kind:"schema",type:"union",reference:P,expects:[...new Set(r.map(t=>t.expects))].join(" | ")||"never",async:!1,options:r,message:e,_run(t,n){let s,i,o;for(const u of this.options){const c=u._run({typed:!1,value:t.value},n);if(c.typed)if(c.issues)i?i.push(c):i=[c];else{s=c;break}else o?o.push(c):o=[c]}if(s)return s;if(i){if(i.length===1)return i[0];R(this,"type",t,n,{issues:Qt(i)}),t.typed=!0}else{if((o==null?void 0:o.length)===1)return o[0];R(this,"type",t,n,{issues:Qt(o)})}return t}}}function ye(){return{kind:"schema",type:"unknown",reference:ye,expects:"unknown",async:!1,_run(r){return r.typed=!0,r}}}function M(r,e,t){const n=r._run({typed:!1,value:e},Ps(t));if(n.issues)throw new Ns(n.issues);return n.value}function E(...r){return{...r[0],pipe:r,_run(e,t){for(let n=0;n<r.length;n++){if(e.issues&&(r[n].kind==="schema"||r[n].kind==="transformation")){e.typed=!1;break}(!e.issues||!t.abortEarly&&!t.abortPipeEarly)&&(e=r[n]._run(e,t))}return e}}}function we(r){const e=Object.entries(r).map(([t,n])=>d({[t]:n}));return E(P(e),dt(t=>({...t,$kind:Object.keys(t)[0]})))}const je=E(m(),dt(r=>k(r)),We(ne)),B=je,be=m(),$=E(P([m(),E(C(),x())]),We(r=>{try{return BigInt(r),BigInt(r)>=0&&BigInt(r)<=18446744073709551615n}catch{return!1}},"Invalid u64")),ue=d({objectId:je,version:$,digest:m()}),T=E(P([d({GasCoin:p(!0)}),d({Input:E(C(),x()),type:U(p("pure"))}),d({Input:E(C(),x()),type:U(p("object"))}),d({Result:E(C(),x())}),d({NestedResult:qt([E(C(),x()),E(C(),x())])})]),dt(r=>({...r,$kind:Object.keys(r)[0]}))),Ds=d({budget:v($),price:v($),owner:v(je),payment:v(f(ue))}),Tt=P([p("address"),p("bool"),p("u8"),p("u16"),p("u32"),p("u64"),p("u128"),p("u256"),d({vector:qe(()=>Tt)}),d({datatype:d({package:m(),module:m(),type:m(),typeParameters:f(qe(()=>Tt))})}),d({typeParameter:E(C(),x())})]),zs=d({ref:v(P([p("&"),p("&mut")])),body:Tt}),Vs=d({package:B,module:m(),function:m(),typeArguments:f(m()),arguments:f(T),_argumentTypes:U(v(f(zs)))}),qs=d({name:m(),inputs:Ge(m(),P([T,f(T)])),data:Ge(m(),ye())}),Gs=we({MoveCall:Vs,TransferObjects:d({objects:f(T),address:T}),SplitCoins:d({coin:T,amounts:f(T)}),MergeCoins:d({destination:T,sources:f(T)}),Publish:d({modules:f(be),dependencies:f(B)}),MakeMoveVec:d({type:v(m()),elements:f(T)}),Upgrade:d({modules:f(be),dependencies:f(B),package:B,ticket:T}),$Intent:qs}),en=we({ImmOrOwnedObject:ue,SharedObject:d({objectId:B,initialSharedVersion:$,mutable:ht()}),Receiving:ue}),Ks=we({Object:en,Pure:d({bytes:be}),UnresolvedPure:d({value:ye()}),UnresolvedObject:d({objectId:B,version:U(v($)),digest:U(v(m())),initialSharedVersion:U(v($))})}),er=we({Object:en,Pure:d({bytes:be})}),tn=we({None:p(!0),Epoch:$}),et=d({version:p(2),sender:Te(je),expiration:Te(tn),gasData:Ds,inputs:f(Ks),commands:f(Gs)}),he={MoveCall(r){const[e,t="",n=""]="target"in r?r.target.split("::"):[r.package,r.module,r.function];return{$kind:"MoveCall",MoveCall:{package:e,module:t,function:n,typeArguments:r.typeArguments??[],arguments:r.arguments??[]}}},TransferObjects(r,e){return{$kind:"TransferObjects",TransferObjects:{objects:r.map(t=>M(T,t)),address:M(T,e)}}},SplitCoins(r,e){return{$kind:"SplitCoins",SplitCoins:{coin:M(T,r),amounts:e.map(t=>M(T,t))}}},MergeCoins(r,e){return{$kind:"MergeCoins",MergeCoins:{destination:M(T,r),sources:e.map(t=>M(T,t))}}},Publish({modules:r,dependencies:e}){return{$kind:"Publish",Publish:{modules:r.map(t=>typeof t=="string"?t:A(new Uint8Array(t))),dependencies:e.map(t=>ie(t))}}},Upgrade({modules:r,dependencies:e,package:t,ticket:n}){return{$kind:"Upgrade",Upgrade:{modules:r.map(s=>typeof s=="string"?s:A(new Uint8Array(s))),dependencies:e.map(s=>ie(s)),package:t,ticket:M(T,n)}}},MakeMoveVec({type:r,elements:e}){return{$kind:"MakeMoveVec",MakeMoveVec:{type:r??null,elements:e.map(t=>M(T,t))}}},Intent({name:r,inputs:e={},data:t={}}){return{$kind:"$Intent",$Intent:{name:r,inputs:Object.fromEntries(Object.entries(e).map(([n,s])=>[n,Array.isArray(s)?s.map(i=>M(T,i)):M(T,s)])),data:t}}}},jt=d({digest:m(),objectId:m(),version:P([E(C(),x()),m(),Vt()])}),Fs=we({ImmOrOwned:jt,Shared:d({objectId:B,initialSharedVersion:$,mutable:ht()}),Receiving:jt}),tr=we({Object:Fs,Pure:f(E(C(),x()))}),rn=P([d({kind:p("Input"),index:E(C(),x()),value:ye(),type:U(p("object"))}),d({kind:p("Input"),index:E(C(),x()),value:ye(),type:p("pure")})]),Ls=P([d({Epoch:E(C(),x())}),d({None:v(p(!0))})]),rr=E(P([C(),m(),Vt()]),We(r=>{if(!["string","number","bigint"].includes(typeof r))return!1;try{return BigInt(r),!0}catch{return!1}})),Gt=P([d({bool:v(p(!0))}),d({u8:v(p(!0))}),d({u64:v(p(!0))}),d({u128:v(p(!0))}),d({address:v(p(!0))}),d({signer:v(p(!0))}),d({vector:qe(()=>Gt)}),d({struct:qe(()=>Ws)}),d({u16:v(p(!0))}),d({u32:v(p(!0))}),d({u256:v(p(!0))})]),Ws=d({address:m(),module:m(),name:m(),typeParams:f(Gt)}),Hs=d({budget:U(rr),price:U(rr),payment:U(f(jt)),owner:U(m())}),Js=[rn,d({kind:p("GasCoin")}),d({kind:p("Result"),index:E(C(),x())}),d({kind:p("NestedResult"),index:E(C(),x()),resultIndex:E(C(),x())})],oe=P([...Js]),Zs=d({kind:p("MoveCall"),target:E(m(),We(r=>r.split("::").length===3)),typeArguments:f(m()),arguments:f(oe)}),Ys=d({kind:p("TransferObjects"),objects:f(oe),address:oe}),Xs=d({kind:p("SplitCoins"),coin:oe,amounts:f(oe)}),Qs=d({kind:p("MergeCoins"),destination:oe,sources:f(oe)}),ei=d({kind:p("MakeMoveVec"),type:P([d({Some:Gt}),d({None:v(p(!0))})]),objects:f(oe)}),ti=d({kind:p("Publish"),modules:f(f(E(C(),x()))),dependencies:f(m())}),ri=d({kind:p("Upgrade"),modules:f(f(E(C(),x()))),dependencies:f(m()),packageId:m(),ticket:oe}),ni=[Zs,Ys,Xs,Qs,ti,ri,ei],si=P([...ni]);d({version:p(1),sender:U(m()),expiration:Te(Ls),gasConfig:Hs,inputs:f(rn),transactions:f(si)});function nr(r){var t;const e=r.inputs.map((n,s)=>{if(n.Object)return{kind:"Input",index:s,value:{Object:n.Object.ImmOrOwnedObject?{ImmOrOwned:n.Object.ImmOrOwnedObject}:n.Object.Receiving?{Receiving:{digest:n.Object.Receiving.digest,version:n.Object.Receiving.version,objectId:n.Object.Receiving.objectId}}:{Shared:{mutable:n.Object.SharedObject.mutable,initialSharedVersion:n.Object.SharedObject.initialSharedVersion,objectId:n.Object.SharedObject.objectId}}},type:"object"};if(n.Pure)return{kind:"Input",index:s,value:{Pure:Array.from(z(n.Pure.bytes))},type:"pure"};if(n.UnresolvedPure)return{kind:"Input",type:"pure",index:s,value:n.UnresolvedPure.value};if(n.UnresolvedObject)return{kind:"Input",type:"object",index:s,value:n.UnresolvedObject.objectId};throw new Error("Invalid input")});return{version:1,sender:r.sender??void 0,expiration:((t=r.expiration)==null?void 0:t.$kind)==="Epoch"?{Epoch:Number(r.expiration.Epoch)}:r.expiration?{None:!0}:null,gasConfig:{owner:r.gasData.owner??void 0,budget:r.gasData.budget??void 0,price:r.gasData.price??void 0,payment:r.gasData.payment??void 0},inputs:e,transactions:r.commands.map(n=>{if(n.MakeMoveVec)return{kind:"MakeMoveVec",type:n.MakeMoveVec.type===null?{None:!0}:{Some:J.parseFromStr(n.MakeMoveVec.type)},objects:n.MakeMoveVec.elements.map(s=>X(s,e))};if(n.MergeCoins)return{kind:"MergeCoins",destination:X(n.MergeCoins.destination,e),sources:n.MergeCoins.sources.map(s=>X(s,e))};if(n.MoveCall)return{kind:"MoveCall",target:`${n.MoveCall.package}::${n.MoveCall.module}::${n.MoveCall.function}`,typeArguments:n.MoveCall.typeArguments,arguments:n.MoveCall.arguments.map(s=>X(s,e))};if(n.Publish)return{kind:"Publish",modules:n.Publish.modules.map(s=>Array.from(z(s))),dependencies:n.Publish.dependencies};if(n.SplitCoins)return{kind:"SplitCoins",coin:X(n.SplitCoins.coin,e),amounts:n.SplitCoins.amounts.map(s=>X(s,e))};if(n.TransferObjects)return{kind:"TransferObjects",objects:n.TransferObjects.objects.map(s=>X(s,e)),address:X(n.TransferObjects.address,e)};if(n.Upgrade)return{kind:"Upgrade",modules:n.Upgrade.modules.map(s=>Array.from(z(s))),dependencies:n.Upgrade.dependencies,packageId:n.Upgrade.package,ticket:X(n.Upgrade.ticket,e)};throw new Error(`Unknown transaction ${Object.keys(n)}`)})}}function X(r,e){if(r.$kind==="GasCoin")return{kind:"GasCoin"};if(r.$kind==="Result")return{kind:"Result",index:r.Result};if(r.$kind==="NestedResult")return{kind:"NestedResult",index:r.NestedResult[0],resultIndex:r.NestedResult[1]};if(r.$kind==="Input")return e[r.Input];throw new Error(`Invalid argument ${Object.keys(r)}`)}function ii(r){var e,t,n;return M(et,{version:2,sender:r.sender??null,expiration:r.expiration?"Epoch"in r.expiration?{Epoch:r.expiration.Epoch}:{None:!0}:null,gasData:{owner:r.gasConfig.owner??null,budget:((e=r.gasConfig.budget)==null?void 0:e.toString())??null,price:((t=r.gasConfig.price)==null?void 0:t.toString())??null,payment:((n=r.gasConfig.payment)==null?void 0:n.map(s=>({digest:s.digest,objectId:s.objectId,version:s.version.toString()})))??null},inputs:r.inputs.map(s=>{if(s.kind==="Input"){if(It(tr,s.value)){const i=M(tr,s.value);if(i.Object){if(i.Object.ImmOrOwned)return{Object:{ImmOrOwnedObject:{objectId:i.Object.ImmOrOwned.objectId,version:String(i.Object.ImmOrOwned.version),digest:i.Object.ImmOrOwned.digest}}};if(i.Object.Shared)return{Object:{SharedObject:{mutable:i.Object.Shared.mutable??null,initialSharedVersion:i.Object.Shared.initialSharedVersion,objectId:i.Object.Shared.objectId}}};if(i.Object.Receiving)return{Object:{Receiving:{digest:i.Object.Receiving.digest,version:String(i.Object.Receiving.version),objectId:i.Object.Receiving.objectId}}};throw new Error("Invalid object input")}return{Pure:{bytes:A(new Uint8Array(i.Pure))}}}return s.type==="object"?{UnresolvedObject:{objectId:s.value}}:{UnresolvedPure:{value:s.value}}}throw new Error("Invalid input")}),commands:r.transactions.map(s=>{switch(s.kind){case"MakeMoveVec":return{MakeMoveVec:{type:"Some"in s.type?J.tagToString(s.type.Some):null,elements:s.objects.map(i=>Q(i))}};case"MergeCoins":return{MergeCoins:{destination:Q(s.destination),sources:s.sources.map(i=>Q(i))}};case"MoveCall":{const[i,o,u]=s.target.split("::");return{MoveCall:{package:i,module:o,function:u,typeArguments:s.typeArguments,arguments:s.arguments.map(c=>Q(c))}}}case"Publish":return{Publish:{modules:s.modules.map(i=>A(Uint8Array.from(i))),dependencies:s.dependencies}};case"SplitCoins":return{SplitCoins:{coin:Q(s.coin),amounts:s.amounts.map(i=>Q(i))}};case"TransferObjects":return{TransferObjects:{objects:s.objects.map(i=>Q(i)),address:Q(s.address)}};case"Upgrade":return{Upgrade:{modules:s.modules.map(i=>A(Uint8Array.from(i))),dependencies:s.dependencies,package:s.packageId,ticket:Q(s.ticket)}}}throw new Error(`Unknown transaction ${Object.keys(s)}`)})})}function Q(r){switch(r.kind){case"GasCoin":return{GasCoin:!0};case"Result":return{Result:r.index};case"NestedResult":return{NestedResult:[r.index,r.resultIndex]};case"Input":return{Input:r.index}}}function He(r){return P(Object.entries(r).map(([e,t])=>d({[e]:t})))}const V=He({GasCoin:p(!0),Input:E(C(),x()),Result:E(C(),x()),NestedResult:qt([E(C(),x()),E(C(),x())])}),ai=d({budget:v($),price:v($),owner:v(je),payment:v(f(ue))}),oi=d({package:B,module:m(),function:m(),typeArguments:f(m()),arguments:f(V)}),ci=d({name:m(),inputs:Ge(m(),P([V,f(V)])),data:Ge(m(),ye())}),ui=He({MoveCall:oi,TransferObjects:d({objects:f(V),address:V}),SplitCoins:d({coin:V,amounts:f(V)}),MergeCoins:d({destination:V,sources:f(V)}),Publish:d({modules:f(be),dependencies:f(B)}),MakeMoveVec:d({type:v(m()),elements:f(V)}),Upgrade:d({modules:f(be),dependencies:f(B),package:B,ticket:V}),$Intent:ci}),li=He({ImmOrOwnedObject:ue,SharedObject:d({objectId:B,initialSharedVersion:$,mutable:ht()}),Receiving:ue}),di=He({Object:li,Pure:d({bytes:be}),UnresolvedPure:d({value:ye()}),UnresolvedObject:d({objectId:B,version:U(v($)),digest:U(v(m())),initialSharedVersion:U(v($))})}),hi=He({None:p(!0),Epoch:$}),fi=d({version:p(2),sender:Te(je),expiration:Te(hi),gasData:ai,inputs:f(di),commands:f(ui)}),pi=50,gi=1000n,mi=5e10;async function yi(r,e,t){return await ki(r,e),await Si(r,e),e.onlyTransactionKind||(await bi(r,e),await wi(r,e),await vi(r,e)),await Ei(r),await t()}async function bi(r,e){r.gasConfig.price||(r.gasConfig.price=String(await Je(e).getReferenceGasPrice()))}async function wi(r,e){if(r.gasConfig.budget)return;const t=await Je(e).dryRunTransactionBlock({transactionBlock:r.build({overrides:{gasData:{budget:String(mi),payment:[]}}})});if(t.effects.status.status!=="success")throw new Error(`Dry run failed, could not automatically determine a budget: ${t.effects.status.error}`,{cause:t});const n=gi*BigInt(r.gasConfig.price||1n),s=BigInt(t.effects.gasUsed.computationCost)+n,i=s+BigInt(t.effects.gasUsed.storageCost)-BigInt(t.effects.gasUsed.storageRebate);r.gasConfig.budget=String(i>s?i:s)}async function vi(r,e){if(!r.gasConfig.payment){const n=(await Je(e).getCoins({owner:r.gasConfig.owner||r.sender,coinType:Gn})).data.filter(s=>!r.inputs.find(o=>{var u;return(u=o.Object)!=null&&u.ImmOrOwnedObject?s.coinObjectId===o.Object.ImmOrOwnedObject.objectId:!1})).map(s=>({objectId:s.coinObjectId,digest:s.digest,version:s.version}));if(!n.length)throw new Error("No valid gas coins found for the transaction.");r.gasConfig.payment=n.map(s=>M(ue,s))}}async function Si(r,e){const t=r.inputs.filter(l=>{var h;return l.UnresolvedObject&&!(l.UnresolvedObject.version||(h=l.UnresolvedObject)!=null&&h.initialSharedVersion)}),n=[...new Set(t.map(l=>ie(l.UnresolvedObject.objectId)))],s=n.length?ji(n,pi):[],i=(await Promise.all(s.map(l=>Je(e).multiGetObjects({ids:l,options:{showOwner:!0}})))).flat(),o=new Map(n.map((l,h)=>[l,i[h]])),u=Array.from(o).filter(([l,h])=>h.error).map(([l,h])=>JSON.stringify(h.error));if(u.length)throw new Error(`The following input objects are invalid: ${u.join(", ")}`);const c=i.map(l=>{if(l.error||!l.data)throw new Error(`Failed to fetch object: ${l.error}`);const h=l.data.owner,I=h&&typeof h=="object"&&"Shared"in h?h.Shared.initial_shared_version:null;return{objectId:l.data.objectId,digest:l.data.digest,version:l.data.version,initialSharedVersion:I}}),g=new Map(n.map((l,h)=>[l,c[h]]));for(const[l,h]of r.inputs.entries()){if(!h.UnresolvedObject)continue;let I;const O=k(h.UnresolvedObject.objectId),S=g.get(O);h.UnresolvedObject.initialSharedVersion??(S==null?void 0:S.initialSharedVersion)?I=ae.SharedObjectRef({objectId:O,initialSharedVersion:h.UnresolvedObject.initialSharedVersion||(S==null?void 0:S.initialSharedVersion),mutable:Oi(r,l)}):Ii(r,l)&&(I=ae.ReceivingRef({objectId:O,digest:h.UnresolvedObject.digest??(S==null?void 0:S.digest),version:h.UnresolvedObject.version??(S==null?void 0:S.version)})),r.inputs[r.inputs.indexOf(h)]=I??ae.ObjectRef({objectId:O,digest:h.UnresolvedObject.digest??(S==null?void 0:S.digest),version:h.UnresolvedObject.version??(S==null?void 0:S.version)})}}async function ki(r,e){const{inputs:t,commands:n}=r,s=[],i=new Set;n.forEach(u=>{if(u.MoveCall){if(u.MoveCall._argumentTypes)return;if(u.MoveCall.arguments.map(l=>l.$kind==="Input"?r.inputs[l.Input]:null).some(l=>(l==null?void 0:l.UnresolvedPure)||(l==null?void 0:l.UnresolvedObject))){const l=`${u.MoveCall.package}::${u.MoveCall.module}::${u.MoveCall.function}`;i.add(l),s.push(u.MoveCall)}}switch(u.$kind){case"SplitCoins":u.SplitCoins.amounts.forEach(c=>{sr(c,y.U64,r)});break;case"TransferObjects":sr(u.TransferObjects.address,y.Address,r);break}});const o=new Map;if(i.size>0){const u=Je(e);await Promise.all([...i].map(async c=>{const[g,l,h]=c.split("::"),I=await u.getNormalizedMoveFunction({package:g,module:l,function:h});o.set(c,I.parameters.map(O=>xs(O)))}))}s.length&&await Promise.all(s.map(async u=>{const c=o.get(`${u.package}::${u.module}::${u.function}`);if(!c)return;const l=c.length>0&&Ms(c.at(-1))?c.slice(0,c.length-1):c;u._argumentTypes=l})),n.forEach(u=>{if(!u.MoveCall)return;const c=u.MoveCall,g=`${c.package}::${c.module}::${c.function}`,l=c._argumentTypes;if(l){if(l.length!==u.MoveCall.arguments.length)throw new Error(`Incorrect number of arguments for ${g}`);l.forEach((h,I)=>{var Jt,Zt;const O=c.arguments[I];if(O.$kind!=="Input")return;const S=t[O.Input];if(!S.UnresolvedPure&&!S.UnresolvedObject)return;const Z=((Jt=S.UnresolvedPure)==null?void 0:Jt.value)??((Zt=S.UnresolvedObject)==null?void 0:Zt.objectId),Ce=Ot(h.body);if(Ce){O.type="pure",t[t.indexOf(S)]=ae.Pure(Ce.serialize(Z));return}if(typeof Z!="string")throw new Error(`Expect the argument to be an object id string, got ${JSON.stringify(Z,null,2)}`);O.type="object";const _e=S.UnresolvedPure?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:Z}}:S;t[O.Input]=_e})}})}function Ei(r){r.inputs.forEach((e,t)=>{if(e.$kind!=="Object"&&e.$kind!=="Pure")throw new Error(`Input at index ${t} has not been resolved. Expected a Pure or Object input, but found ${JSON.stringify(e)}`)})}function sr(r,e,t){if(r.$kind!=="Input")return;const n=t.inputs[r.Input];n.$kind==="UnresolvedPure"&&(t.inputs[r.Input]=ae.Pure(e.serialize(n.UnresolvedPure.value)))}function Oi(r,e){let t=!1;return r.getInputUses(e,(n,s)=>{if(s.MoveCall&&s.MoveCall._argumentTypes){const i=s.MoveCall.arguments.indexOf(n);t=s.MoveCall._argumentTypes[i].ref!=="&"||t}(s.$kind==="MakeMoveVec"||s.$kind==="MergeCoins"||s.$kind==="SplitCoins")&&(t=!0)}),t}function Ii(r,e){let t=!1;return r.getInputUses(e,(n,s)=>{if(s.MoveCall&&s.MoveCall._argumentTypes){const i=s.MoveCall.arguments.indexOf(n);t=Ti(s.MoveCall._argumentTypes[i])||t}}),t}function Ti(r){return typeof r.body!="object"||!("datatype"in r.body)?!1:r.body.datatype.package==="0x2"&&r.body.datatype.module==="transfer"&&r.body.datatype.type==="Receiving"}function Je(r){if(!r.client)throw new Error("No sui client passed to Transaction#build, but transaction data was not sufficient to build offline.");return r.client}function ji(r,e){return Array.from({length:Math.ceil(r.length/e)},(t,n)=>r.slice(n*e,n*e+e))}function Ci(r){function e(t){return r(t)}return e.system=()=>e("0x5"),e.clock=()=>e("0x6"),e.random=()=>e("0x8"),e.denyList=()=>e("0x403"),e.option=({type:t,value:n})=>s=>s.moveCall({typeArguments:[t],target:`0x1::option::${n===null?"none":"some"}`,arguments:n===null?[]:[s.object(n)]}),e}function _i(r){function e(t,n){if(typeof t=="string")return r($e(t).serialize(n));if(t instanceof Uint8Array||Ut(t))return r(t);throw new Error("tx.pure must be called either a bcs type name, or a serialized bcs value")}return e.u8=t=>r(y.U8.serialize(t)),e.u16=t=>r(y.U16.serialize(t)),e.u32=t=>r(y.U32.serialize(t)),e.u64=t=>r(y.U64.serialize(t)),e.u128=t=>r(y.U128.serialize(t)),e.u256=t=>r(y.U256.serialize(t)),e.bool=t=>r(y.Bool.serialize(t)),e.string=t=>r(y.String.serialize(t)),e.address=t=>r(y.Address.serialize(t)),e.id=e.address,e.vector=(t,n)=>r(y.vector($e(t)).serialize(n)),e.option=(t,n)=>r(y.option($e(t)).serialize(n)),e}function Mi(r,e){const t=Array.from(`${r}::`).map(s=>s.charCodeAt(0)),n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),st(n,{dkLen:32})}function ir(r){return k(r).replace("0x","")}class F{constructor(e){this.version=2,this.sender=(e==null?void 0:e.sender)??null,this.expiration=(e==null?void 0:e.expiration)??null,this.inputs=(e==null?void 0:e.inputs)??[],this.commands=(e==null?void 0:e.commands)??[],this.gasData=(e==null?void 0:e.gasData)??{budget:null,price:null,owner:null,payment:null}}static fromKindBytes(e){const n=y.TransactionKind.parse(e).ProgrammableTransaction;if(!n)throw new Error("Unable to deserialize from bytes.");return F.restore({version:2,sender:null,expiration:null,gasData:{budget:null,owner:null,payment:null,price:null},inputs:n.inputs,commands:n.commands})}static fromBytes(e){const t=y.TransactionData.parse(e),n=t==null?void 0:t.V1,s=n.kind.ProgrammableTransaction;if(!n||!s)throw new Error("Unable to deserialize from bytes.");return F.restore({version:2,sender:n.sender,expiration:n.expiration,gasData:n.gasData,inputs:s.inputs,commands:s.commands})}static restore(e){return e.version===2?new F(M(et,e)):new F(M(et,ii(e)))}static getDigestFromBytes(e){const t=Mi("TransactionData",e);return Pt(t)}get gasConfig(){return this.gasData}set gasConfig(e){this.gasData=e}build({maxSizeBytes:e=1/0,overrides:t,onlyTransactionKind:n}={}){const s=this.inputs,i=this.commands,o={ProgrammableTransaction:{inputs:s,commands:i}};if(n)return y.TransactionKind.serialize(o,{maxSize:e}).toBytes();const u=(t==null?void 0:t.expiration)??this.expiration,c=(t==null?void 0:t.sender)??this.sender,g={...this.gasData,...t==null?void 0:t.gasConfig,...t==null?void 0:t.gasData};if(!c)throw new Error("Missing transaction sender");if(!g.budget)throw new Error("Missing gas budget");if(!g.payment)throw new Error("Missing gas payment");if(!g.price)throw new Error("Missing gas price");const l={sender:ir(c),expiration:u||{None:!0},gasData:{payment:g.payment,owner:ir(this.gasData.owner??c),price:BigInt(g.price),budget:BigInt(g.budget)},kind:{ProgrammableTransaction:{inputs:s,commands:i}}};return y.TransactionData.serialize({V1:l},{maxSize:e}).toBytes()}addInput(e,t){const n=this.inputs.length;return this.inputs.push(t),{Input:n,type:e,$kind:"Input"}}getInputUses(e,t){this.mapArguments((n,s)=>(n.$kind==="Input"&&n.Input===e&&t(n,s),n))}mapArguments(e){for(const t of this.commands)switch(t.$kind){case"MoveCall":t.MoveCall.arguments=t.MoveCall.arguments.map(s=>e(s,t));break;case"TransferObjects":t.TransferObjects.objects=t.TransferObjects.objects.map(s=>e(s,t)),t.TransferObjects.address=e(t.TransferObjects.address,t);break;case"SplitCoins":t.SplitCoins.coin=e(t.SplitCoins.coin,t),t.SplitCoins.amounts=t.SplitCoins.amounts.map(s=>e(s,t));break;case"MergeCoins":t.MergeCoins.destination=e(t.MergeCoins.destination,t),t.MergeCoins.sources=t.MergeCoins.sources.map(s=>e(s,t));break;case"MakeMoveVec":t.MakeMoveVec.elements=t.MakeMoveVec.elements.map(s=>e(s,t));break;case"Upgrade":t.Upgrade.ticket=e(t.Upgrade.ticket,t);break;case"$Intent":const n=t.$Intent.inputs;t.$Intent.inputs={};for(const[s,i]of Object.entries(n))t.$Intent.inputs[s]=Array.isArray(i)?i.map(o=>e(o,t)):e(i,t);break;case"Publish":break;default:throw new Error(`Unexpected transaction kind: ${t.$kind}`)}}replaceCommand(e,t){if(!Array.isArray(t)){this.commands[e]=t;return}const n=t.length-1;this.commands.splice(e,1,...t),n!==0&&this.mapArguments(s=>{switch(s.$kind){case"Result":s.Result>e&&(s.Result+=n);break;case"NestedResult":s.NestedResult[0]>e&&(s.NestedResult[0]+=n);break}return s})}getDigest(){const e=this.build({onlyTransactionKind:!1});return F.getDigestFromBytes(e)}snapshot(){return M(et,this)}}function ar(r){if(typeof r=="string")return k(r);if(r.Object)return r.Object.ImmOrOwnedObject?k(r.Object.ImmOrOwnedObject.objectId):r.Object.Receiving?k(r.Object.Receiving.objectId):k(r.Object.SharedObject.objectId);if(r.UnresolvedObject)return k(r.UnresolvedObject.objectId)}var nn=r=>{throw TypeError(r)},Kt=(r,e,t)=>e.has(r)||nn("Cannot "+t),b=(r,e,t)=>(Kt(r,e,"read from private field"),t?t.call(r):e.get(r)),Me=(r,e,t)=>e.has(r)?nn("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),fe=(r,e,t,n)=>(Kt(r,e,"write to private field"),e.set(r,t),t),te=(r,e,t)=>(Kt(r,e,"access private method"),t),Ue,De,ge,w,q,tt,Ft,Ct,Lt;function or(r,e=1/0){const t={$kind:"Result",Result:r},n=[],s=i=>n[i]??(n[i]={$kind:"NestedResult",NestedResult:[r,i]});return new Proxy(t,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(i,o){if(o in i)return Reflect.get(i,o);if(o===Symbol.iterator)return function*(){let c=0;for(;c<e;)yield s(c),c++};if(typeof o=="symbol")return;const u=parseInt(o,10);if(!(Number.isNaN(u)||u<0))return s(u)}})}const sn=Symbol.for("@mysten/transaction");function an(r){return!!r&&typeof r=="object"&&r[sn]===!0}const cr={buildPlugins:new Map,serializationPlugins:new Map},St=Symbol.for("@mysten/transaction/registry");function xe(){try{const r=globalThis;return r[St]||(r[St]=cr),r[St]}catch{return cr}}const xi=class _t{constructor(){Me(this,q),Me(this,Ue),Me(this,De),Me(this,ge,new Map),Me(this,w),this.object=Ci(t=>{var i,o;if(typeof t=="function")return this.object(t(this));if(typeof t=="object"&&It(T,t))return t;const n=ar(t),s=b(this,w).inputs.find(u=>n===ar(u));return(i=s==null?void 0:s.Object)!=null&&i.SharedObject&&typeof t=="object"&&((o=t.Object)!=null&&o.SharedObject)&&(s.Object.SharedObject.mutable=s.Object.SharedObject.mutable||t.Object.SharedObject.mutable),s?{$kind:"Input",Input:b(this,w).inputs.indexOf(s),type:"object"}:b(this,w).addInput("object",typeof t=="string"?{$kind:"UnresolvedObject",UnresolvedObject:{objectId:k(t)}}:t)});const e=xe();fe(this,w,new F),fe(this,De,[...e.buildPlugins.values()]),fe(this,Ue,[...e.serializationPlugins.values()])}static fromKind(e){const t=new _t;return fe(t,w,F.fromKindBytes(typeof e=="string"?z(e):e)),t}static from(e){const t=new _t;return an(e)?fe(t,w,new F(e.getData())):typeof e!="string"||!e.startsWith("{")?fe(t,w,F.fromBytes(typeof e=="string"?z(e):e)):fe(t,w,F.restore(JSON.parse(e))),t}static registerGlobalSerializationPlugin(e,t){xe().serializationPlugins.set(e,t??e)}static unregisterGlobalSerializationPlugin(e){xe().serializationPlugins.delete(e)}static registerGlobalBuildPlugin(e,t){xe().buildPlugins.set(e,t??e)}static unregisterGlobalBuildPlugin(e){xe().buildPlugins.delete(e)}addSerializationPlugin(e){b(this,Ue).push(e)}addBuildPlugin(e){b(this,De).push(e)}addIntentResolver(e,t){if(b(this,ge).has(e)&&b(this,ge).get(e)!==t)throw new Error(`Intent resolver for ${e} already exists`);b(this,ge).set(e,t)}setSender(e){b(this,w).sender=e}setSenderIfNotSet(e){b(this,w).sender||(b(this,w).sender=e)}setExpiration(e){b(this,w).expiration=e?M(tn,e):null}setGasPrice(e){b(this,w).gasConfig.price=String(e)}setGasBudget(e){b(this,w).gasConfig.budget=String(e)}setGasBudgetIfNotSet(e){b(this,w).gasData.budget==null&&(b(this,w).gasConfig.budget=String(e))}setGasOwner(e){b(this,w).gasConfig.owner=e}setGasPayment(e){b(this,w).gasConfig.payment=e.map(t=>M(ue,t))}get blockData(){return nr(b(this,w).snapshot())}getData(){return b(this,w).snapshot()}get[sn](){return!0}get pure(){return Object.defineProperty(this,"pure",{enumerable:!1,value:_i(e=>Ut(e)?b(this,w).addInput("pure",{$kind:"Pure",Pure:{bytes:e.toBase64()}}):b(this,w).addInput("pure",It(er,e)?M(er,e):e instanceof Uint8Array?ae.Pure(e):{$kind:"UnresolvedPure",UnresolvedPure:{value:e}}))}),this.pure}get gas(){return{$kind:"GasCoin",GasCoin:!0}}objectRef(...e){return this.object(ae.ObjectRef(...e))}receivingRef(...e){return this.object(ae.ReceivingRef(...e))}sharedObjectRef(...e){return this.object(ae.SharedObjectRef(...e))}add(e){if(typeof e=="function")return e(this);const t=b(this,w).commands.push(e);return or(t-1)}splitCoins(e,t){const n=he.SplitCoins(typeof e=="string"?this.object(e):te(this,q,Ft).call(this,e),t.map(i=>typeof i=="number"||typeof i=="bigint"||typeof i=="string"?this.pure.u64(i):te(this,q,tt).call(this,i))),s=b(this,w).commands.push(n);return or(s-1,t.length)}mergeCoins(e,t){return this.add(he.MergeCoins(this.object(e),t.map(n=>this.object(n))))}publish({modules:e,dependencies:t}){return this.add(he.Publish({modules:e,dependencies:t}))}upgrade({modules:e,dependencies:t,package:n,ticket:s}){return this.add(he.Upgrade({modules:e,dependencies:t,package:n,ticket:this.object(s)}))}moveCall({arguments:e,...t}){return this.add(he.MoveCall({...t,arguments:e==null?void 0:e.map(n=>te(this,q,tt).call(this,n))}))}transferObjects(e,t){return this.add(he.TransferObjects(e.map(n=>this.object(n)),typeof t=="string"?this.pure.address(t):te(this,q,tt).call(this,t)))}makeMoveVec({type:e,elements:t}){return this.add(he.MakeMoveVec({type:e,elements:t.map(n=>this.object(n))}))}serialize(){return JSON.stringify(nr(b(this,w).snapshot()))}async toJSON(e={}){return await this.prepareForSerialization(e),JSON.stringify(M(fi,b(this,w).snapshot()),(t,n)=>typeof n=="bigint"?n.toString():n,2)}async sign(e){const{signer:t,...n}=e,s=await this.build(n);return t.signTransaction(s)}async build(e={}){return await this.prepareForSerialization(e),await te(this,q,Ct).call(this,e),b(this,w).build({onlyTransactionKind:e.onlyTransactionKind})}async getDigest(e={}){return await te(this,q,Ct).call(this,e),b(this,w).getDigest()}async prepareForSerialization(e){var s;const t=new Set;for(const i of b(this,w).commands)i.$Intent&&t.add(i.$Intent.name);const n=[...b(this,Ue)];for(const i of t)if(!((s=e.supportedIntents)!=null&&s.includes(i))){if(!b(this,ge).has(i))throw new Error(`Missing intent resolver for ${i}`);n.push(b(this,ge).get(i))}await te(this,q,Lt).call(this,n,e)}};Ue=new WeakMap;De=new WeakMap;ge=new WeakMap;w=new WeakMap;q=new WeakSet;tt=function(r){return Ut(r)?this.pure(r):te(this,q,Ft).call(this,r)};Ft=function(r){return typeof r=="function"?M(T,r(this)):M(T,r)};Ct=async function(r){if(!r.onlyTransactionKind&&!b(this,w).sender)throw new Error("Missing transaction sender");await te(this,q,Lt).call(this,[...b(this,De),yi],r)};Lt=async function(r,e){const t=n=>{if(n>=r.length)return()=>{};const s=r[n];return async()=>{const i=t(n+1);let o=!1,u=!1;if(await s(b(this,w),e,async()=>{if(o)throw new Error(`next() was call multiple times in TransactionPlugin ${n}`);o=!0,await i(),u=!0}),!o)throw new Error(`next() was not called in TransactionPlugin ${n}`);if(!u)throw new Error(`next() was not awaited in TransactionPlugin ${n}`)}};await t(0)()};let ua=xi;const Ai=Symbol.for("@mysten/SuiClient");class Pi{get[Ai](){return!0}constructor(e){this.transport=e.transport??new Ss({url:e.url})}async getRpcApiVersion(){return(await this.transport.request({method:"rpc.discover",params:[]})).info.version}async getCoins(e){if(!e.owner||!ne(k(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getCoins",params:[e.owner,e.coinType,e.cursor,e.limit]})}async getAllCoins(e){if(!e.owner||!ne(k(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllCoins",params:[e.owner,e.cursor,e.limit]})}async getBalance(e){if(!e.owner||!ne(k(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getBalance",params:[e.owner,e.coinType]})}async getAllBalances(e){if(!e.owner||!ne(k(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getAllBalances",params:[e.owner]})}async getCoinMetadata(e){return await this.transport.request({method:"suix_getCoinMetadata",params:[e.coinType]})}async getTotalSupply(e){return await this.transport.request({method:"suix_getTotalSupply",params:[e.coinType]})}async call(e,t){return await this.transport.request({method:e,params:t})}async getMoveFunctionArgTypes(e){return await this.transport.request({method:"sui_getMoveFunctionArgTypes",params:[e.package,e.module,e.function]})}async getNormalizedMoveModulesByPackage(e){return await this.transport.request({method:"sui_getNormalizedMoveModulesByPackage",params:[e.package]})}async getNormalizedMoveModule(e){return await this.transport.request({method:"sui_getNormalizedMoveModule",params:[e.package,e.module]})}async getNormalizedMoveFunction(e){return await this.transport.request({method:"sui_getNormalizedMoveFunction",params:[e.package,e.module,e.function]})}async getNormalizedMoveStruct(e){return await this.transport.request({method:"sui_getNormalizedMoveStruct",params:[e.package,e.module,e.struct]})}async getOwnedObjects(e){if(!e.owner||!ne(k(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getOwnedObjects",params:[e.owner,{filter:e.filter,options:e.options},e.cursor,e.limit]})}async getObject(e){if(!e.id||!Ze(ie(e.id)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"sui_getObject",params:[e.id,e.options]})}async tryGetPastObject(e){return await this.transport.request({method:"sui_tryGetPastObject",params:[e.id,e.version,e.options]})}async multiGetObjects(e){if(e.ids.forEach(n=>{if(!n||!Ze(ie(n)))throw new Error(`Invalid Sui Object id ${n}`)}),e.ids.length!==new Set(e.ids).size)throw new Error(`Duplicate object ids in batch call ${e.ids}`);return await this.transport.request({method:"sui_multiGetObjects",params:[e.ids,e.options]})}async queryTransactionBlocks(e){return await this.transport.request({method:"suix_queryTransactionBlocks",params:[{filter:e.filter,options:e.options},e.cursor,e.limit,(e.order||"descending")==="descending"]})}async getTransactionBlock(e){if(!Yt(e.digest))throw new Error("Invalid Transaction digest");return await this.transport.request({method:"sui_getTransactionBlock",params:[e.digest,e.options]})}async multiGetTransactionBlocks(e){if(e.digests.forEach(n=>{if(!Yt(n))throw new Error(`Invalid Transaction digest ${n}`)}),e.digests.length!==new Set(e.digests).size)throw new Error(`Duplicate digests in batch call ${e.digests}`);return await this.transport.request({method:"sui_multiGetTransactionBlocks",params:[e.digests,e.options]})}async executeTransactionBlock({transactionBlock:e,signature:t,options:n,requestType:s}){const i=await this.transport.request({method:"sui_executeTransactionBlock",params:[typeof e=="string"?e:A(e),Array.isArray(t)?t:[t],n]});if(s==="WaitForLocalExecution")try{await this.waitForTransaction({digest:i.digest})}catch{}return i}async signAndExecuteTransaction({transaction:e,signer:t,...n}){let s;e instanceof Uint8Array?s=e:(e.setSenderIfNotSet(t.toSuiAddress()),s=await e.build({client:this}));const{signature:i,bytes:o}=await t.signTransaction(s);return this.executeTransactionBlock({transactionBlock:o,signature:i,...n})}async getTotalTransactionBlocks(){const e=await this.transport.request({method:"sui_getTotalTransactionBlocks",params:[]});return BigInt(e)}async getReferenceGasPrice(){const e=await this.transport.request({method:"suix_getReferenceGasPrice",params:[]});return BigInt(e)}async getStakes(e){if(!e.owner||!ne(k(e.owner)))throw new Error("Invalid Sui address");return await this.transport.request({method:"suix_getStakes",params:[e.owner]})}async getStakesByIds(e){return e.stakedSuiIds.forEach(t=>{if(!t||!Ze(ie(t)))throw new Error(`Invalid Sui Stake id ${t}`)}),await this.transport.request({method:"suix_getStakesByIds",params:[e.stakedSuiIds]})}async getLatestSuiSystemState(){return await this.transport.request({method:"suix_getLatestSuiSystemState",params:[]})}async queryEvents(e){return await this.transport.request({method:"suix_queryEvents",params:[e.query,e.cursor,e.limit,(e.order||"descending")==="descending"]})}async subscribeEvent(e){return this.transport.subscribe({method:"suix_subscribeEvent",unsubscribe:"suix_unsubscribeEvent",params:[e.filter],onMessage:e.onMessage})}async subscribeTransaction(e){return this.transport.subscribe({method:"suix_subscribeTransaction",unsubscribe:"suix_unsubscribeTransaction",params:[e.filter],onMessage:e.onMessage})}async devInspectTransactionBlock(e){var n;let t;if(an(e.transactionBlock))e.transactionBlock.setSenderIfNotSet(e.sender),t=A(await e.transactionBlock.build({client:this,onlyTransactionKind:!0}));else if(typeof e.transactionBlock=="string")t=e.transactionBlock;else if(e.transactionBlock instanceof Uint8Array)t=A(e.transactionBlock);else throw new Error("Unknown transaction block format.");return await this.transport.request({method:"sui_devInspectTransactionBlock",params:[e.sender,t,(n=e.gasPrice)==null?void 0:n.toString(),e.epoch]})}async dryRunTransactionBlock(e){return await this.transport.request({method:"sui_dryRunTransactionBlock",params:[typeof e.transactionBlock=="string"?e.transactionBlock:A(e.transactionBlock)]})}async getDynamicFields(e){if(!e.parentId||!Ze(ie(e.parentId)))throw new Error("Invalid Sui Object id");return await this.transport.request({method:"suix_getDynamicFields",params:[e.parentId,e.cursor,e.limit]})}async getDynamicFieldObject(e){return await this.transport.request({method:"suix_getDynamicFieldObject",params:[e.parentId,e.name]})}async getLatestCheckpointSequenceNumber(){const e=await this.transport.request({method:"sui_getLatestCheckpointSequenceNumber",params:[]});return String(e)}async getCheckpoint(e){return await this.transport.request({method:"sui_getCheckpoint",params:[e.id]})}async getCheckpoints(e){return await this.transport.request({method:"sui_getCheckpoints",params:[e.cursor,e==null?void 0:e.limit,e.descendingOrder]})}async getCommitteeInfo(e){return await this.transport.request({method:"suix_getCommitteeInfo",params:[e==null?void 0:e.epoch]})}async getNetworkMetrics(){return await this.transport.request({method:"suix_getNetworkMetrics",params:[]})}async getAddressMetrics(){return await this.transport.request({method:"suix_getLatestAddressMetrics",params:[]})}async getEpochMetrics(e){return await this.transport.request({method:"suix_getEpochMetrics",params:[e==null?void 0:e.cursor,e==null?void 0:e.limit,e==null?void 0:e.descendingOrder]})}async getAllEpochAddressMetrics(e){return await this.transport.request({method:"suix_getAllEpochAddressMetrics",params:[e==null?void 0:e.descendingOrder]})}async getEpochs(e){return await this.transport.request({method:"suix_getEpochs",params:[e==null?void 0:e.cursor,e==null?void 0:e.limit,e==null?void 0:e.descendingOrder]})}async getMoveCallMetrics(){return await this.transport.request({method:"suix_getMoveCallMetrics",params:[]})}async getCurrentEpoch(){return await this.transport.request({method:"suix_getCurrentEpoch",params:[]})}async getValidatorsApy(){return await this.transport.request({method:"suix_getValidatorsApy",params:[]})}async getChainIdentifier(){const e=await this.getCheckpoint({id:"0"}),t=nt(e.digest);return ze(t.slice(0,4))}async resolveNameServiceAddress(e){return await this.transport.request({method:"suix_resolveNameServiceAddress",params:[e.name]})}async resolveNameServiceNames({format:e="dot",...t}){const{nextCursor:n,hasNextPage:s,data:i}=await this.transport.request({method:"suix_resolveNameServiceNames",params:[t.address,t.cursor,t.limit]});return{hasNextPage:s,nextCursor:n,data:i.map(o=>Vn(o,e))}}async getProtocolConfig(e){return await this.transport.request({method:"sui_getProtocolConfig",params:[e==null?void 0:e.version]})}async waitForTransaction({signal:e,timeout:t=60*1e3,pollInterval:n=2*1e3,...s}){const i=AbortSignal.timeout(t),o=new Promise((u,c)=>{i.addEventListener("abort",()=>c(i.reason))});for(o.catch(()=>{});!i.aborted;){e==null||e.throwIfAborted();try{return await this.getTransactionBlock(s)}catch{await Promise.race([new Promise(c=>setTimeout(c,n)),o])}}throw i.throwIfAborted(),new Error("Unexpected error while waiting for transaction block.")}}var Ke={};Object.defineProperty(Ke,"__esModule",{value:!0});Ke.bech32m=Fe=Ke.bech32=void 0;const lt="qpzry9x8gf2tvdw0s3jn54khce6mua7l",on={};for(let r=0;r<lt.length;r++){const e=lt.charAt(r);on[e]=r}function Ie(r){const e=r>>25;return(r&33554431)<<5^-(e>>0&1)&996825010^-(e>>1&1)&642813549^-(e>>2&1)&513874426^-(e>>3&1)&1027748829^-(e>>4&1)&705979059}function ur(r){let e=1;for(let t=0;t<r.length;++t){const n=r.charCodeAt(t);if(n<33||n>126)return"Invalid prefix ("+r+")";e=Ie(e)^n>>5}e=Ie(e);for(let t=0;t<r.length;++t){const n=r.charCodeAt(t);e=Ie(e)^n&31}return e}function Wt(r,e,t,n){let s=0,i=0;const o=(1<<t)-1,u=[];for(let c=0;c<r.length;++c)for(s=s<<e|r[c],i+=e;i>=t;)i-=t,u.push(s>>i&o);if(n)i>0&&u.push(s<<t-i&o);else{if(i>=e)return"Excess padding";if(s<<t-i&o)return"Non-zero padding"}return u}function Ui(r){return Wt(r,8,5,!0)}function $i(r){const e=Wt(r,5,8,!1);if(Array.isArray(e))return e}function Bi(r){const e=Wt(r,5,8,!1);if(Array.isArray(e))return e;throw new Error(e)}function cn(r){let e;r==="bech32"?e=1:e=734539939;function t(o,u,c){if(c=c||90,o.length+7+u.length>c)throw new TypeError("Exceeds length limit");o=o.toLowerCase();let g=ur(o);if(typeof g=="string")throw new Error(g);let l=o+"1";for(let h=0;h<u.length;++h){const I=u[h];if(I>>5)throw new Error("Non 5-bit word");g=Ie(g)^I,l+=lt.charAt(I)}for(let h=0;h<6;++h)g=Ie(g);g^=e;for(let h=0;h<6;++h){const I=g>>(5-h)*5&31;l+=lt.charAt(I)}return l}function n(o,u){if(u=u||90,o.length<8)return o+" too short";if(o.length>u)return"Exceeds length limit";const c=o.toLowerCase(),g=o.toUpperCase();if(o!==c&&o!==g)return"Mixed-case string "+o;o=c;const l=o.lastIndexOf("1");if(l===-1)return"No separator character for "+o;if(l===0)return"Missing prefix for "+o;const h=o.slice(0,l),I=o.slice(l+1);if(I.length<6)return"Data too short";let O=ur(h);if(typeof O=="string")return O;const S=[];for(let Z=0;Z<I.length;++Z){const Ce=I.charAt(Z),_e=on[Ce];if(_e===void 0)return"Unknown character "+Ce;O=Ie(O)^_e,!(Z+6>=I.length)&&S.push(_e)}return O!==e?"Invalid checksum for "+o:{prefix:h,words:S}}function s(o,u){const c=n(o,u);if(typeof c=="object")return c}function i(o,u){const c=n(o,u);if(typeof c=="object")return c;throw new Error(c)}return{decodeUnsafe:s,decode:i,encode:t,toWords:Ui,fromWordsUnsafe:$i,fromWords:Bi}}var Fe=Ke.bech32=cn("bech32");Ke.bech32m=cn("bech32m");function un(r,e){return y.IntentMessage(y.fixedArray(e.length,y.u8())).serialize({intent:{scope:{[r]:!0},version:{V0:!0},appId:{Sui:!0}},value:e}).toBytes()}const Ht={ED25519:0,Secp256k1:1,Secp256r1:2,MultiSig:3,ZkLogin:5,Passkey:6},Ri={ED25519:32,Secp256k1:33,Secp256r1:33},ln={0:"ED25519",1:"Secp256k1",2:"Secp256r1",3:"MultiSig",5:"ZkLogin",6:"Passkey"};function dn(r,e){if(r===e)return!0;if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}class Ni{equals(e){return dn(this.toRawBytes(),e.toRawBytes())}toBase64(){return A(this.toRawBytes())}toString(){throw new Error("`toString` is not implemented on public keys. Use `toBase64()` or `toRawBytes()` instead.")}toSuiPublicKey(){const e=this.toSuiBytes();return A(e)}verifyWithIntent(e,t,n){const s=un(n,e),i=st(s,{dkLen:32});return this.verify(i,t)}verifyPersonalMessage(e,t){return this.verifyWithIntent(y.vector(y.u8()).serialize(e).toBytes(),t,"PersonalMessage")}verifyTransaction(e,t){return this.verifyWithIntent(e,t,"TransactionData")}verifyAddress(e){return this.toSuiAddress()===e}toSuiBytes(){const e=this.toRawBytes(),t=new Uint8Array(e.length+1);return t.set([this.flag()]),t.set(e,1),t}toSuiAddress(){return k(vn(st(this.toSuiBytes(),{dkLen:32})).slice(0,fr*2))}}function Di(r){const e=z(r),t=ln[e[0]];switch(t){case"ED25519":case"Secp256k1":case"Secp256r1":const n=Ri[t],s=e.slice(1,e.length-n),i=e.slice(1+s.length);return{serializedSignature:r,signatureScheme:t,signature:s,publicKey:i,bytes:e};default:throw new Error("Unsupported signature scheme")}}function zi({signature:r,signatureScheme:e,publicKey:t}){if(!t)throw new Error("`publicKey` is required");const n=t.toRawBytes(),s=new Uint8Array(1+r.length+n.length);return s.set([Ht[e]]),s.set(r,1),s.set(n,1+r.length),A(s)}const rt=32,hn="suiprivkey";class Vi{async signWithIntent(e,t){const n=un(t,e),s=st(n,{dkLen:32});return{signature:zi({signature:await this.sign(s),signatureScheme:this.getKeyScheme(),publicKey:this.getPublicKey()}),bytes:A(e)}}async signTransaction(e){return this.signWithIntent(e,"TransactionData")}async signPersonalMessage(e){const{signature:t}=await this.signWithIntent(a.vector(a.u8()).serialize(e).toBytes(),"PersonalMessage");return{bytes:A(e),signature:t}}toSuiAddress(){return this.getPublicKey().toSuiAddress()}}class qi extends Vi{}function Gi(r){const{prefix:e,words:t}=Fe.decode(r);if(e!==hn)throw new Error("invalid private key prefix");const n=new Uint8Array(Fe.fromWords(t)),s=n.slice(1);return{schema:ln[n[0]],secretKey:s}}function Ki(r,e){if(r.length!==rt)throw new Error("Invalid bytes length");const t=Ht[e],n=new Uint8Array(r.length+1);return n.set([t]),n.set(r,1),Fe.encode(hn,Fe.toWords(n))}function lr(r){return!!new RegExp("^m\\/44'\\/784'\\/[0-9]+'\\/[0-9]+'\\/[0-9]+'+$").test(r)}function Fi(r){return Mn(r,"")}function Li(r){return ze(Fi(r))}const Wi="ed25519 seed",Hi=2147483648,Ji=new RegExp("^m(\\/[0-9]+')+$"),fn=r=>r.replace("'",""),Zi=r=>{const t=pr.create(gr,Wi).update(At(r)).digest(),n=t.slice(0,32),s=t.slice(32);return{key:n,chainCode:s}},Yi=({key:r,chainCode:e},t)=>{const n=new ArrayBuffer(4);new DataView(n).setUint32(0,t);const i=new Uint8Array(1+r.length+n.byteLength);i.set(new Uint8Array(1).fill(0)),i.set(r,1),i.set(new Uint8Array(n,0,n.byteLength),r.length+1);const o=pr.create(gr,e).update(i).digest(),u=o.slice(0,32),c=o.slice(32);return{key:u,chainCode:c}},Xi=r=>Ji.test(r)?!r.split("/").slice(1).map(fn).some(isNaN):!1,dr=(r,e,t=Hi)=>{if(!Xi(r))throw new Error("Invalid derivation path");const{key:n,chainCode:s}=Zi(e);return r.split("/").slice(1).map(fn).map(o=>parseInt(o,10)).reduce((o,u)=>Yi(o,u+t),{key:n,chainCode:s})},Mt=32;class pn extends Ni{constructor(e){if(super(),typeof e=="string"?this.data=z(e):e instanceof Uint8Array?this.data=e:this.data=Uint8Array.from(e),this.data.length!==Mt)throw new Error(`Invalid public key input. Expected ${Mt} bytes, got ${this.data.length}`)}equals(e){return super.equals(e)}toRawBytes(){return this.data}flag(){return Ht.ED25519}async verify(e,t){let n;if(typeof t=="string"){const s=Di(t);if(s.signatureScheme!=="ED25519")throw new Error("Invalid signature scheme");if(!dn(this.toRawBytes(),s.publicKey))throw new Error("Signature does not match public key");n=s.signature}else n=t;return ee.verify(n,e,this.toRawBytes())}}pn.SIZE=Mt;const hr="m/44'/784'/0'/0'/0'";class ke extends qi{constructor(e){if(super(),e)this.keypair={publicKey:e.publicKey,secretKey:e.secretKey.slice(0,32)};else{const t=ee.utils.randomPrivateKey();this.keypair={publicKey:ee.getPublicKey(t),secretKey:t}}}getKeyScheme(){return"ED25519"}static generate(){const e=ee.utils.randomPrivateKey();return new ke({publicKey:ee.getPublicKey(e),secretKey:e})}static fromSecretKey(e,t){if(typeof e=="string"){const i=Gi(e);if(i.schema!=="ED25519")throw new Error(`Expected a ED25519 keypair, got ${i.schema}`);return this.fromSecretKey(i.secretKey,t)}const n=e.length;if(n!==rt)throw new Error(`Wrong secretKey size. Expected ${rt} bytes, got ${n}.`);const s={publicKey:ee.getPublicKey(e),secretKey:e};if(!t||!t.skipValidation){const o=new TextEncoder().encode("sui validation"),u=ee.sign(o,e);if(!ee.verify(u,o,s.publicKey))throw new Error("provided secretKey is invalid")}return new ke(s)}getPublicKey(){return new pn(this.keypair.publicKey)}getSecretKey(){return Ki(this.keypair.secretKey.slice(0,rt),this.getKeyScheme())}async sign(e){return ee.sign(e,this.keypair.secretKey)}static deriveKeypair(e,t){if(t==null&&(t=hr),!lr(t))throw new Error("Invalid derivation path");const{key:n}=dr(t,Li(e));return ke.fromSecretKey(n)}static deriveKeypairFromSeed(e,t){if(t==null&&(t=hr),!lr(t))throw new Error("Invalid derivation path");const{key:n}=dr(t,e);return ke.fromSecretKey(n)}}class gn extends Sn{}const xt="Sui",Qi=r=>{var t;const e=(t=r.data)==null?void 0:t.content;return e&&e.dataType==="moveObject"?e.fields:null},ea=async(r,e)=>{if(!ne(e))throw new Error(`Invalid object ID: ${e}`);const t=await r.getObject({id:e,options:{showContent:!0}});return Qi(t)},re=class re extends kn{constructor(e,t){super(e,t??En(e,re._platform))}getRpc(e){if(e in this.config)return new Pi({url:this.config[e].rpc});throw new Error("No configuration available for chain: "+e)}getChain(e){if(e in this.config)return new gn(e,this);throw new Error("No configuration available for chain: "+e)}static nativeTokenId(e,t){if(!re.isSupportedChain(t))throw new Error(`invalid chain for ${xt}: ${t}`);return On.tokenId(t,In)}static isNativeTokenId(e,t,n){return!re.isSupportedChain(t)||n.chain!==t?!1:this.nativeTokenId(e,t)===n}static isSupportedChain(e){return Tn(e)===re._platform}static async getDecimals(e,t,n){if(ft(n))return jn(re._platform);const s=new Xe(n);try{const o=await ea(t,s.toString());if(o&&"decimals"in o)return o.decimals}catch{}const i=await t.getCoinMetadata({coinType:s.toString()});if(i===null)throw new Error(`Can't fetch decimals for token ${s.toString()}`);return i.decimals}static async getCoins(e,t,n){let s=[],i=null;const o=new Xe(t).toString();do{const u=await e.getCoins({owner:o,coinType:n,cursor:i});s=[...s,...u.data],i=u.hasNextPage?u.nextCursor:null}while(i);return s}static async getBalance(e,t,n,s){if(ft(s)){const{totalBalance:o}=await t.getBalance({owner:n});return BigInt(o)}const{totalBalance:i}=await t.getBalance({owner:n,coinType:s.toString()});return BigInt(i)}static async getBalances(e,t,n,s){return(await Promise.all(s.map(async o=>{const u=await this.getBalance(e,t,n,o);return{[ft(o)?"native":new Xe(o).toString()]:u}}))).reduce((o,u)=>Object.assign(o,u),{})}static async sendWait(e,t,n){const s=[];for(const i of n){const o=await t.executeTransactionBlock(i);await t.waitForTransaction({digest:o.digest}),s.push(o.digest)}return s}static async getLatestBlock(e){return Number(await e.getLatestCheckpointSequenceNumber())}static async getLatestFinalizedBlock(e){return this.getLatestBlock(e)}static chainFromChainId(e){const t=Cn(re._platform,e);if(t===void 0)throw new Error(`Unknown native chain id ${e}`);const[n,s]=t;return[n,s]}static async chainFromRpc(e){const t=await e.call("sui_getChainIdentifier",[]);return this.chainFromChainId(t)}};le(re,"_platform",xt);let Le=re;async function ta(r,e){const[,t]=await Le.chainFromRpc(r);return new ra(t,r,ke.deriveKeypair(e,"m/44'/784'/0'/0'/0'"))}class ra{constructor(e,t,n,s){le(this,"_chain");le(this,"_client");le(this,"_signer");le(this,"_debug");this._chain=e,this._client=t,this._signer=n,this._debug=s}chain(){return this._chain}address(){return this._signer.toSuiAddress()}async signAndSend(e){const t=[];for(const n of e){const{description:s,transaction:i}=n;this._debug&&console.log(`Signing ${s} for ${this.address()}`);try{const o=await this._client.signAndExecuteTransaction({transaction:i,signer:this._signer});t.push(o.digest)}catch(o){throw o}}return t}}const na={Address:Xe,Platform:Le,getSigner:ta,protocols:{WormholeCore:()=>pt(()=>import("./index-BRtMY3at.js"),__vite__mapDeps([0,1,2,3,4])),TokenBridge:()=>pt(()=>import("./index-RBS_ALc7.js"),__vite__mapDeps([5,1,2,0,3,4])),CircleBridge:()=>pt(()=>import("./index-BUlVFUMr.js"),__vite__mapDeps([6,1,2,3,4]))},getChain:(r,e,t)=>new gn(e,new Le(r,_n(r,xt,{[e]:t})))},la=Object.freeze(Object.defineProperty({__proto__:null,default:na},Symbol.toStringTag,{value:"Module"}));export{Pi as S,ua as T,ca as a,Gn as b,la as s};
@@ -1 +0,0 @@
1
- "use strict";var x=Object.defineProperty;var $=(o,e,t)=>e in o?x(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var c=(o,e,t)=>$(o,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./index-wsfzS6PN.js"),C="::",S="0x2::sui::SUI",M=o=>/^(0x)?[0-9a-fA-F]+::\w+::\w+$/.test(o);function I(o){return o=o.startsWith("0x")?o.slice(2):o,o=o.length%2===0?o:"0"+o,`0x${o.length===64?o:r.hex.encode(r.bytes.zpad(r.hex.decode(o),32))}`}const g=class g{constructor(e){c(this,"address");c(this,"module");if(g.instanceof(e))this.address=e.address,this.module=e.module;else if(r.UniversalAddress.instanceof(e))this.address=e.toUint8Array();else if(typeof e=="string"){if(M(e)){const t=e.split(C);this.module=t.slice(1).join(C),e=t[0]}if(e=I(e),!r.hex.valid(e))throw new Error("Invalid Sui address: "+e);this.address=r.hex.decode(e)}else this.address=e}unwrap(){const e=this.getPackageId(),t=this.module?C+this.module:"";return`${e}${t}`}toString(){return this.unwrap()}toNative(){return this}toUint8Array(){return this.address}toUniversalAddress(){return new r.UniversalAddress(this.toUint8Array())}getPackageId(){return I(r.hex.encode(this.address))}getCoinType(){if(this.module==="sui::SUI")return S;if(!this.module)throw new Error("No module present in Sui token address");return this.unwrap()}static instanceof(e){return e.constructor.platform===g.platform}equals(e){return g.instanceof(e)?e.unwrap()===this.unwrap():this.toUniversalAddress().equals(e)}};c(g,"byteSize",32),c(g,"platform","Sui");let f=g;r.registerNative("Sui",f);class _{constructor(e,t,s,n,a=!1){c(this,"transaction");c(this,"network");c(this,"chain");c(this,"description");c(this,"parallelizable");this.transaction=e,this.network=t,this.chain=s,this.description=n,this.parallelizable=a}}class B extends r.ChainContext{}const k="Sui",E=o=>{var t;const e=(t=o.data)==null?void 0:t.content;return e&&e.dataType==="moveObject"?e.fields:null},j=async(o,e)=>{if(!r.isValidSuiAddress(e))throw new Error(`Invalid object ID: ${e}`);const t=await o.getObject({id:e,options:{showContent:!0}});return E(t)},l=class l extends r.PlatformContext{constructor(e,t){super(e,t??r.networkPlatformConfigs(e,l._platform))}getRpc(e){if(e in this.config)return new r.SuiClient({url:this.config[e].rpc});throw new Error("No configuration available for chain: "+e)}getChain(e){if(e in this.config)return new B(e,this);throw new Error("No configuration available for chain: "+e)}static nativeTokenId(e,t){if(!l.isSupportedChain(t))throw new Error(`invalid chain for ${k}: ${t}`);return r.Wormhole.tokenId(t,S)}static isNativeTokenId(e,t,s){return!l.isSupportedChain(t)||s.chain!==t?!1:this.nativeTokenId(e,t)===s}static isSupportedChain(e){return r.chainToPlatform(e)===l._platform}static async getDecimals(e,t,s){if(r.isNative(s))return r.nativeDecimals(l._platform);const n=new f(s);try{const i=await j(t,n.toString());if(i&&"decimals"in i)return i.decimals}catch{}const a=await t.getCoinMetadata({coinType:n.toString()});if(a===null)throw new Error(`Can't fetch decimals for token ${n.toString()}`);return a.decimals}static async getCoins(e,t,s){let n=[],a=null;const i=new f(t).toString();do{const d=await e.getCoins({owner:i,coinType:s,cursor:a});n=[...n,...d.data],a=d.hasNextPage?d.nextCursor:null}while(a);return n}static async getBalance(e,t,s,n){if(r.isNative(n)){const{totalBalance:i}=await t.getBalance({owner:s});return BigInt(i)}const{totalBalance:a}=await t.getBalance({owner:s,coinType:n.toString()});return BigInt(a)}static async getBalances(e,t,s,n){return(await Promise.all(n.map(async i=>{const d=await this.getBalance(e,t,s,i);return{[r.isNative(i)?"native":new f(i).toString()]:d}}))).reduce((i,d)=>Object.assign(i,d),{})}static async sendWait(e,t,s){const n=[];for(const a of s){const i=await t.executeTransactionBlock(a);await t.waitForTransaction({digest:i.digest}),n.push(i.digest)}return n}static async getLatestBlock(e){return Number(await e.getLatestCheckpointSequenceNumber())}static async getLatestFinalizedBlock(e){return this.getLatestBlock(e)}static chainFromChainId(e){const t=r.platformNativeChainIdToNetworkChain(l._platform,e);if(t===void 0)throw new Error(`Unknown native chain id ${e}`);const[s,n]=t;return[s,n]}static async chainFromRpc(e){const t=await e.call("sui_getChainIdentifier",[]);return this.chainFromChainId(t)}};c(l,"_platform",k);let b=l;const U=[["Testnet",{tokenMessengerState:"0x5252abd1137094ed1db3e0d75bc36abcd287aee4bc310f8e047727ef5682e7c2",messageTransmitterState:"0x98234bd0fa9ac12cc0a20a144a22e36d6a32f7e0a97baaeaf9c76cdc6d122d2e",usdcTreasury:"0x7170137d4a6431bf83351ac025baf462909bffe2877d87716374fb42b9629ebe"}],["Mainnet",{tokenMessengerState:"0x45993eecc0382f37419864992c12faee2238f5cfe22b98ad3bf455baf65c8a2f",messageTransmitterState:"0xf68268c3d9b1df3215f2439400c1c4ea08ac4ef4bb7d6f3ca6a2a239e17510af",usdcTreasury:"0x57d6725e7a8b49a7b2a612f6bd66ab5f39fc95332ca48be421c3229d514a6de7"}]],N=r.constMap(U,[0,1]);class T{constructor(e,t,s,n){c(this,"network");c(this,"chain");c(this,"provider");c(this,"contracts");c(this,"usdcId");c(this,"usdcTreasuryId");c(this,"tokenMessengerId");c(this,"tokenMessengerStateId");c(this,"messageTransmitterId");c(this,"messageTransmitterStateId");var m,h,p,w;if(this.network=e,this.chain=t,this.provider=s,this.contracts=n,e==="Devnet")throw new Error("CircleBridge not supported on Devnet");const a=r.usdcContract.get(this.network,this.chain);if(!a)throw new Error(`No USDC contract configured for network=${this.network} chain=${this.chain}`);const{tokenMessengerState:i,messageTransmitterState:d,usdcTreasury:u}=N(e);if(!((m=n.cctp)!=null&&m.tokenMessenger))throw new Error(`Circle Token Messenger contract for domain ${t} not found`);if(!((h=n.cctp)!=null&&h.messageTransmitter))throw new Error(`Circle Message Transmitter contract for domain ${t} not found`);this.usdcId=a,this.usdcTreasuryId=u,this.tokenMessengerId=(p=n.cctp)==null?void 0:p.tokenMessenger,this.messageTransmitterId=(w=n.cctp)==null?void 0:w.messageTransmitter,this.tokenMessengerStateId=i,this.messageTransmitterStateId=d}async*transfer(e,t,s){const n=new r.Transaction$2,a=r.circleChainId.get(this.network,t.chain),[i,...d]=await b.getCoins(this.provider,e,this.usdcId);if(i===void 0)throw new Error("No USDC in wallet");const u=n.object(i.coinObjectId);d.length>0&&n.mergeCoins(u,d.map(h=>n.object(h.coinObjectId)));const[m]=n.splitCoins(u,[s]);n.moveCall({target:`${this.tokenMessengerId}::deposit_for_burn::deposit_for_burn`,arguments:[m,n.pure.u32(a),n.pure.address(t.address.toUniversalAddress().toString()),n.object(this.tokenMessengerStateId),n.object(this.messageTransmitterStateId),n.object("0x403"),n.object(this.usdcTreasuryId)],typeArguments:[this.usdcId]}),yield this.createUnsignedTx(n,"Sui.CircleBridge.Transfer")}async isTransferCompleted(e){const t=new r.Transaction$2;t.moveCall({target:`${this.messageTransmitterId}::state::is_nonce_used`,arguments:[t.object(this.messageTransmitterStateId),t.pure.u32(e.sourceDomain),t.pure.u64(e.nonce)]});const s=await this.provider.devInspectTransactionBlock({sender:"0x0000000000000000000000000000000000000000000000000000000000000000",transactionBlock:t});try{return!!s.results[0].returnValues[0][0][0]}catch(n){return console.error(`Error reading if nonce was used: ${n}`),!1}}async*redeem(e,t,s){const n=new r.Transaction$2,[a]=n.moveCall({target:`${this.messageTransmitterId}::receive_message::receive_message`,arguments:[n.pure.vector("u8",r.CircleBridge.serialize(t)),n.pure.vector("u8",r.hex.decode(s)),n.object(this.messageTransmitterStateId)]});if(!a)throw new Error("Failed to produce receipt");const[i]=n.moveCall({target:`${this.tokenMessengerId}::handle_receive_message::handle_receive_message`,arguments:[a,n.object(this.tokenMessengerStateId),n.object("0x403"),n.object(this.usdcTreasuryId)],typeArguments:[this.usdcId]});if(!i)throw new Error("Failed to produce stamp receipt ticket with burn message");const[d]=n.moveCall({target:`${this.tokenMessengerId}::handle_receive_message::deconstruct_stamp_receipt_ticket_with_burn_message`,arguments:[i]});if(!d)throw new Error("Failed to produce stamp receipt ticket");const[u]=n.moveCall({target:`${this.messageTransmitterId}::receive_message::stamp_receipt`,arguments:[d,n.object(this.messageTransmitterStateId)],typeArguments:[`${this.tokenMessengerId}::message_transmitter_authenticator::MessageTransmitterAuthenticator`]});if(!u)throw new Error("Failed to produce stamped receipt");n.moveCall({target:`${this.messageTransmitterId}::receive_message::complete_receive_message`,arguments:[u,n.object(this.messageTransmitterStateId)]}),yield this.createUnsignedTx(n,"Sui.CircleBridge.Redeem")}async parseTransactionDetails(e){var v;const t=await this.provider.waitForTransaction({digest:e,options:{showEvents:!0,showEffects:!0,showInput:!0}});if(!t)throw new Error("Transaction not found");if(!t.events)throw new Error("Transaction events not found");const s=(v=t.events)==null?void 0:v.find(y=>y.type.includes("send_message::MessageSent"));if(!s)throw new Error("No MessageSent event found");const n=new Uint8Array((s==null?void 0:s.parsedJson).message),[a,i]=r.CircleBridge.deserialize(n),{payload:d}=a,u=d.messageSender,m=d.mintRecipient,h=r.toCircleChain(this.network,a.sourceDomain),p=r.toCircleChain(this.network,a.destinationDomain),w={chain:h,address:d.burnToken};return{from:{chain:h,address:u},to:{chain:p,address:m},token:w,amount:d.amount,message:a,id:{hash:i}}}static async fromRpc(e,t){const[s,n]=await b.chainFromRpc(e),a=t[n];if(a.network!==s)throw new Error(`Network mismatch: ${a.network} != ${s}`);return new T(s,n,e,a.contracts)}createUnsignedTx(e,t,s=!1){return new _(e,this.network,this.chain,t,s)}}r.registerProtocol("Sui","CircleBridge",T);exports.SuiCircleBridge=T;
@@ -1 +0,0 @@
1
- "use strict";var v=Object.defineProperty;var C=(i,t,e)=>t in i?v(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var c=(i,t,e)=>C(i,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./index-wsfzS6PN.js"),g="::",y="0x2::sui::SUI",S=i=>/^(0x)?[0-9a-fA-F]+::\w+::\w+$/.test(i);function f(i){return i=i.startsWith("0x")?i.slice(2):i,i=i.length%2===0?i:"0"+i,`0x${i.length===64?i:s.hex.encode(s.bytes.zpad(s.hex.decode(i),32))}`}const h=class h{constructor(t){c(this,"address");c(this,"module");if(h.instanceof(t))this.address=t.address,this.module=t.module;else if(s.UniversalAddress.instanceof(t))this.address=t.toUint8Array();else if(typeof t=="string"){if(S(t)){const e=t.split(g);this.module=e.slice(1).join(g),t=e[0]}if(t=f(t),!s.hex.valid(t))throw new Error("Invalid Sui address: "+t);this.address=s.hex.decode(t)}else this.address=t}unwrap(){const t=this.getPackageId(),e=this.module?g+this.module:"";return`${t}${e}`}toString(){return this.unwrap()}toNative(){return this}toUint8Array(){return this.address}toUniversalAddress(){return new s.UniversalAddress(this.toUint8Array())}getPackageId(){return f(s.hex.encode(this.address))}getCoinType(){if(this.module==="sui::SUI")return y;if(!this.module)throw new Error("No module present in Sui token address");return this.unwrap()}static instanceof(t){return t.constructor.platform===h.platform}equals(t){return h.instanceof(t)?t.unwrap()===this.unwrap():this.toUniversalAddress().equals(t)}};c(h,"byteSize",32),c(h,"platform","Sui");let d=h;s.registerNative("Sui",d);class k extends s.ChainContext{}const p="Sui",I=i=>{var e;const t=(e=i.data)==null?void 0:e.content;return t&&t.dataType==="moveObject"?t.fields:null},x=async(i,t)=>{if(!s.isValidSuiAddress(t))throw new Error(`Invalid object ID: ${t}`);const e=await i.getObject({id:t,options:{showContent:!0}});return I(e)},l=class l extends s.PlatformContext{constructor(t,e){super(t,e??s.networkPlatformConfigs(t,l._platform))}getRpc(t){if(t in this.config)return new s.SuiClient({url:this.config[t].rpc});throw new Error("No configuration available for chain: "+t)}getChain(t){if(t in this.config)return new k(t,this);throw new Error("No configuration available for chain: "+t)}static nativeTokenId(t,e){if(!l.isSupportedChain(e))throw new Error(`invalid chain for ${p}: ${e}`);return s.Wormhole.tokenId(e,y)}static isNativeTokenId(t,e,n){return!l.isSupportedChain(e)||n.chain!==e?!1:this.nativeTokenId(t,e)===n}static isSupportedChain(t){return s.chainToPlatform(t)===l._platform}static async getDecimals(t,e,n){if(s.isNative(n))return s.nativeDecimals(l._platform);const r=new d(n);try{const a=await x(e,r.toString());if(a&&"decimals"in a)return a.decimals}catch{}const o=await e.getCoinMetadata({coinType:r.toString()});if(o===null)throw new Error(`Can't fetch decimals for token ${r.toString()}`);return o.decimals}static async getCoins(t,e,n){let r=[],o=null;const a=new d(e).toString();do{const u=await t.getCoins({owner:a,coinType:n,cursor:o});r=[...r,...u.data],o=u.hasNextPage?u.nextCursor:null}while(o);return r}static async getBalance(t,e,n,r){if(s.isNative(r)){const{totalBalance:a}=await e.getBalance({owner:n});return BigInt(a)}const{totalBalance:o}=await e.getBalance({owner:n,coinType:r.toString()});return BigInt(o)}static async getBalances(t,e,n,r){return(await Promise.all(r.map(async a=>{const u=await this.getBalance(t,e,n,a);return{[s.isNative(a)?"native":new d(a).toString()]:u}}))).reduce((a,u)=>Object.assign(a,u),{})}static async sendWait(t,e,n){const r=[];for(const o of n){const a=await e.executeTransactionBlock(o);await e.waitForTransaction({digest:a.digest}),r.push(a.digest)}return r}static async getLatestBlock(t){return Number(await t.getLatestCheckpointSequenceNumber())}static async getLatestFinalizedBlock(t){return this.getLatestBlock(t)}static chainFromChainId(t){const e=s.platformNativeChainIdToNetworkChain(l._platform,t);if(e===void 0)throw new Error(`Unknown native chain id ${t}`);const[n,r]=e;return[n,r]}static async chainFromRpc(t){const e=await t.call("sui_getChainIdentifier",[]);return this.chainFromChainId(e)}};c(l,"_platform",p);let m=l;class w{constructor(t,e,n,r){c(this,"network");c(this,"chain");c(this,"provider");c(this,"contracts");c(this,"chainId");c(this,"coreBridgePackageId");this.network=t,this.chain=e,this.provider=n,this.contracts=r,this.chainId=s.toChainId(e);const o=r.coreBridge;if(!o)throw new Error(`CoreBridge contract Address for chain ${e} not found`);this.coreBridgePackageId=o}getGuardianSet(t){throw new Error("Method not implemented.")}getMessageFee(){throw new Error("Method not implemented.")}static async fromRpc(t,e){const[n,r]=await m.chainFromRpc(t),o=e[r];if(o.network!==n)throw new Error(`Network mismatch: ${o.network} !== ${n}`);return new w(n,r,t,o.contracts)}async*verifyMessage(t,e){throw new Error("Method not implemented.")}async*publishMessage(t,e){throw new Error("Method not implemented.")}async parseTransaction(t){return(await this.parseMessages(t)).map(n=>({emitter:n.emitterAddress,sequence:n.sequence,chain:this.chain}))}async getGuardianSetIndex(){throw new Error("Method not implemented.")}async parseMessages(t){var r;const n=(r=(await this.provider.getTransactionBlock({digest:t,options:{showEvents:!0,showEffects:!0,showInput:!0}})).events)==null?void 0:r.filter(o=>o.type.endsWith("WormholeMessage"));if(!n||n.length==0)throw new Error("WormholeMessage not found");return n.map(o=>{const a=o.parsedJson;return s.createVAA("Uint8Array",{emitterChain:this.chain,emitterAddress:new d(a.sender).toUniversalAddress(),sequence:BigInt(a.sequence),guardianSet:0,timestamp:Number(a.timestamp),consistencyLevel:a.consistency_level,nonce:a.nonce,signatures:[],payload:new Uint8Array(a.payload)})})}}s.registerProtocol("Sui","WormholeCore",w);exports.SuiWormholeCore=w;
@@ -1,252 +0,0 @@
1
- var k = Object.defineProperty;
2
- var S = (a, t, e) => t in a ? k(a, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : a[t] = e;
3
- var o = (a, t, e) => S(a, typeof t != "symbol" ? t + "" : t, e);
4
- import { c0 as p, aa as d, cL as I, cU as B, $ as x, ao as E, a0 as A, a2 as b, ap as T, a3 as N, a5 as U, a6 as w, a7 as M, a9 as $, bE as F, cM as P, bQ as q } from "./index-m0543tB2.mjs";
5
- const g = "::", C = "0x2::sui::SUI", O = (a) => /^(0x)?[0-9a-fA-F]+::\w+::\w+$/.test(a);
6
- function y(a) {
7
- return a = a.startsWith("0x") ? a.slice(2) : a, a = a.length % 2 === 0 ? a : "0" + a, `0x${a.length === 64 ? a : d.encode(I.zpad(d.decode(a), 32))}`;
8
- }
9
- const u = class u {
10
- constructor(t) {
11
- // Full 32 bytes of Address
12
- o(this, "address");
13
- // Optional module and contract name
14
- o(this, "module");
15
- if (u.instanceof(t))
16
- this.address = t.address, this.module = t.module;
17
- else if (p.instanceof(t))
18
- this.address = t.toUint8Array();
19
- else if (typeof t == "string") {
20
- if (O(t)) {
21
- const e = t.split(g);
22
- this.module = e.slice(1).join(g), t = e[0];
23
- }
24
- if (t = y(t), !d.valid(t))
25
- throw new Error("Invalid Sui address: " + t);
26
- this.address = d.decode(t);
27
- } else
28
- this.address = t;
29
- }
30
- unwrap() {
31
- const t = this.getPackageId(), e = this.module ? g + this.module : "";
32
- return `${t}${e}`;
33
- }
34
- toString() {
35
- return this.unwrap();
36
- }
37
- toNative() {
38
- return this;
39
- }
40
- toUint8Array() {
41
- return this.address;
42
- }
43
- toUniversalAddress() {
44
- return new p(this.toUint8Array());
45
- }
46
- getPackageId() {
47
- return y(d.encode(this.address));
48
- }
49
- getCoinType() {
50
- if (this.module === "sui::SUI")
51
- return C;
52
- if (!this.module)
53
- throw new Error("No module present in Sui token address");
54
- return this.unwrap();
55
- }
56
- static instanceof(t) {
57
- return t.constructor.platform === u.platform;
58
- }
59
- equals(t) {
60
- return u.instanceof(t) ? t.unwrap() === this.unwrap() : this.toUniversalAddress().equals(t);
61
- }
62
- };
63
- o(u, "byteSize", 32), o(u, "platform", "Sui");
64
- let h = u;
65
- B("Sui", h);
66
- class R extends x {
67
- }
68
- const v = "Sui", W = (a) => {
69
- var e;
70
- const t = (e = a.data) == null ? void 0 : e.content;
71
- return t && t.dataType === "moveObject" ? t.fields : null;
72
- }, z = async (a, t) => {
73
- if (!E(t))
74
- throw new Error(`Invalid object ID: ${t}`);
75
- const e = await a.getObject({
76
- id: t,
77
- options: {
78
- showContent: !0
79
- }
80
- });
81
- return W(e);
82
- }, c = class c extends A {
83
- constructor(t, e) {
84
- super(t, e ?? b(t, c._platform));
85
- }
86
- getRpc(t) {
87
- if (t in this.config)
88
- return new T({ url: this.config[t].rpc });
89
- throw new Error("No configuration available for chain: " + t);
90
- }
91
- getChain(t) {
92
- if (t in this.config)
93
- return new R(t, this);
94
- throw new Error("No configuration available for chain: " + t);
95
- }
96
- static nativeTokenId(t, e) {
97
- if (!c.isSupportedChain(e))
98
- throw new Error(`invalid chain for ${v}: ${e}`);
99
- return N.tokenId(e, C);
100
- }
101
- static isNativeTokenId(t, e, n) {
102
- return !c.isSupportedChain(e) || n.chain !== e ? !1 : this.nativeTokenId(t, e) === n;
103
- }
104
- static isSupportedChain(t) {
105
- return U(t) === c._platform;
106
- }
107
- static async getDecimals(t, e, n) {
108
- if (w(n))
109
- return M(c._platform);
110
- const r = new h(n);
111
- try {
112
- const s = await z(e, r.toString());
113
- if (s && "decimals" in s)
114
- return s.decimals;
115
- } catch {
116
- }
117
- const i = await e.getCoinMetadata({ coinType: r.toString() });
118
- if (i === null)
119
- throw new Error(`Can't fetch decimals for token ${r.toString()}`);
120
- return i.decimals;
121
- }
122
- static async getCoins(t, e, n) {
123
- let r = [], i = null;
124
- const s = new h(e).toString();
125
- do {
126
- const l = await t.getCoins({
127
- owner: s,
128
- coinType: n,
129
- cursor: i
130
- });
131
- r = [...r, ...l.data], i = l.hasNextPage ? l.nextCursor : null;
132
- } while (i);
133
- return r;
134
- }
135
- static async getBalance(t, e, n, r) {
136
- if (w(r)) {
137
- const { totalBalance: s } = await e.getBalance({
138
- owner: n
139
- });
140
- return BigInt(s);
141
- }
142
- const { totalBalance: i } = await e.getBalance({
143
- owner: n,
144
- coinType: r.toString()
145
- });
146
- return BigInt(i);
147
- }
148
- static async getBalances(t, e, n, r) {
149
- return (await Promise.all(r.map(async (s) => {
150
- const l = await this.getBalance(t, e, n, s);
151
- return { [w(s) ? "native" : new h(s).toString()]: l };
152
- }))).reduce((s, l) => Object.assign(s, l), {});
153
- }
154
- static async sendWait(t, e, n) {
155
- const r = [];
156
- for (const i of n) {
157
- const s = await e.executeTransactionBlock(i);
158
- await e.waitForTransaction({ digest: s.digest }), r.push(s.digest);
159
- }
160
- return r;
161
- }
162
- static async getLatestBlock(t) {
163
- return Number(await t.getLatestCheckpointSequenceNumber());
164
- }
165
- static async getLatestFinalizedBlock(t) {
166
- return this.getLatestBlock(t);
167
- }
168
- static chainFromChainId(t) {
169
- const e = $(c._platform, t);
170
- if (e === void 0)
171
- throw new Error(`Unknown native chain id ${t}`);
172
- const [n, r] = e;
173
- return [n, r];
174
- }
175
- static async chainFromRpc(t) {
176
- const e = await t.call("sui_getChainIdentifier", []);
177
- return this.chainFromChainId(e);
178
- }
179
- };
180
- o(c, "_platform", v);
181
- let m = c;
182
- class f {
183
- constructor(t, e, n, r) {
184
- o(this, "network");
185
- o(this, "chain");
186
- o(this, "provider");
187
- o(this, "contracts");
188
- o(this, "chainId");
189
- o(this, "coreBridgePackageId");
190
- this.network = t, this.chain = e, this.provider = n, this.contracts = r, this.chainId = F(e);
191
- const i = r.coreBridge;
192
- if (!i)
193
- throw new Error(`CoreBridge contract Address for chain ${e} not found`);
194
- this.coreBridgePackageId = i;
195
- }
196
- getGuardianSet(t) {
197
- throw new Error("Method not implemented.");
198
- }
199
- getMessageFee() {
200
- throw new Error("Method not implemented.");
201
- }
202
- static async fromRpc(t, e) {
203
- const [n, r] = await m.chainFromRpc(t), i = e[r];
204
- if (i.network !== n)
205
- throw new Error(`Network mismatch: ${i.network} !== ${n}`);
206
- return new f(n, r, t, i.contracts);
207
- }
208
- async *verifyMessage(t, e) {
209
- throw new Error("Method not implemented.");
210
- }
211
- async *publishMessage(t, e) {
212
- throw new Error("Method not implemented.");
213
- }
214
- async parseTransaction(t) {
215
- return (await this.parseMessages(t)).map((n) => ({
216
- emitter: n.emitterAddress,
217
- sequence: n.sequence,
218
- chain: this.chain
219
- }));
220
- }
221
- async getGuardianSetIndex() {
222
- throw new Error("Method not implemented.");
223
- }
224
- async parseMessages(t) {
225
- var r;
226
- const n = (r = (await this.provider.getTransactionBlock({
227
- digest: t,
228
- options: { showEvents: !0, showEffects: !0, showInput: !0 }
229
- })).events) == null ? void 0 : r.filter((i) => i.type.endsWith("WormholeMessage"));
230
- if (!n || n.length == 0)
231
- throw new Error("WormholeMessage not found");
232
- return n.map((i) => {
233
- const s = i.parsedJson;
234
- return P("Uint8Array", {
235
- emitterChain: this.chain,
236
- emitterAddress: new h(s.sender).toUniversalAddress(),
237
- sequence: BigInt(s.sequence),
238
- guardianSet: 0,
239
- // TODO: need to implement guardian set idx
240
- timestamp: Number(s.timestamp),
241
- consistencyLevel: s.consistency_level,
242
- nonce: s.nonce,
243
- signatures: [],
244
- payload: new Uint8Array(s.payload)
245
- });
246
- });
247
- }
248
- }
249
- q("Sui", "WormholeCore", f);
250
- export {
251
- f as SuiWormholeCore
252
- };