@naviprotocol/wallet-client 1.0.1-dev.0 → 1.0.1-dev.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 NAVI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.cjs.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=require("@mysten/sui/client"),Q=require("mitt"),K=require("axios"),l=require("@naviprotocol/lending"),T=require("bignumber.js"),B=require("@mysten/sui/utils"),w=require("@mysten/sui/transactions"),v=require("@naviprotocol/astros-aggregator-sdk"),L=require("@mysten/sui/cryptography"),M=K.create({timeout:2e4});M.interceptors.response.use(function(c){if(c.data.err)throw new Error(c.data.err);if(c.data.error)throw new Error(c.data.error.message);return c},function(c){return Promise.reject(c)});class ${constructor(e){this.requestId=0,this.rpcUrl=e}async request(e){return this.requestId+=1,(await M.post(this.rpcUrl,{jsonrpc:"2.0",id:this.requestId,method:e.method,params:e.params})).data.result}async subscribe(){throw new Error("subscribe not implemented.")}}class E{get config(){return this.walletClient?this.walletClient.config(this.name):this.defaultConfig}emit(e,a){var t;(t=this.walletClient)==null||t.events.emit(e,a)}install(e){this.walletClient=e}uninstall(){this.walletClient=void 0}}class p{constructor(e){if(e instanceof p)this.balances=JSON.parse(JSON.stringify(e.balances));else{const a={};e==null||e.forEach(t=>{const s=B.normalizeStructTag(t.coinType);let n=a[s];n||(n={coinType:s,amount:T.BigNumber(0),coins:[]},a[s]=n),n.coins.push(t),n.amount=n.amount.plus(t.balance)}),this.balances=a}}getBalance(e){return e=B.normalizeStructTag(e),this.balances[e]||{coinType:e,amount:T.BigNumber(0),coins:[]}}getCoinTypes(){return Object.values(this.balances).map(e=>e.coinType)}balanceOf(e){e=B.normalizeStructTag(e);const a=this.getBalance(e);return(a==null?void 0:a.amount)||T.BigNumber(0)}clone(){const e=JSON.parse(JSON.stringify(this.balances)),a=new p;return a.balances=e,a}}class z extends E{constructor(){super(...arguments),this.name="balance",this.defaultConfig={coinPollingInterval:6e3},this.updatePortfolio=l.withSingleton(async()=>{if(!this.walletClient)throw new Error("Wallet client not found");this._coins=await l.getCoins(this.walletClient.address,{client:this.walletClient.client}),this._portfolio=new p(this._coins),this.emit("balance:portfolio-updated",{})}),this._coins=[],this._portfolio=new p,this.pollingTimer=null,this._updatePromise=null}get coins(){return this._coins}get portfolio(){return this._portfolio}async waitForUpdate(){if(!this._updatePromise)throw new Error("Update promise not found");return await this._updatePromise}async sendCoin(e,a,t,s){return this.sendCoinBatch(e,[a],[t],s)}async sendCoinBatch(e,a,t,s){var h;if(!this.walletClient)throw new Error("Wallet client not found");if(a.length!==t.length)throw new Error("Recipients and amounts must have the same length");await this.waitForUpdate();const n=this.portfolio.getBalance(e),u=t.reduce((g,f)=>g.plus(f),T(0));if(n.amount.lt(u))throw new Error("Insufficient balance");const i=new w.Transaction;let r=i.gas;B.normalizeStructTag(e)!==B.normalizeStructTag("0x2::sui::SUI")&&(r=l.mergeCoinsPTB(i,n.coins,{balance:u.toNumber()}));const o=i.splitCoins(r,t);return a.forEach((g,f)=>{i.transferObjects([o[f]],g)}),await this.walletClient.signExecuteTransaction({transaction:i,dryRun:(h=s==null?void 0:s.dryRun)!=null?h:!1})}async transferObject(e,a,t){return this.transferObjectBatch([e],[a],t)}async transferObjectBatch(e,a,t){var u;if(!this.walletClient)throw new Error("Wallet client not found");if(e.length!==a.length)throw new Error("Objects and recipients must have the same length");await this.waitForUpdate();const s=new w.Transaction;return e.forEach((i,r)=>{s.transferObjects([s.object(i)],a[r])}),await this.walletClient.signExecuteTransaction({transaction:s,dryRun:(u=t==null?void 0:t.dryRun)!=null?u:!1})}async startPolling(){try{await this.updatePortfolio()}catch(e){console.error(e)}finally{this.pollingTimer=setTimeout(this.startPolling,this.config.coinPollingInterval)}}install(e){super.install(e),this.startPolling=this.startPolling.bind(this),this.startPolling(),this._updatePromise=new Promise(a=>{e.events.on("balance:portfolio-updated",()=>{a()})})}uninstall(){super.uninstall(),this.pollingTimer&&(clearTimeout(this.pollingTimer),this.pollingTimer=null)}}const G=27;function H(c,e=2){return c?new T(c.toString()).shiftedBy(-1*G).multipliedBy(100).decimalPlaces(e,T.ROUND_DOWN).toFixed(e):"0.00"}async function W(c,e,a,t){var S,R;if(!this.walletClient)throw new Error("Wallet client not found");const s=await this.getPool(e),n=await this.getPool(a),i=(await this.getLendingState()).find(O=>O.pool.id===s.id),r=this.walletClient.address;if(!i||i.supplyBalance==="0")throw new Error("No supply balance");if(t!=null&&t.amount&&t.amount<Number(i.supplyBalance))throw new Error("Amount is less than supply balance");const o=await l.getFlashLoanAsset(n,{env:this.config.env});if(!(o!=null&&o.flashloanFee))throw new Error(`${s.token.symbol} pool not support flashloan`);const d=(S=t==null?void 0:t.slippage)!=null?S:.005,h=(R=t==null?void 0:t.amount)!=null?R:Number(i.supplyBalance),g=await this.walletClient.swap.getQuote(s.suiCoinType,n.suiCoinType,h),f=Number(g.amount_out);if(f<=0)throw new Error("The amount of swapAmountOut must be greater than 0.");const y=Math.floor(f*(1-d)),m=Math.floor(y/(1+o.flashloanFee));if(m<=0)throw new Error("The calculated borrow amount must be positive.");const[C,b]=await l.flashloanPTB(c,n,m),[P]=c.moveCall({target:"0x2::coin::from_balance",arguments:[C],typeArguments:[n.suiCoinType]});await l.depositCoinPTB(c,n,P,{amount:m});const x=await l.withdrawCoinPTB(c,s,h),A=await v.buildSwapPTBFromQuote(r,c,y,x,g),F=c.moveCall({target:"0x2::coin::into_balance",arguments:[A],typeArguments:[n.suiCoinType]}),[k]=await l.repayFlashLoanPTB(c,n,b,F),[j]=c.moveCall({target:"0x2::coin::from_balance",arguments:[k],typeArguments:[n.suiCoinType]});return await l.depositCoinPTB(c,n,j),c}async function N(c,e,a,t){var O,U;if(!this.walletClient)throw new Error("Wallet client not found");const s=this.walletClient.address,n=await this.getPool(e),u=await this.getPool(a),r=(await this.getLendingState()).find(_=>_.pool.id===n.id);if(!r||r.borrowBalance==="0")throw new Error("No borrow balance");if(t!=null&&t.amount&&t.amount<Number(r.borrowBalance))throw new Error("Amount is less than borrow balance");let o=(O=t==null?void 0:t.amount)!=null?O:Number(r.borrowBalance);if(Number(r.borrowBalance)===o){const _=parseFloat(H(n.currentBorrowRate,8))/100;o=Math.ceil(new T(o).multipliedBy(_*(60*3)/(365*24*3600)).plus(new T(1).shiftedBy(-n.token.decimals)).plus(o).toNumber())}const d=await l.getFlashLoanAsset(n,{env:this.config.env});if(!d)throw new Error(`${n.token.symbol} pool not support flashloan`);if(!this.walletClient)throw new Error("Wallet client not found");const h=(U=t==null?void 0:t.slippage)!=null?U:.005,g=Math.ceil(o*(1+d.flashloanFee)),f=g,y=await this.walletClient.swap.getQuote(n.suiCoinType,u.suiCoinType,f);let m=1+h,C=Math.ceil(Number(y.amount_out)*m),b=await this.walletClient.swap.getQuote(u.suiCoinType,n.suiCoinType,C);for(;Number(b.amount_out)<f;)m=m*Math.max(f/Number(b.amount_out),1.001),C=Math.ceil(Number(y.amount_out)*m),b=await this.walletClient.swap.getQuote(u.suiCoinType,n.suiCoinType,C);const[P,x]=await l.flashloanPTB(c,n,o),[A]=c.moveCall({target:"0x2::coin::from_balance",arguments:[P],typeArguments:[n.suiCoinType]});await l.repayCoinPTB(c,n,A,{amount:o});const F=await l.borrowCoinPTB(c,u,C),k=await v.buildSwapPTBFromQuote(s,c,g,F,b),j=c.moveCall({target:"0x2::coin::into_balance",arguments:[k],typeArguments:[n.suiCoinType]}),[S]=await l.repayFlashLoanPTB(c,n,x,j),[R]=c.moveCall({target:"0x2::coin::from_balance",arguments:[S],typeArguments:[n.suiCoinType]});return c.transferObjects([R],s),c}async function I(c,e,a,t){var o,d;if(!this.walletClient)throw new Error("Wallet client not found");this.walletClient.address;const s=await this.getPool(a),n=this.walletClient.balance.portfolio.getBalance(e);if(n.amount.eq(0))throw new Error(`No balance of ${e}`);if(t!=null&&t.amount&&n.amount.lt(t.amount))throw new Error("Amount is less than balance");const u=(o=t==null?void 0:t.amount)!=null?o:n.amount.toNumber(),i=(d=t==null?void 0:t.slippage)!=null?d:.005;let r=await l.mergeCoinsPTB(c,n.coins,{balance:u,useGasCoin:!0});if(B.normalizeStructTag(e)!==B.normalizeStructTag(s.suiCoinType)){const h=await this.walletClient.swap.getQuote(e,s.suiCoinType,u);r=await this.walletClient.swap.buildSwapPTBFromQuote(c,h,r,i)}return await l.depositCoinPTB(c,s,r),c}class D extends E{constructor(){super(),this.name="lending",this.defaultConfig={env:"prod"},this.migrateSupplyPTB=W,this.migrateBorrowPTB=N,this.migrateBalanceToSupplyPTB=I,this.migrateSupplyPTB=W.bind(this),this.migrateBorrowPTB=N.bind(this),this.migrateBalanceToSupplyPTB=I.bind(this)}async getPools(e){return await l.getPools({env:this.config.env,...e})}async getPool(e,a){return await l.getPool(e,{env:this.config.env,...a})}async deposit(e,a,t){var o,d,h;if(!this.walletClient)throw new Error("Wallet client not found");const s=await l.getPool(e,{env:this.config.env});await this.walletClient.module("balance").waitForUpdate();const n=new w.Transaction,u=this.walletClient.module("balance").portfolio.getBalance(s.suiCoinType),i=l.mergeCoinsPTB(n,u.coins,{balance:a,useGasCoin:!0});await l.depositCoinPTB(n,s,i,{env:this.config.env,amount:a,accountCap:t==null?void 0:t.accountCap});const r=await this.walletClient.signExecuteTransaction({transaction:n,dryRun:(o=t==null?void 0:t.dryRun)!=null?o:!1});return!(t!=null&&t.dryRun)&&((h=(d=r.effects)==null?void 0:d.status)==null?void 0:h.status)==="success"&&(this.emit("lending:deposit-success",{identifier:e,amount:a}),this.walletClient.module("balance").updatePortfolio()),r}async withdraw(e,a,t){var r,o,d;if(!this.walletClient)throw new Error("Wallet client not found");const s=await l.getPool(e,{env:this.config.env}),n=new w.Transaction;t!=null&&t.disableUpdateOracle||await this.updateOraclePTB(n,[s]);const u=await l.withdrawCoinPTB(n,s,a,{env:this.config.env,accountCap:t==null?void 0:t.accountCap});n.transferObjects([u],this.walletClient.address);const i=await this.walletClient.signExecuteTransaction({transaction:n,dryRun:(r=t==null?void 0:t.dryRun)!=null?r:!1});return!(t!=null&&t.dryRun)&&((d=(o=i.effects)==null?void 0:o.status)==null?void 0:d.status)==="success"&&(this.emit("lending:withdraw-success",{identifier:e,amount:a}),this.walletClient.module("balance").updatePortfolio()),i}async borrow(e,a,t){var r,o,d;if(!this.walletClient)throw new Error("Wallet client not found");const s=await l.getPool(e,{env:this.config.env}),n=new w.Transaction;t!=null&&t.disableUpdateOracle||await this.updateOraclePTB(n,[s]);const u=await l.borrowCoinPTB(n,s,a,{env:this.config.env,accountCap:t==null?void 0:t.accountCap});n.transferObjects([u],this.walletClient.address);const i=await this.walletClient.signExecuteTransaction({transaction:n,dryRun:(r=t==null?void 0:t.dryRun)!=null?r:!1});return!(t!=null&&t.dryRun)&&((d=(o=i.effects)==null?void 0:o.status)==null?void 0:d.status)==="success"&&(this.emit("lending:borrow-success",{identifier:e,amount:a}),this.walletClient.module("balance").updatePortfolio()),i}async repay(e,a,t){var o,d,h;if(!this.walletClient)throw new Error("Wallet client not found");await this.walletClient.module("balance").waitForUpdate();const s=await l.getPool(e,{env:this.config.env}),n=new w.Transaction,u=this.walletClient.module("balance").portfolio.getBalance(s.suiCoinType),i=l.mergeCoinsPTB(n,u.coins,{balance:a,useGasCoin:!0});await l.repayCoinPTB(n,s,i,{env:this.config.env,amount:a,accountCap:t==null?void 0:t.accountCap});const r=await this.walletClient.signExecuteTransaction({transaction:n,dryRun:(o=t==null?void 0:t.dryRun)!=null?o:!1});return!(t!=null&&t.dryRun)&&((h=(d=r.effects)==null?void 0:d.status)==null?void 0:h.status)==="success"&&(this.emit("lending:repay-success",{identifier:e,amount:a}),this.walletClient.module("balance").updatePortfolio()),r}async getHealthFactor(){if(!this.walletClient)throw new Error("Wallet client not found");const e=this.walletClient.address;return await l.getHealthFactor(e,{env:this.config.env,client:this.walletClient.client})}async liquidate(e,a,t,s,n){var C,b,P;if(!this.walletClient)throw new Error("Wallet client not found");const u=await l.getPool(e,{env:this.config.env}),i=await l.getPool(t,{env:this.config.env}),r=new w.Transaction,o=this.walletClient.module("balance").portfolio.getBalance(u.suiCoinType),d=l.mergeCoinsPTB(r,o.coins,{balance:a,useGasCoin:!0}),[h,g]=await l.liquidatePTB(r,u,d,i,s,{env:this.config.env}),[f]=r.moveCall({target:"0x2::coin::from_balance",arguments:[h],typeArguments:[i.suiCoinType]}),[y]=r.moveCall({target:"0x2::coin::from_balance",arguments:[g],typeArguments:[u.suiCoinType]});r.transferObjects([f,y],this.walletClient.address);const m=await this.walletClient.signExecuteTransaction({transaction:r,dryRun:(C=n==null?void 0:n.dryRun)!=null?C:!1});return!(n!=null&&n.dryRun)&&((P=(b=m.effects)==null?void 0:b.status)==null?void 0:P.status)==="success"&&(this.emit("lending:liquidate-success",{payIdentifier:e,payAmount:a,collateralIdentifier:t,liquidationAddress:s}),this.walletClient.module("balance").updatePortfolio()),m}async getAvailableRewards(e){if(!this.walletClient)throw new Error("Wallet client not found");return l.getUserAvailableLendingRewards(this.walletClient.address,{...e,env:this.config.env})}async getClaimedRewardHistory(e){if(!this.walletClient)throw new Error("Wallet client not found");return l.getUserClaimedRewardHistory(this.walletClient.address,{...e})}async claimAllRewards(e){var n,u,i;if(!this.walletClient)throw new Error("Wallet client not found");const a=new w.Transaction,t=await l.getUserAvailableLendingRewards(this.walletClient.address,{env:this.config.env});await l.claimLendingRewardsPTB(a,t,{env:this.config.env,accountCap:e==null?void 0:e.accountCap});const s=await this.walletClient.signExecuteTransaction({transaction:a,dryRun:(n=e==null?void 0:e.dryRun)!=null?n:!1});return!(e!=null&&e.dryRun)&&((i=(u=s.effects)==null?void 0:u.status)==null?void 0:i.status)==="success"&&(this.emit("lending:claim-rewards-success",{rewards:t}),this.walletClient.module("balance").updatePortfolio()),s}async updateOraclePTB(e,a){const t=await l.getPriceFeeds({env:this.config.env}),s=await this.getLendingState({cacheTime:60*1e3}),n=l.filterPriceFeeds(t,{lendingState:s,pools:a});await l.updateOraclePricesPTB(e,n,{env:this.config.env,updatePythPriceFeeds:!0})}async updateOracle(e){var s;if(!this.walletClient)throw new Error("Wallet client not found");const a=new w.Transaction;return await this.updateOraclePTB(a,e==null?void 0:e.pools),await this.walletClient.signExecuteTransaction({transaction:a,dryRun:(s=e==null?void 0:e.dryRun)!=null?s:!1})}async getLendingState(e){if(!this.walletClient)throw new Error("Wallet client not found");return await l.getLendingState(this.walletClient.address,{env:this.config.env,...e,client:this.walletClient.client})}async createAccountCap(e){var n;if(!this.walletClient)throw new Error("Wallet client not found");const a=new w.Transaction,t=await l.createAccountCapPTB(a);return a.transferObjects([t],this.walletClient.address),await this.walletClient.signExecuteTransaction({transaction:a,dryRun:(n=e==null?void 0:e.dryRun)!=null?n:!1})}}class J extends E{constructor(){super(...arguments),this.name="volo",this.defaultConfig={packageId:"0x68d22cf8bdbcd11ecba1e094922873e4080d4d11133e2443fddda0bfd11dae20",poolId:"0x2d914e23d82fedef1b5f56a32d5c64bdcc3087ccfea2b4d6ea51a71f587840e5",metadataId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",coinType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT"},this.getStats=l.withCache(l.withSingleton(async()=>(await fetch("https://open-api.naviprotocol.io/api/volo/stats").then(a=>a.json())).data))}async stakePTB(e,a){const[t]=e.moveCall({target:`${this.config.packageId}::stake_pool::stake`,arguments:[e.object(this.config.poolId),e.object(this.config.metadataId),e.object("0x05"),l.parseTxValue(a,e.object)],typeArguments:[]});return t}async unstakePTB(e,a){const[t]=e.moveCall({target:`${this.config.packageId}::stake_pool::unstake`,arguments:[e.object(this.config.poolId),e.object(this.config.metadataId),e.object("0x05"),l.parseTxValue(a,e.object)],typeArguments:[]});return t}async stake(e,a){var r,o,d;if(!this.walletClient)throw new Error("Wallet client not found");if(e<1e9)throw new Error("Stake amount should be greater than 1Sui");const t=new w.Transaction;await this.walletClient.module("balance").waitForUpdate();const s=this.walletClient.module("balance").portfolio.getBalance("0x2::sui::SUI"),n=l.mergeCoinsPTB(t,s.coins,{balance:e,useGasCoin:!0}),u=await this.stakePTB(t,n);t.transferObjects([u],this.walletClient.address);const i=await this.walletClient.signExecuteTransaction({transaction:t,dryRun:(r=a==null?void 0:a.dryRun)!=null?r:!1});return!(a!=null&&a.dryRun)&&((d=(o=i.effects)==null?void 0:o.status)==null?void 0:d.status)==="success"&&(this.emit("volo:stake-success",{suiAmount:e}),this.walletClient.module("balance").updatePortfolio()),i}async unstake(e,a){var r,o,d;if(!this.walletClient)throw new Error("Wallet client not found");if(e<1e9)throw new Error("Unstake amount should >= 1vSui");await this.walletClient.module("balance").waitForUpdate();const t=new w.Transaction,s=this.walletClient.module("balance").portfolio.getBalance(this.config.coinType),n=l.mergeCoinsPTB(t,s.coins,{balance:e}),u=await this.unstakePTB(t,n);t.transferObjects([u],this.walletClient.address);const i=await this.walletClient.signExecuteTransaction({transaction:t,dryRun:(r=a==null?void 0:a.dryRun)!=null?r:!1});return!(a!=null&&a.dryRun)&&((d=(o=i.effects)==null?void 0:o.status)==null?void 0:d.status)==="success"&&(this.emit("volo:unstake-success",{vSuiAmount:e}),this.walletClient.module("balance").updatePortfolio()),i}}class V extends E{constructor(){super(...arguments),this.name="swap",this.defaultConfig={apiKey:"",baseUrl:"https://open-aggregator-api.naviprotocol.io/find_routes",dexList:[],depth:3,serviceFee:void 0,env:"prod"}}get referral(){return this.config.apiKey?v.generateRefId(this.config.apiKey):0}get swapOptions(){return{baseUrl:this.config.baseUrl,dexList:this.config.dexList,depth:this.config.depth,serviceFee:this.config.serviceFee}}async getQuote(e,a,t){return v.getQuote(e,a,t,this.config.apiKey,this.swapOptions)}async buildSwapPTBFromQuote(e,a,t,s){if(!this.walletClient)throw new Error("Wallet client not found");const n=new T(a.amount_out).multipliedBy(1-s).toFixed(0);return await v.buildSwapPTBFromQuote(this.walletClient.address,e,Number(n),t,a,this.referral,!1,this.config.apiKey,this.swapOptions)}async swap(e,a,t,s,n){var g,f,y,m;if(!this.walletClient)throw new Error("Wallet client not found");await this.walletClient.module("balance").waitForUpdate();const u=this.walletClient.module("balance").portfolio.getBalance(e),i=new w.Transaction,r=l.mergeCoinsPTB(i,u.coins,{balance:t,useGasCoin:!0}),o=await this.getQuote(e,a,t),d=await this.buildSwapPTBFromQuote(i,o,r,s);i.transferObjects([d],this.walletClient.address);const h=await this.walletClient.signExecuteTransaction({transaction:i,dryRun:(g=n==null?void 0:n.dryRun)!=null?g:!1});if(!(n!=null&&n.dryRun)&&((y=(f=h.effects)==null?void 0:f.status)==null?void 0:y.status)==="success"){const C=(m=h.events)==null?void 0:m.find(b=>b.type.includes("::slippage::SwapEvent"));C&&this.emit("swap:swap-success",{fromCoinType:e,toCoinType:a,fromAmount:t,slippage:s,toAmount:Number(C.parsedJson.amount_out)}),this.walletClient.module("balance").updatePortfolio()}return h}}class X extends E{constructor(){super(...arguments),this.name="haedal",this.defaultConfig={packageId:"0x3f45767c1aa95b25422f675800f02d8a813ec793a00b60667d071a77ba7178a2",configId:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",coinType:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"},this.getApy=l.withCache(l.withSingleton(async()=>(await fetch("https://open-api.naviprotocol.io/api/haedal/stats").then(a=>a.json())).data.apy))}async stakePTB(e,a){const[t]=e.moveCall({target:`${this.config.packageId}::staking::request_stake_coin`,arguments:[e.object("0x05"),e.object(this.config.configId),l.parseTxValue(a,e.object),e.pure.address("0x0000000000000000000000000000000000000000000000000000000000000000")],typeArguments:[]});return t}async unstakePTB(e,a){const[t]=e.moveCall({target:`${this.config.packageId}::staking::request_unstake_instant_coin`,arguments:[e.object("0x05"),e.object(this.config.configId),l.parseTxValue(a,e.object)],typeArguments:[]});return t}async stake(e,a){var r,o,d;if(!this.walletClient)throw new Error("Wallet client not found");const t=new w.Transaction;await this.walletClient.module("balance").waitForUpdate();const s=this.walletClient.module("balance").portfolio.getBalance("0x2::sui::SUI"),n=l.mergeCoinsPTB(t,s.coins,{balance:e,useGasCoin:!0}),u=await this.stakePTB(t,n);t.transferObjects([u],this.walletClient.address);const i=await this.walletClient.signExecuteTransaction({transaction:t,dryRun:(r=a==null?void 0:a.dryRun)!=null?r:!1});return!(a!=null&&a.dryRun)&&((d=(o=i.effects)==null?void 0:o.status)==null?void 0:d.status)==="success"&&(this.emit("haedal:stake-success",{suiAmount:e}),this.walletClient.module("balance").updatePortfolio()),i}async unstake(e,a){var r,o,d;if(!this.walletClient)throw new Error("Wallet client not found");await this.walletClient.module("balance").waitForUpdate();const t=new w.Transaction,s=this.walletClient.module("balance").portfolio.getBalance(this.config.coinType),n=l.mergeCoinsPTB(t,s.coins,{balance:e}),u=await this.unstakePTB(t,n);t.transferObjects([u],this.walletClient.address);const i=await this.walletClient.signExecuteTransaction({transaction:t,dryRun:(r=a==null?void 0:a.dryRun)!=null?r:!1});return!(a!=null&&a.dryRun)&&((d=(o=i.effects)==null?void 0:o.status)==null?void 0:d.status)==="success"&&(this.emit("haedal:unstake-success",{haSUIAmount:e}),this.walletClient.module("balance").updatePortfolio()),i}}const Y={balance:new z,lending:new D,volo:new J,swap:new V,haedal:new X},Z={url:q.getFullnodeUrl("mainnet")};class ee{constructor(e){this.modules=Y,this.userConfigs={},this.events=Q();const a={...Z,...e.client};a.transport=a.transport||new $(a.url),this.client=new q.SuiClient(a),this.signer=e.signer,this.userConfigs=e.configs||{},Object.entries(this.modules).forEach(([t,s])=>{if(t!==s.name)throw new Error(`Module name ${t} does not match module name ${s.name}`);s.install(this)})}get lending(){return this.modules.lending}get balance(){return this.modules.balance}get volo(){return this.modules.volo}get swap(){return this.modules.swap}get haedal(){return this.modules.haedal}async signExecuteTransaction(e){const{dryRun:a=!1,...t}=e;if(a){let s;return e.transaction instanceof w.Transaction?(e.transaction.setSenderIfNotSet(this.address),s=await e.transaction.build({client:this.client})):s=e.transaction,this.client.dryRunTransactionBlock({transactionBlock:s})}return this.client.signAndExecuteTransaction({...t,signer:this.signer})}get address(){return this.signer.getPublicKey().toSuiAddress()}module(e){return this.modules[e]}config(e){return{...this.modules[e].defaultConfig,...this.userConfigs[e]}}hasModule(e){return e in this.modules}}class te extends L.Signer{constructor(e){super(),this.address=e}async sign(e){return new Uint8Array([])}getPublicKey(){return{toSuiAddress:()=>this.address,toBytes:()=>new Uint8Array(32),toRawBytes:()=>new Uint8Array(32),flag:0,verify:async()=>!1}}getKeyScheme(){return"ed25519"}async signAndExecuteTransaction({transaction:e,client:a}){return{}}}class ae extends L.Signer{constructor(e){super(),this.address=e}async sign(e){return new Uint8Array([])}getPublicKey(){return{toSuiAddress:()=>this.address,toBytes:()=>new Uint8Array(32),toRawBytes:()=>new Uint8Array(32),flag:0,verify:async()=>!1}}getKeyScheme(){return"ed25519"}}exports.WalletClient=ee;exports.WatchSigner=te;exports.WebSigner=ae;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=require("@mysten/sui/client"),Q=require("mitt"),K=require("axios"),l=require("@naviprotocol/lending"),T=require("bignumber.js"),B=require("@mysten/sui/utils"),w=require("@mysten/sui/transactions"),v=require("@naviprotocol/astros-aggregator-sdk"),L=require("@mysten/sui/cryptography"),M=K.create({timeout:2e4});M.interceptors.response.use(function(c){if(c.data.err)throw new Error(c.data.err);if(c.data.error)throw new Error(c.data.error.message);return c},function(c){return Promise.reject(c)});class ${constructor(e){this.requestId=0,this.rpcUrl=e}async request(e){return this.requestId+=1,(await M.post(this.rpcUrl,{jsonrpc:"2.0",id:this.requestId,method:e.method,params:e.params})).data.result}async subscribe(){throw new Error("subscribe not implemented.")}}class E{get config(){return this.walletClient?this.walletClient.config(this.name):this.defaultConfig}emit(e,a){var t;(t=this.walletClient)==null||t.events.emit(e,a)}install(e){this.walletClient=e}uninstall(){this.walletClient=void 0}}class p{constructor(e){if(e instanceof p)this.balances=JSON.parse(JSON.stringify(e.balances));else{const a={};e==null||e.forEach(t=>{const s=B.normalizeStructTag(t.coinType);let n=a[s];n||(n={coinType:s,amount:T.BigNumber(0),coins:[]},a[s]=n),n.coins.push(t),n.amount=n.amount.plus(t.balance)}),this.balances=a}}getBalance(e){return e=B.normalizeStructTag(e),this.balances[e]||{coinType:e,amount:T.BigNumber(0),coins:[]}}getCoinTypes(){return Object.values(this.balances).map(e=>e.coinType)}balanceOf(e){e=B.normalizeStructTag(e);const a=this.getBalance(e);return(a==null?void 0:a.amount)||T.BigNumber(0)}clone(){const e=JSON.parse(JSON.stringify(this.balances)),a=new p;return a.balances=e,a}}class z extends E{constructor(){super(...arguments),this.name="balance",this.defaultConfig={coinPollingInterval:6e3},this.updatePortfolio=l.withSingleton(async()=>{if(!this.walletClient)throw new Error("Wallet client not found");this._coins=await l.getCoins(this.walletClient.address,{client:this.walletClient.client}),this._portfolio=new p(this._coins),this.emit("balance:portfolio-updated",{})}),this._coins=[],this._portfolio=new p,this.pollingTimer=null,this._updatePromise=null}get coins(){return this._coins}get portfolio(){return this._portfolio}async waitForUpdate(){if(!this._updatePromise)throw new Error("Update promise not found");return await this._updatePromise}async sendCoin(e,a,t,s){return this.sendCoinBatch(e,[a],[t],s)}async sendCoinBatch(e,a,t,s){var h;if(!this.walletClient)throw new Error("Wallet client not found");if(a.length!==t.length)throw new Error("Recipients and amounts must have the same length");await this.waitForUpdate();const n=this.portfolio.getBalance(e),u=t.reduce((g,f)=>g.plus(f),T(0));if(n.amount.lt(u))throw new Error("Insufficient balance");const r=new w.Transaction;let i=r.gas;B.normalizeStructTag(e)!==B.normalizeStructTag("0x2::sui::SUI")&&(i=l.mergeCoinsPTB(r,n.coins,{balance:u.toNumber()}));const o=r.splitCoins(i,t);return a.forEach((g,f)=>{r.transferObjects([o[f]],g)}),await this.walletClient.signExecuteTransaction({transaction:r,dryRun:(h=s==null?void 0:s.dryRun)!=null?h:!1})}async transferObject(e,a,t){return this.transferObjectBatch([e],[a],t)}async transferObjectBatch(e,a,t){var u;if(!this.walletClient)throw new Error("Wallet client not found");if(e.length!==a.length)throw new Error("Objects and recipients must have the same length");await this.waitForUpdate();const s=new w.Transaction;return e.forEach((r,i)=>{s.transferObjects([s.object(r)],a[i])}),await this.walletClient.signExecuteTransaction({transaction:s,dryRun:(u=t==null?void 0:t.dryRun)!=null?u:!1})}async startPolling(){try{await this.updatePortfolio()}catch(e){console.error(e)}finally{this.pollingTimer=setTimeout(this.startPolling,this.config.coinPollingInterval)}}install(e){super.install(e),this.startPolling=this.startPolling.bind(this),this.startPolling(),this._updatePromise=new Promise(a=>{e.events.on("balance:portfolio-updated",()=>{a()})})}uninstall(){super.uninstall(),this.pollingTimer&&(clearTimeout(this.pollingTimer),this.pollingTimer=null)}}const G=27;function H(c,e=2){return c?new T(c.toString()).shiftedBy(-1*G).multipliedBy(100).decimalPlaces(e,T.ROUND_DOWN).toFixed(e):"0.00"}async function W(c,e,a,t){var S,R;if(!this.walletClient)throw new Error("Wallet client not found");await this.walletClient.balance.waitForUpdate();const s=await this.getPool(e),n=await this.getPool(a),r=(await this.getLendingState()).find(F=>F.pool.id===s.id),i=this.walletClient.address;if(!r||r.supplyBalance==="0")throw new Error("No supply balance");if(t!=null&&t.amount&&t.amount<Number(r.supplyBalance))throw new Error("Amount is less than supply balance");const o=await l.getFlashLoanAsset(n,{env:this.config.env});if(!(o!=null&&o.flashloanFee))throw new Error(`${s.token.symbol} pool not support flashloan`);const d=(S=t==null?void 0:t.slippage)!=null?S:.005,h=(R=t==null?void 0:t.amount)!=null?R:Number(r.supplyBalance),g=await this.walletClient.swap.getQuote(s.suiCoinType,n.suiCoinType,h),f=Number(g.amount_out);if(f<=0)throw new Error("The amount of swapAmountOut must be greater than 0.");const y=Math.floor(f*(1-d)),m=Math.floor(y/(1+o.flashloanFee));if(m<=0)throw new Error("The calculated borrow amount must be positive.");const[C,b]=await l.flashloanPTB(c,n,m),[P]=c.moveCall({target:"0x2::coin::from_balance",arguments:[C],typeArguments:[n.suiCoinType]});await l.depositCoinPTB(c,n,P,{amount:m});const O=await l.withdrawCoinPTB(c,s,h),x=await v.buildSwapPTBFromQuote(i,c,y,O,g),A=c.moveCall({target:"0x2::coin::into_balance",arguments:[x],typeArguments:[n.suiCoinType]}),[k]=await l.repayFlashLoanPTB(c,n,b,A),[j]=c.moveCall({target:"0x2::coin::from_balance",arguments:[k],typeArguments:[n.suiCoinType]});return await l.depositCoinPTB(c,n,j),c}async function N(c,e,a,t){var F,_;if(!this.walletClient)throw new Error("Wallet client not found");await this.walletClient.balance.waitForUpdate();const s=this.walletClient.address,n=await this.getPool(e),u=await this.getPool(a),i=(await this.getLendingState()).find(U=>U.pool.id===n.id);if(!i||i.borrowBalance==="0")throw new Error("No borrow balance");if(t!=null&&t.amount&&t.amount<Number(i.borrowBalance))throw new Error("Amount is less than borrow balance");let o=(F=t==null?void 0:t.amount)!=null?F:Number(i.borrowBalance);if(Number(i.borrowBalance)===o){const U=parseFloat(H(n.currentBorrowRate,8))/100;o=Math.ceil(new T(o).multipliedBy(U*(60*3)/(365*24*3600)).plus(new T(1).shiftedBy(-n.token.decimals)).plus(o).toNumber())}const d=await l.getFlashLoanAsset(n,{env:this.config.env});if(!d)throw new Error(`${n.token.symbol} pool not support flashloan`);if(!this.walletClient)throw new Error("Wallet client not found");const h=(_=t==null?void 0:t.slippage)!=null?_:.005,g=Math.ceil(o*(1+d.flashloanFee)),f=g,y=await this.walletClient.swap.getQuote(n.suiCoinType,u.suiCoinType,f);let m=1+h,C=Math.ceil(Number(y.amount_out)*m),b=await this.walletClient.swap.getQuote(u.suiCoinType,n.suiCoinType,C);for(;Number(b.amount_out)<f;)m=m*Math.max(f/Number(b.amount_out),1.001),C=Math.ceil(Number(y.amount_out)*m),b=await this.walletClient.swap.getQuote(u.suiCoinType,n.suiCoinType,C);const[P,O]=await l.flashloanPTB(c,n,o),[x]=c.moveCall({target:"0x2::coin::from_balance",arguments:[P],typeArguments:[n.suiCoinType]});await l.repayCoinPTB(c,n,x,{amount:o});const A=await l.borrowCoinPTB(c,u,C),k=await v.buildSwapPTBFromQuote(s,c,g,A,b),j=c.moveCall({target:"0x2::coin::into_balance",arguments:[k],typeArguments:[n.suiCoinType]}),[S]=await l.repayFlashLoanPTB(c,n,O,j),[R]=c.moveCall({target:"0x2::coin::from_balance",arguments:[S],typeArguments:[n.suiCoinType]});return c.transferObjects([R],s),c}async function I(c,e,a,t){var o,d;if(!this.walletClient)throw new Error("Wallet client not found");await this.walletClient.balance.waitForUpdate(),this.walletClient.address;const s=await this.getPool(a),n=this.walletClient.balance.portfolio.getBalance(e);if(n.amount.eq(0))throw new Error(`No balance of ${e}`);if(t!=null&&t.amount&&n.amount.lt(t.amount))throw new Error("Amount is less than balance");const u=(o=t==null?void 0:t.amount)!=null?o:n.amount.toNumber(),r=(d=t==null?void 0:t.slippage)!=null?d:.005;let i=await l.mergeCoinsPTB(c,n.coins,{balance:u,useGasCoin:!0});if(B.normalizeStructTag(e)!==B.normalizeStructTag(s.suiCoinType)){const h=await this.walletClient.swap.getQuote(e,s.suiCoinType,u);i=await this.walletClient.swap.buildSwapPTBFromQuote(c,h,i,r)}return await l.depositCoinPTB(c,s,i),c}class D extends E{constructor(){super(),this.name="lending",this.defaultConfig={env:"prod"},this.migrateSupplyPTB=W,this.migrateBorrowPTB=N,this.migrateBalanceToSupplyPTB=I,this.migrateSupplyPTB=W.bind(this),this.migrateBorrowPTB=N.bind(this),this.migrateBalanceToSupplyPTB=I.bind(this)}async getPools(e){return await l.getPools({env:this.config.env,...e})}async getPool(e,a){return await l.getPool(e,{env:this.config.env,...a})}async deposit(e,a,t){var o,d,h;if(!this.walletClient)throw new Error("Wallet client not found");const s=await l.getPool(e,{env:this.config.env});await this.walletClient.module("balance").waitForUpdate();const n=new w.Transaction,u=this.walletClient.module("balance").portfolio.getBalance(s.suiCoinType),r=l.mergeCoinsPTB(n,u.coins,{balance:a,useGasCoin:!0});await l.depositCoinPTB(n,s,r,{env:this.config.env,amount:a,accountCap:t==null?void 0:t.accountCap});const i=await this.walletClient.signExecuteTransaction({transaction:n,dryRun:(o=t==null?void 0:t.dryRun)!=null?o:!1});return!(t!=null&&t.dryRun)&&((h=(d=i.effects)==null?void 0:d.status)==null?void 0:h.status)==="success"&&(this.emit("lending:deposit-success",{identifier:e,amount:a}),this.walletClient.module("balance").updatePortfolio()),i}async withdraw(e,a,t){var i,o,d;if(!this.walletClient)throw new Error("Wallet client not found");const s=await l.getPool(e,{env:this.config.env}),n=new w.Transaction;t!=null&&t.disableUpdateOracle||await this.updateOraclePTB(n,[s]);const u=await l.withdrawCoinPTB(n,s,a,{env:this.config.env,accountCap:t==null?void 0:t.accountCap});n.transferObjects([u],this.walletClient.address);const r=await this.walletClient.signExecuteTransaction({transaction:n,dryRun:(i=t==null?void 0:t.dryRun)!=null?i:!1});return!(t!=null&&t.dryRun)&&((d=(o=r.effects)==null?void 0:o.status)==null?void 0:d.status)==="success"&&(this.emit("lending:withdraw-success",{identifier:e,amount:a}),this.walletClient.module("balance").updatePortfolio()),r}async borrow(e,a,t){var i,o,d;if(!this.walletClient)throw new Error("Wallet client not found");const s=await l.getPool(e,{env:this.config.env}),n=new w.Transaction;t!=null&&t.disableUpdateOracle||await this.updateOraclePTB(n,[s]);const u=await l.borrowCoinPTB(n,s,a,{env:this.config.env,accountCap:t==null?void 0:t.accountCap});n.transferObjects([u],this.walletClient.address);const r=await this.walletClient.signExecuteTransaction({transaction:n,dryRun:(i=t==null?void 0:t.dryRun)!=null?i:!1});return!(t!=null&&t.dryRun)&&((d=(o=r.effects)==null?void 0:o.status)==null?void 0:d.status)==="success"&&(this.emit("lending:borrow-success",{identifier:e,amount:a}),this.walletClient.module("balance").updatePortfolio()),r}async repay(e,a,t){var o,d,h;if(!this.walletClient)throw new Error("Wallet client not found");await this.walletClient.module("balance").waitForUpdate();const s=await l.getPool(e,{env:this.config.env}),n=new w.Transaction,u=this.walletClient.module("balance").portfolio.getBalance(s.suiCoinType),r=l.mergeCoinsPTB(n,u.coins,{balance:a,useGasCoin:!0});await l.repayCoinPTB(n,s,r,{env:this.config.env,amount:a,accountCap:t==null?void 0:t.accountCap});const i=await this.walletClient.signExecuteTransaction({transaction:n,dryRun:(o=t==null?void 0:t.dryRun)!=null?o:!1});return!(t!=null&&t.dryRun)&&((h=(d=i.effects)==null?void 0:d.status)==null?void 0:h.status)==="success"&&(this.emit("lending:repay-success",{identifier:e,amount:a}),this.walletClient.module("balance").updatePortfolio()),i}async getHealthFactor(){if(!this.walletClient)throw new Error("Wallet client not found");const e=this.walletClient.address;return await l.getHealthFactor(e,{env:this.config.env,client:this.walletClient.client})}async liquidate(e,a,t,s,n){var C,b,P;if(!this.walletClient)throw new Error("Wallet client not found");const u=await l.getPool(e,{env:this.config.env}),r=await l.getPool(t,{env:this.config.env}),i=new w.Transaction,o=this.walletClient.module("balance").portfolio.getBalance(u.suiCoinType),d=l.mergeCoinsPTB(i,o.coins,{balance:a,useGasCoin:!0}),[h,g]=await l.liquidatePTB(i,u,d,r,s,{env:this.config.env}),[f]=i.moveCall({target:"0x2::coin::from_balance",arguments:[h],typeArguments:[r.suiCoinType]}),[y]=i.moveCall({target:"0x2::coin::from_balance",arguments:[g],typeArguments:[u.suiCoinType]});i.transferObjects([f,y],this.walletClient.address);const m=await this.walletClient.signExecuteTransaction({transaction:i,dryRun:(C=n==null?void 0:n.dryRun)!=null?C:!1});return!(n!=null&&n.dryRun)&&((P=(b=m.effects)==null?void 0:b.status)==null?void 0:P.status)==="success"&&(this.emit("lending:liquidate-success",{payIdentifier:e,payAmount:a,collateralIdentifier:t,liquidationAddress:s}),this.walletClient.module("balance").updatePortfolio()),m}async getAvailableRewards(e){if(!this.walletClient)throw new Error("Wallet client not found");return l.getUserAvailableLendingRewards(this.walletClient.address,{...e,env:this.config.env})}async getClaimedRewardHistory(e){if(!this.walletClient)throw new Error("Wallet client not found");return l.getUserClaimedRewardHistory(this.walletClient.address,{...e})}async claimAllRewards(e){var n,u,r;if(!this.walletClient)throw new Error("Wallet client not found");const a=new w.Transaction,t=await l.getUserAvailableLendingRewards(this.walletClient.address,{env:this.config.env});await l.claimLendingRewardsPTB(a,t,{env:this.config.env,accountCap:e==null?void 0:e.accountCap});const s=await this.walletClient.signExecuteTransaction({transaction:a,dryRun:(n=e==null?void 0:e.dryRun)!=null?n:!1});return!(e!=null&&e.dryRun)&&((r=(u=s.effects)==null?void 0:u.status)==null?void 0:r.status)==="success"&&(this.emit("lending:claim-rewards-success",{rewards:t}),this.walletClient.module("balance").updatePortfolio()),s}async updateOraclePTB(e,a){const t=await l.getPriceFeeds({env:this.config.env}),s=await this.getLendingState({cacheTime:60*1e3}),n=l.filterPriceFeeds(t,{lendingState:s,pools:a});await l.updateOraclePricesPTB(e,n,{env:this.config.env,updatePythPriceFeeds:!0})}async updateOracle(e){var s;if(!this.walletClient)throw new Error("Wallet client not found");const a=new w.Transaction;return await this.updateOraclePTB(a,e==null?void 0:e.pools),await this.walletClient.signExecuteTransaction({transaction:a,dryRun:(s=e==null?void 0:e.dryRun)!=null?s:!1})}async getLendingState(e){if(!this.walletClient)throw new Error("Wallet client not found");return await l.getLendingState(this.walletClient.address,{env:this.config.env,...e,client:this.walletClient.client})}async createAccountCap(e){var n;if(!this.walletClient)throw new Error("Wallet client not found");const a=new w.Transaction,t=await l.createAccountCapPTB(a);return a.transferObjects([t],this.walletClient.address),await this.walletClient.signExecuteTransaction({transaction:a,dryRun:(n=e==null?void 0:e.dryRun)!=null?n:!1})}}class J extends E{constructor(){super(...arguments),this.name="volo",this.defaultConfig={packageId:"0x68d22cf8bdbcd11ecba1e094922873e4080d4d11133e2443fddda0bfd11dae20",poolId:"0x2d914e23d82fedef1b5f56a32d5c64bdcc3087ccfea2b4d6ea51a71f587840e5",metadataId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",coinType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT"},this.getStats=l.withCache(l.withSingleton(async()=>(await fetch("https://open-api.naviprotocol.io/api/volo/stats").then(a=>a.json())).data))}async stakePTB(e,a){const[t]=e.moveCall({target:`${this.config.packageId}::stake_pool::stake`,arguments:[e.object(this.config.poolId),e.object(this.config.metadataId),e.object("0x05"),l.parseTxValue(a,e.object)],typeArguments:[]});return t}async unstakePTB(e,a){const[t]=e.moveCall({target:`${this.config.packageId}::stake_pool::unstake`,arguments:[e.object(this.config.poolId),e.object(this.config.metadataId),e.object("0x05"),l.parseTxValue(a,e.object)],typeArguments:[]});return t}async stake(e,a){var i,o,d;if(!this.walletClient)throw new Error("Wallet client not found");if(e<1e9)throw new Error("Stake amount should be greater than 1Sui");const t=new w.Transaction;await this.walletClient.module("balance").waitForUpdate();const s=this.walletClient.module("balance").portfolio.getBalance("0x2::sui::SUI"),n=l.mergeCoinsPTB(t,s.coins,{balance:e,useGasCoin:!0}),u=await this.stakePTB(t,n);t.transferObjects([u],this.walletClient.address);const r=await this.walletClient.signExecuteTransaction({transaction:t,dryRun:(i=a==null?void 0:a.dryRun)!=null?i:!1});return!(a!=null&&a.dryRun)&&((d=(o=r.effects)==null?void 0:o.status)==null?void 0:d.status)==="success"&&(this.emit("volo:stake-success",{suiAmount:e}),this.walletClient.module("balance").updatePortfolio()),r}async unstake(e,a){var i,o,d;if(!this.walletClient)throw new Error("Wallet client not found");if(e<1e9)throw new Error("Unstake amount should >= 1vSui");await this.walletClient.module("balance").waitForUpdate();const t=new w.Transaction,s=this.walletClient.module("balance").portfolio.getBalance(this.config.coinType),n=l.mergeCoinsPTB(t,s.coins,{balance:e}),u=await this.unstakePTB(t,n);t.transferObjects([u],this.walletClient.address);const r=await this.walletClient.signExecuteTransaction({transaction:t,dryRun:(i=a==null?void 0:a.dryRun)!=null?i:!1});return!(a!=null&&a.dryRun)&&((d=(o=r.effects)==null?void 0:o.status)==null?void 0:d.status)==="success"&&(this.emit("volo:unstake-success",{vSuiAmount:e}),this.walletClient.module("balance").updatePortfolio()),r}}class V extends E{constructor(){super(...arguments),this.name="swap",this.defaultConfig={apiKey:"",baseUrl:"https://open-aggregator-api.naviprotocol.io/find_routes",dexList:[],depth:3,serviceFee:void 0,env:"prod"}}get referral(){return this.config.apiKey?v.generateRefId(this.config.apiKey):0}get swapOptions(){return{baseUrl:this.config.baseUrl,dexList:this.config.dexList,depth:this.config.depth,serviceFee:this.config.serviceFee}}async getQuote(e,a,t){return v.getQuote(e,a,t,this.config.apiKey,this.swapOptions)}async buildSwapPTBFromQuote(e,a,t,s){if(!this.walletClient)throw new Error("Wallet client not found");const n=new T(a.amount_out).multipliedBy(1-s).toFixed(0);return await v.buildSwapPTBFromQuote(this.walletClient.address,e,Number(n),t,a,this.referral,!1,this.config.apiKey,this.swapOptions)}async swap(e,a,t,s,n){var g,f,y,m;if(!this.walletClient)throw new Error("Wallet client not found");await this.walletClient.module("balance").waitForUpdate();const u=this.walletClient.module("balance").portfolio.getBalance(e),r=new w.Transaction,i=l.mergeCoinsPTB(r,u.coins,{balance:t,useGasCoin:!0}),o=await this.getQuote(e,a,t),d=await this.buildSwapPTBFromQuote(r,o,i,s);r.transferObjects([d],this.walletClient.address);const h=await this.walletClient.signExecuteTransaction({transaction:r,dryRun:(g=n==null?void 0:n.dryRun)!=null?g:!1});if(!(n!=null&&n.dryRun)&&((y=(f=h.effects)==null?void 0:f.status)==null?void 0:y.status)==="success"){const C=(m=h.events)==null?void 0:m.find(b=>b.type.includes("::slippage::SwapEvent"));C&&this.emit("swap:swap-success",{fromCoinType:e,toCoinType:a,fromAmount:t,slippage:s,toAmount:Number(C.parsedJson.amount_out)}),this.walletClient.module("balance").updatePortfolio()}return h}}class X extends E{constructor(){super(...arguments),this.name="haedal",this.defaultConfig={packageId:"0x3f45767c1aa95b25422f675800f02d8a813ec793a00b60667d071a77ba7178a2",configId:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",coinType:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"},this.getApy=l.withCache(l.withSingleton(async()=>(await fetch("https://open-api.naviprotocol.io/api/haedal/stats").then(a=>a.json())).data.apy))}async stakePTB(e,a){const[t]=e.moveCall({target:`${this.config.packageId}::staking::request_stake_coin`,arguments:[e.object("0x05"),e.object(this.config.configId),l.parseTxValue(a,e.object),e.pure.address("0x0000000000000000000000000000000000000000000000000000000000000000")],typeArguments:[]});return t}async unstakePTB(e,a){const[t]=e.moveCall({target:`${this.config.packageId}::staking::request_unstake_instant_coin`,arguments:[e.object("0x05"),e.object(this.config.configId),l.parseTxValue(a,e.object)],typeArguments:[]});return t}async stake(e,a){var i,o,d;if(!this.walletClient)throw new Error("Wallet client not found");const t=new w.Transaction;await this.walletClient.module("balance").waitForUpdate();const s=this.walletClient.module("balance").portfolio.getBalance("0x2::sui::SUI"),n=l.mergeCoinsPTB(t,s.coins,{balance:e,useGasCoin:!0}),u=await this.stakePTB(t,n);t.transferObjects([u],this.walletClient.address);const r=await this.walletClient.signExecuteTransaction({transaction:t,dryRun:(i=a==null?void 0:a.dryRun)!=null?i:!1});return!(a!=null&&a.dryRun)&&((d=(o=r.effects)==null?void 0:o.status)==null?void 0:d.status)==="success"&&(this.emit("haedal:stake-success",{suiAmount:e}),this.walletClient.module("balance").updatePortfolio()),r}async unstake(e,a){var i,o,d;if(!this.walletClient)throw new Error("Wallet client not found");await this.walletClient.module("balance").waitForUpdate();const t=new w.Transaction,s=this.walletClient.module("balance").portfolio.getBalance(this.config.coinType),n=l.mergeCoinsPTB(t,s.coins,{balance:e}),u=await this.unstakePTB(t,n);t.transferObjects([u],this.walletClient.address);const r=await this.walletClient.signExecuteTransaction({transaction:t,dryRun:(i=a==null?void 0:a.dryRun)!=null?i:!1});return!(a!=null&&a.dryRun)&&((d=(o=r.effects)==null?void 0:o.status)==null?void 0:d.status)==="success"&&(this.emit("haedal:unstake-success",{haSUIAmount:e}),this.walletClient.module("balance").updatePortfolio()),r}}const Y={balance:new z,lending:new D,volo:new J,swap:new V,haedal:new X},Z={url:q.getFullnodeUrl("mainnet")};class ee{constructor(e){this.modules=Y,this.userConfigs={},this.events=Q();const a={...Z,...e.client};a.transport=a.transport||new $(a.url),this.client=new q.SuiClient(a),this.signer=e.signer,this.userConfigs=e.configs||{},Object.entries(this.modules).forEach(([t,s])=>{if(t!==s.name)throw new Error(`Module name ${t} does not match module name ${s.name}`);s.install(this)})}get lending(){return this.modules.lending}get balance(){return this.modules.balance}get volo(){return this.modules.volo}get swap(){return this.modules.swap}get haedal(){return this.modules.haedal}async signExecuteTransaction(e){const{dryRun:a=!1,...t}=e;if(a){let s;return e.transaction instanceof w.Transaction?(e.transaction.setSenderIfNotSet(this.address),s=await e.transaction.build({client:this.client})):s=e.transaction,this.client.dryRunTransactionBlock({transactionBlock:s})}return this.client.signAndExecuteTransaction({...t,signer:this.signer})}get address(){return this.signer.getPublicKey().toSuiAddress()}module(e){return this.modules[e]}config(e){return{...this.modules[e].defaultConfig,...this.userConfigs[e]}}hasModule(e){return e in this.modules}}class te extends L.Signer{constructor(e){super(),this.address=e}async sign(e){return new Uint8Array([])}getPublicKey(){return{toSuiAddress:()=>this.address,toBytes:()=>new Uint8Array(32),toRawBytes:()=>new Uint8Array(32),flag:0,verify:async()=>!1}}getKeyScheme(){return"ed25519"}async signAndExecuteTransaction({transaction:e,client:a}){return{}}}class ae extends L.Signer{constructor(e){super(),this.address=e}async sign(e){return new Uint8Array([])}getPublicKey(){return{toSuiAddress:()=>this.address,toBytes:()=>new Uint8Array(32),toRawBytes:()=>new Uint8Array(32),flag:0,verify:async()=>!1}}getKeyScheme(){return"ed25519"}}exports.WalletClient=ee;exports.WatchSigner=te;exports.WebSigner=ae;
2
2
  //# sourceMappingURL=index.cjs.js.map