@naviprotocol/wallet-client 1.4.6 → 1.4.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +507 -529
- package/dist/index.esm.js.map +1 -1
- package/package.json +3 -3
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const G=require("@mysten/sui/client"),V=require("mitt"),Y=require("axios"),s=require("@naviprotocol/lending"),B=require("bignumber.js"),P=require("@mysten/sui/utils"),C=require("@mysten/sui/transactions"),O=require("@naviprotocol/astros-aggregator-sdk"),v=require("@suilend/sdk"),z=require("@suilend/sui-fe"),X=require("shio-sdk"),D=require("@mysten/sui/cryptography"),H=Y.create({timeout:2e4});H.interceptors.response.use(function(l){if(l.data.err)throw new Error(l.data.err);if(l.data.error)throw new Error(l.data.error.message);return l},function(l){return Promise.reject(l)});class Z{constructor(e){this.requestId=0,this.rpcUrl=e}async request(e){return this.requestId+=1,(await H.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 F{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 R{constructor(e){if(e instanceof R)this.balances=JSON.parse(JSON.stringify(e.balances));else{const a={};e==null||e.forEach(t=>{const i=P.normalizeStructTag(t.coinType);let n=a[i];n||(n={coinType:i,amount:B.BigNumber(0),coins:[]},a[i]=n),n.coins.push(t),n.amount=n.amount.plus(t.balance)}),this.balances=a}}getBalance(e){return e=P.normalizeStructTag(e),this.balances[e]||{coinType:e,amount:B.BigNumber(0),coins:[]}}getCoinTypes(){return Object.values(this.balances).map(e=>e.coinType)}balanceOf(e){e=P.normalizeStructTag(e);const a=this.getBalance(e);return(a==null?void 0:a.amount)||B.BigNumber(0)}clone(){const e=JSON.parse(JSON.stringify(this.balances)),a=new R;return a.balances=e,a}}class ee extends F{constructor(){super(...arguments),this.name="balance",this.defaultConfig={coinPollingInterval:6e3,disableCoinPolling:!1},this.updatePortfolio=s.withSingleton(async()=>{if(!this.walletClient)throw new Error("Wallet client not found");this._coins=await s.getCoins(this.walletClient.address,{client:this.walletClient.client}),this._portfolio=new R(this._coins),this.emit("balance:portfolio-updated",{})}),this._coins=[],this._portfolio=new R,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,i){return this.sendCoinBatch(e,[a],[t],i)}async sendCoinBatch(e,a,t,i){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),d=t.reduce((g,f)=>g.plus(f),B(0));if(n.amount.lt(d))throw new Error("Insufficient balance");const r=new C.Transaction;let o=r.gas;P.normalizeStructTag(e)!==P.normalizeStructTag("0x2::sui::SUI")&&(o=s.mergeCoinsPTB(r,n.coins,{balance:d.toNumber()}));const u=r.splitCoins(o,t);return a.forEach((g,f)=>{r.transferObjects([u[f]],g)}),await this.walletClient.signExecuteTransaction({transaction:r,dryRun:(h=i==null?void 0:i.dryRun)!=null?h:!1})}async transferObject(e,a,t){return this.transferObjectBatch([e],[a],t)}async transferObjectBatch(e,a,t){var d;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 i=new C.Transaction;return e.forEach((r,o)=>{i.transferObjects([i.object(r)],a[o])}),await this.walletClient.signExecuteTransaction({transaction:i,dryRun:(d=t==null?void 0:t.dryRun)!=null?d:!1})}async startPolling(){try{if(this.config.disableCoinPolling)return;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)}}async function Q(l,e,a,t){var k,x,A;if(!this.walletClient)throw new Error("Wallet client not found");const i=await this.getPool(e),n=await this.getPool(a),d=await this.getLendingState(),r=this.walletClient.address,o=(k=t==null?void 0:t.protocol)!=null?k:"navi",u=await this.getProtocol(o);if(!u)throw new Error(`Protocol ${o} not found`);const c=await u.getPool(i.coinType);if(console.log("migrateBetweenSupplyPTB",{fromPoolLending:c}),o==="navi"&&c.supplyBalance===0)throw new Error("No supply balance");if(t!=null&&t.amount&&t.amount>c.supplyBalance)throw new Error("Amount is less than supply balance");const h=(x=t==null?void 0:t.slippage)!=null?x:.005,g=(A=t==null?void 0:t.amount)!=null?A:Number(c.supplyBalance),f=await s.getPriceFeeds(),y=await Promise.all([i,n]);if(await s.updateOraclePricesPTB(l,s.filterPriceFeeds(f,{lendingState:d,pools:y})),o!=="navi"&&i.id===n.id){const N=await u.withdrawCoinPTB(l,i.suiCoinType,g);return await s.depositCoinPTB(l,n,N,{amount:g}),l}const T=await s.getFlashLoanAsset(n,{env:this.config.env});if(!T)throw new Error(`${n.token.symbol} pool not support flashloan`);const w=await this.walletClient.swap.getQuote(i.suiCoinType,n.suiCoinType,g),m=Number(w.amount_out);if(m<=0)throw new Error("The amount of swapAmountOut must be greater than 0.");const b=Math.floor(m*(1-h)),p=Math.floor(b/(1+T.flashloanFee));if(p<=0)throw new Error("The calculated borrow amount must be positive.");const[E,S]=await s.flashloanPTB(l,n,p),[_]=l.moveCall({target:"0x2::coin::from_balance",arguments:[E],typeArguments:[n.suiCoinType]});await s.depositCoinPTB(l,n,_,{amount:p});const j=await u.withdrawCoinPTB(l,i.suiCoinType,g),I=await O.buildSwapPTBFromQuote(r,l,b,j,w),U=l.moveCall({target:"0x2::coin::into_balance",arguments:[I],typeArguments:[n.suiCoinType]}),[W]=await s.repayFlashLoanPTB(l,n,S,U),[M]=l.moveCall({target:"0x2::coin::from_balance",arguments:[W],typeArguments:[n.suiCoinType]});return await s.depositCoinPTB(l,n,M),l}async function K(l,e,a,t){var A,N,L;if(!this.walletClient)throw new Error("Wallet client not found");const i=this.walletClient.address,n=await this.getPool(e),d=await this.getPool(a),r=await this.getLendingState(),o=(A=t==null?void 0:t.protocol)!=null?A:"navi",u=await this.getProtocol(o);if(!u)throw new Error(`Protocol ${o} not found`);const c=await u.getPool(n.coinType);if(console.log("migrateBetweenBorrowPTB",{fromPoolLending:c}),c.borrowBalance===0)throw new Error("No borrow balance");if(t!=null&&t.amount&&t.amount>c.borrowBalance)throw new Error("Amount is more than borrow balance");const h=await s.getPriceFeeds(),g=await Promise.all([n,d]);await s.updateOraclePricesPTB(l,s.filterPriceFeeds(h,{lendingState:r,pools:g}));let f=(N=t==null?void 0:t.amount)!=null?N:Number(c.borrowBalance);if(Number(c.borrowBalance)===f){const J=c.borrowAPR/100;f=Math.ceil(new B(f).multipliedBy(J*(60*3)/(365*24*3600)).plus(new B(1).shiftedBy(-n.token.decimals)).plus(f).toNumber())}const y=await s.getFlashLoanAsset(n,{env:this.config.env});if(!y)throw new Error(`${n.token.symbol} pool not support flashloan`);if(!this.walletClient)throw new Error("Wallet client not found");const T=(L=t==null?void 0:t.slippage)!=null?L:.005,w=Math.ceil(f*(1+y.flashloanFee)),m=w,b=await this.walletClient.swap.getQuote(n.suiCoinType,d.suiCoinType,m);let p=1+T,E=Math.ceil(Number(b.amount_out)*p),S=await this.walletClient.swap.getQuote(d.suiCoinType,n.suiCoinType,E);for(;Number(S.amount_out)<m;)p=p*Math.max(m/Number(S.amount_out),1.001),E=Math.ceil(Number(b.amount_out)*p),S=await this.walletClient.swap.getQuote(d.suiCoinType,n.suiCoinType,E);const[_,j]=await s.flashloanPTB(l,n,f),[I]=l.moveCall({target:"0x2::coin::from_balance",arguments:[_],typeArguments:[n.suiCoinType]});await u.repayCoinPTB(l,n.suiCoinType,I,f);const U=await s.borrowCoinPTB(l,d,E),W=await O.buildSwapPTBFromQuote(i,l,w,U,S),M=l.moveCall({target:"0x2::coin::into_balance",arguments:[W],typeArguments:[n.suiCoinType]}),[k]=await s.repayFlashLoanPTB(l,n,j,M),[x]=l.moveCall({target:"0x2::coin::from_balance",arguments:[k],typeArguments:[n.suiCoinType]});return l.transferObjects([x],i),l}async function $(l,e,a,t){var h,g;if(!this.walletClient)throw new Error("Wallet client not found");const i=await s.getCoins(this.walletClient.address,{client:this.walletClient.client,coinType:e}),n=await this.getPool(a),r=new R(i).getBalance(e);if(r.amount.eq(0))throw new Error(`No balance of ${e}`);if(console.log("migrateBalanceToSupplyPTB",{balance:r.amount.toNumber()}),t!=null&&t.amount&&r.amount.lt(t.amount))throw new Error("Amount is greater than balance");const o=(h=t==null?void 0:t.amount)!=null?h:r.amount.toNumber(),u=(g=t==null?void 0:t.slippage)!=null?g:.005;let c=await s.mergeCoinsPTB(l,r.coins,{balance:o,useGasCoin:!0});if(P.normalizeStructTag(e)!==P.normalizeStructTag(n.suiCoinType)){const f=await this.walletClient.swap.getQuote(e,n.suiCoinType,o);c=await this.walletClient.swap.buildSwapPTBFromQuote(l,f,c,u)}return await s.depositCoinPTB(l,n,c),l}class te{constructor(e){this.name="navi",this.walletClient=e}async getPool(e){const a=await this.walletClient.lending.getPool(e),i=(await this.walletClient.lending.getLendingState()).find(r=>r.pool.suiCoinType===P.normalizeStructTag(e)),n=i?new B(i.supplyBalance).toNumber():0,d=i?new B(i.borrowBalance).toNumber():0;return{supplyBalance:n,borrowBalance:d,borrowAPR:parseFloat(a.borrowIncentiveApyInfo.apy)}}async depositCoinPTB(e,a,t,i){throw new Error("Not implemented")}async withdrawCoinPTB(e,a,t){return s.withdrawCoinPTB(e,a,t)}async borrowCoinPTB(e,a,t){throw new Error("Not implemented")}async repayCoinPTB(e,a,t,i){s.repayCoinPTB(e,a,t,{amount:i})}}class q{constructor(e,a,t){this.name="suilend",this.walletClient=e,this.obligationOwnerCap=a,this.suilendClient=t}static async create(e){const[a,t]=await Promise.all([v.SuilendClient.initialize(v.LENDING_MARKET_ID,v.LENDING_MARKET_TYPE,e.client),v.SuilendClient.getObligationOwnerCaps(e.address,[v.LENDING_MARKET_TYPE],e.client)]);if(t.length===0)throw new Error("No existing obligations found for wallet address: "+e.address);return new q(e,t[0],a)}async getPool(e){var y,T;const a=P.normalizeStructTag(e),t=this.suilendClient.lendingMarket.reserves,i=new Set;t.forEach(w=>{i.add(P.normalizeStructTag(w.coinType.name)),w.depositsPoolRewardManager.poolRewards.forEach(m=>{m&&i.add(P.normalizeStructTag(m.coinType.name))}),w.borrowsPoolRewardManager.poolRewards.forEach(m=>{m&&i.add(P.normalizeStructTag(m.coinType.name))})});const n=await z.getCoinMetadataMap(Array.from(i)),r=t.map(w=>v.parseReserve(w,n)).reduce((w,m)=>(w[m.coinType]=m,w),{}),o=await this.suilendClient.getObligation(this.obligationOwnerCap.obligationId),u=v.parseObligation(o,r),c=u.deposits.find(w=>w.coinType===a),h=u.borrows.find(w=>w.coinType===a),g=n[a].decimals;return{cTokenExchangeRate:r[a].cTokenExchangeRate.toNumber(),supplyBalance:(y=c==null?void 0:c.depositedAmount.shiftedBy(g).decimalPlaces(0).toNumber())!=null?y:0,borrowBalance:(T=h==null?void 0:h.borrowedAmount.shiftedBy(g).decimalPlaces(0).toNumber())!=null?T:0,borrowAPR:r[a].borrowAprPercent.toNumber()}}async depositCoinPTB(e,a,t,i){throw new Error("Not implemented")}async withdrawCoinPTB(e,a,t){const i=await this.getPool(a),n=t===i.supplyBalance;return await this.suilendClient.withdraw(this.obligationOwnerCap.id,this.obligationOwnerCap.obligationId,a,n?z.MAX_U64.toString():Math.ceil(t/i.cTokenExchangeRate).toString(),e)}async borrowCoinPTB(e,a,t){throw new Error("Not implemented")}async repayCoinPTB(e,a,t,i){this.suilendClient.repay(this.obligationOwnerCap.obligationId,a,t,e),e.transferObjects([t],e.pure.address(this.walletClient.address))}}class ae extends F{constructor(){super(),this.name="lending",this.defaultConfig={env:"prod",protocols:[]},this._protocols=[],this.migrateBetweenSupplyPTB=Q,this.migrateBetweenBorrowPTB=K,this.migrateBalanceToSupplyPTB=$,this.migrateBetweenSupplyPTB=Q.bind(this),this.migrateBetweenBorrowPTB=K.bind(this),this.migrateBalanceToSupplyPTB=$.bind(this)}get protocols(){return this._protocols.length>0?this._protocols:this.config.protocols}async getProtocol(e){return(!this.protocols||this.protocols.length===0)&&await this.initializeProtocols(),this.protocols.find(a=>a.name===e)}async getPools(e){return await s.getPools({env:this.config.env,...e})}async getPool(e,a){return await s.getPool(e,{env:this.config.env,...a})}async deposit(e,a,t){var u,c,h;if(!this.walletClient)throw new Error("Wallet client not found");const i=await s.getPool(e,{env:this.config.env});await this.walletClient.module("balance").waitForUpdate();const n=new C.Transaction,d=this.walletClient.module("balance").portfolio.getBalance(i.suiCoinType),r=s.mergeCoinsPTB(n,d.coins,{balance:a,useGasCoin:!0});await s.depositCoinPTB(n,i,r,{env:this.config.env,amount:a,accountCap:t==null?void 0:t.accountCap});const o=await this.walletClient.signExecuteTransaction({transaction:n,dryRun:(u=t==null?void 0:t.dryRun)!=null?u:!1});return!(t!=null&&t.dryRun)&&((h=(c=o.effects)==null?void 0:c.status)==null?void 0:h.status)==="success"&&(this.emit("lending:deposit-success",{identifier:e,amount:a}),this.walletClient.module("balance").updatePortfolio()),o}async withdraw(e,a,t){var o,u,c;if(!this.walletClient)throw new Error("Wallet client not found");const i=await s.getPool(e,{env:this.config.env}),n=new C.Transaction;t!=null&&t.disableUpdateOracle||await this.updateOraclePTB(n,[i]);const d=await s.withdrawCoinPTB(n,i,a,{env:this.config.env,accountCap:t==null?void 0:t.accountCap});n.transferObjects([d],this.walletClient.address);const r=await this.walletClient.signExecuteTransaction({transaction:n,dryRun:(o=t==null?void 0:t.dryRun)!=null?o:!1});return!(t!=null&&t.dryRun)&&((c=(u=r.effects)==null?void 0:u.status)==null?void 0:c.status)==="success"&&(this.emit("lending:withdraw-success",{identifier:e,amount:a}),this.walletClient.module("balance").updatePortfolio()),r}async borrow(e,a,t){var o,u,c;if(!this.walletClient)throw new Error("Wallet client not found");const i=await s.getPool(e,{env:this.config.env}),n=new C.Transaction;t!=null&&t.disableUpdateOracle||await this.updateOraclePTB(n,[i]);const d=await s.borrowCoinPTB(n,i,a,{env:this.config.env,accountCap:t==null?void 0:t.accountCap});n.transferObjects([d],this.walletClient.address);const r=await this.walletClient.signExecuteTransaction({transaction:n,dryRun:(o=t==null?void 0:t.dryRun)!=null?o:!1});return!(t!=null&&t.dryRun)&&((c=(u=r.effects)==null?void 0:u.status)==null?void 0:c.status)==="success"&&(this.emit("lending:borrow-success",{identifier:e,amount:a}),this.walletClient.module("balance").updatePortfolio()),r}async repay(e,a,t){var u,c,h;if(!this.walletClient)throw new Error("Wallet client not found");await this.walletClient.module("balance").waitForUpdate();const i=await s.getPool(e,{env:this.config.env}),n=new C.Transaction,d=this.walletClient.module("balance").portfolio.getBalance(i.suiCoinType),r=s.mergeCoinsPTB(n,d.coins,{balance:a,useGasCoin:!0});await s.repayCoinPTB(n,i,r,{env:this.config.env,amount:a,accountCap:t==null?void 0:t.accountCap});const o=await this.walletClient.signExecuteTransaction({transaction:n,dryRun:(u=t==null?void 0:t.dryRun)!=null?u:!1});return!(t!=null&&t.dryRun)&&((h=(c=o.effects)==null?void 0:c.status)==null?void 0:h.status)==="success"&&(this.emit("lending:repay-success",{identifier:e,amount:a}),this.walletClient.module("balance").updatePortfolio()),o}async getHealthFactor(){if(!this.walletClient)throw new Error("Wallet client not found");const e=this.walletClient.address;return await s.getHealthFactor(e,{env:this.config.env,client:this.walletClient.client})}async liquidate(e,a,t,i,n){var w,m,b;if(!this.walletClient)throw new Error("Wallet client not found");const d=await s.getPool(e,{env:this.config.env}),r=await s.getPool(t,{env:this.config.env}),o=new C.Transaction,u=this.walletClient.module("balance").portfolio.getBalance(d.suiCoinType),c=s.mergeCoinsPTB(o,u.coins,{balance:a,useGasCoin:!0}),[h,g]=await s.liquidatePTB(o,d,c,r,i,{env:this.config.env}),[f]=o.moveCall({target:"0x2::coin::from_balance",arguments:[h],typeArguments:[r.suiCoinType]}),[y]=o.moveCall({target:"0x2::coin::from_balance",arguments:[g],typeArguments:[d.suiCoinType]});o.transferObjects([f,y],this.walletClient.address);const T=await this.walletClient.signExecuteTransaction({transaction:o,dryRun:(w=n==null?void 0:n.dryRun)!=null?w:!1});return!(n!=null&&n.dryRun)&&((b=(m=T.effects)==null?void 0:m.status)==null?void 0:b.status)==="success"&&(this.emit("lending:liquidate-success",{payIdentifier:e,payAmount:a,collateralIdentifier:t,liquidationAddress:i}),this.walletClient.module("balance").updatePortfolio()),T}async getAvailableRewards(e){if(!this.walletClient)throw new Error("Wallet client not found");return s.getUserAvailableLendingRewards(this.walletClient.address,{...e,env:this.config.env})}async getClaimedRewardHistory(e){if(!this.walletClient)throw new Error("Wallet client not found");return s.getUserClaimedRewardHistory(this.walletClient.address,{...e})}async claimAllRewards(e){var n,d,r;if(!this.walletClient)throw new Error("Wallet client not found");const a=new C.Transaction,t=await s.getUserAvailableLendingRewards(this.walletClient.address,{env:this.config.env});await s.claimLendingRewardsPTB(a,t,{env:this.config.env,accountCap:e==null?void 0:e.accountCap});const i=await this.walletClient.signExecuteTransaction({transaction:a,dryRun:(n=e==null?void 0:e.dryRun)!=null?n:!1});return!(e!=null&&e.dryRun)&&((r=(d=i.effects)==null?void 0:d.status)==null?void 0:r.status)==="success"&&(this.emit("lending:claim-rewards-success",{rewards:t}),this.walletClient.module("balance").updatePortfolio()),i}async updateOraclePTB(e,a){const t=await s.getPriceFeeds({env:this.config.env}),i=await this.getLendingState({cacheTime:60*1e3}),n=s.filterPriceFeeds(t,{lendingState:i,pools:a});await s.updateOraclePricesPTB(e,n,{env:this.config.env,updatePythPriceFeeds:!0})}async updateOracle(e){var i;if(!this.walletClient)throw new Error("Wallet client not found");const a=new C.Transaction;return await this.updateOraclePTB(a,e==null?void 0:e.pools),await this.walletClient.signExecuteTransaction({transaction:a,dryRun:(i=e==null?void 0:e.dryRun)!=null?i:!1})}async getLendingState(e){if(!this.walletClient)throw new Error("Wallet client not found");return await s.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 C.Transaction,t=await s.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})}async initializeProtocols(){if(!this.walletClient){console.warn("Wallet client not available during protocol initialization");return}const e=[];e.push(new te(this.walletClient));try{e.push(await q.create(this.walletClient))}catch(a){console.warn("Failed to initialize SuilendProtocol:",a)}this._protocols=e}}class ne extends F{constructor(){super(...arguments),this.name="volo",this.defaultConfig={packageId:"0x68d22cf8bdbcd11ecba1e094922873e4080d4d11133e2443fddda0bfd11dae20",poolId:"0x2d914e23d82fedef1b5f56a32d5c64bdcc3087ccfea2b4d6ea51a71f587840e5",metadataId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",coinType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT"},this.getStats=s.withCache(s.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"),s.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"),s.parseTxValue(a,e.object)],typeArguments:[]});return t}async stake(e,a){var o,u,c;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 C.Transaction;await this.walletClient.module("balance").waitForUpdate();const i=this.walletClient.module("balance").portfolio.getBalance("0x2::sui::SUI"),n=s.mergeCoinsPTB(t,i.coins,{balance:e,useGasCoin:!0}),d=await this.stakePTB(t,n);t.transferObjects([d],this.walletClient.address);const r=await this.walletClient.signExecuteTransaction({transaction:t,dryRun:(o=a==null?void 0:a.dryRun)!=null?o:!1});return!(a!=null&&a.dryRun)&&((c=(u=r.effects)==null?void 0:u.status)==null?void 0:c.status)==="success"&&(this.emit("volo:stake-success",{suiAmount:e}),this.walletClient.module("balance").updatePortfolio()),r}async unstake(e,a){var o,u,c;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 C.Transaction,i=this.walletClient.module("balance").portfolio.getBalance(this.config.coinType),n=s.mergeCoinsPTB(t,i.coins,{balance:e}),d=await this.unstakePTB(t,n);t.transferObjects([d],this.walletClient.address);const r=await this.walletClient.signExecuteTransaction({transaction:t,dryRun:(o=a==null?void 0:a.dryRun)!=null?o:!1});return!(a!=null&&a.dryRun)&&((c=(u=r.effects)==null?void 0:u.status)==null?void 0:c.status)==="success"&&(this.emit("volo:unstake-success",{vSuiAmount:e}),this.walletClient.module("balance").updatePortfolio()),r}}class ie extends F{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?O.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 O.getQuote(e,a,t,this.config.apiKey,this.swapOptions)}async buildSwapPTBFromQuote(e,a,t,i){if(!this.walletClient)throw new Error("Wallet client not found");const n=new B(a.amount_out).multipliedBy(1-i).toFixed(0);return await O.buildSwapPTBFromQuote(this.walletClient.address,e,Number(n),t,a,this.referral,!1,this.config.apiKey,this.swapOptions)}async swap(e,a,t,i,n){var T,w,m;if(!this.walletClient)throw new Error("Wallet client not found");await this.walletClient.module("balance").waitForUpdate();const d=this.walletClient.module("balance").portfolio.getBalance(e),r=new C.Transaction,o=s.mergeCoinsPTB(r,d.coins,{balance:t,useGasCoin:!0}),u=await this.getQuote(e,a,t),c=await this.buildSwapPTBFromQuote(r,u,o,i);if(r.transferObjects([c],this.walletClient.address),r.setSender(this.walletClient.address),n!=null&&n.dryRun)return await this.walletClient.signExecuteTransaction({transaction:r,dryRun:!0});const h=await r.build({client:this.walletClient.client}),g=await this.walletClient.signer.signTransaction(h),f=[g.signature];try{await X.executeAuction(g.bytes,f)}catch(b){console.error(b)}const y=await this.walletClient.client.executeTransactionBlock({transactionBlock:g.bytes,signature:f,options:{showEffects:!0,showEvents:!0,showBalanceChanges:!0}});if(((w=(T=y.effects)==null?void 0:T.status)==null?void 0:w.status)==="success"){const b=(m=y.events)==null?void 0:m.find(p=>p.type.includes("::slippage::SwapEvent"));b&&this.emit("swap:swap-success",{fromCoinType:e,toCoinType:a,fromAmount:t,slippage:i,toAmount:Number(b.parsedJson.amount_out)}),this.walletClient.module("balance").updatePortfolio()}return y}}class se extends F{constructor(){super(...arguments),this.name="haedal",this.defaultConfig={packageId:"0x19e6ea7f5ced4f090e20da794cc80349a03e638940ddb95155a4e301f5f4967c",configId:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",coinType:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"},this.getApy=s.withCache(s.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),s.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),s.parseTxValue(a,e.object)],typeArguments:[]});return t}async stake(e,a){var o,u,c;if(!this.walletClient)throw new Error("Wallet client not found");const t=new C.Transaction;await this.walletClient.module("balance").waitForUpdate();const i=this.walletClient.module("balance").portfolio.getBalance("0x2::sui::SUI"),n=s.mergeCoinsPTB(t,i.coins,{balance:e,useGasCoin:!0}),d=await this.stakePTB(t,n);t.transferObjects([d],this.walletClient.address);const r=await this.walletClient.signExecuteTransaction({transaction:t,dryRun:(o=a==null?void 0:a.dryRun)!=null?o:!1});return!(a!=null&&a.dryRun)&&((c=(u=r.effects)==null?void 0:u.status)==null?void 0:c.status)==="success"&&(this.emit("haedal:stake-success",{suiAmount:e}),this.walletClient.module("balance").updatePortfolio()),r}async unstake(e,a){var o,u,c;if(!this.walletClient)throw new Error("Wallet client not found");await this.walletClient.module("balance").waitForUpdate();const t=new C.Transaction,i=this.walletClient.module("balance").portfolio.getBalance(this.config.coinType),n=s.mergeCoinsPTB(t,i.coins,{balance:e}),d=await this.unstakePTB(t,n);t.transferObjects([d],this.walletClient.address);const r=await this.walletClient.signExecuteTransaction({transaction:t,dryRun:(o=a==null?void 0:a.dryRun)!=null?o:!1});return!(a!=null&&a.dryRun)&&((c=(u=r.effects)==null?void 0:u.status)==null?void 0:c.status)==="success"&&(this.emit("haedal:unstake-success",{haSUIAmount:e}),this.walletClient.module("balance").updatePortfolio()),r}}const re={balance:new ee,lending:new ae,volo:new ne,swap:new ie,haedal:new se},le={url:G.getFullnodeUrl("mainnet")};class oe{constructor(e){this.modules=re,this.userConfigs={},this.events=V();const a={...le,...e.client};a.transport=a.transport||new Z(a.url),this.client=new G.SuiClient(a),this.signer=e.signer,this.userConfigs=e.configs||{},Object.entries(this.modules).forEach(([t,i])=>{if(t!==i.name)throw new Error(`Module name ${t} does not match module name ${i.name}`);i.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 i;return e.transaction instanceof C.Transaction?(e.transaction.setSenderIfNotSet(this.address),i=await e.transaction.build({client:this.client})):i=e.transaction,this.client.dryRunTransactionBlock({transactionBlock:i})}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 ce extends D.Signer{constructor(e){super(),this.address=e}async sign(e){return Promise.resolve(new Uint8Array(0))}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 ue extends D.Signer{constructor(e){super(),this.address=e}async sign(e){return Promise.resolve(new Uint8Array(0))}getPublicKey(){return{toSuiAddress:()=>this.address,toBytes:()=>new Uint8Array(32),toRawBytes:()=>new Uint8Array(32),flag:0,verify:async()=>!1}}getKeyScheme(){return"ed25519"}}exports.WalletClient=oe;exports.WatchSigner=ce;exports.WebSigner=ue;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const z=require("@mysten/sui/client"),D=require("mitt"),H=require("axios"),s=require("@naviprotocol/lending"),b=require("bignumber.js"),C=require("@mysten/sui/utils"),f=require("@mysten/sui/transactions"),A=require("@naviprotocol/astros-aggregator-sdk"),P=require("@suilend/sdk"),W=require("@suilend/sui-fe"),J=require("shio-sdk"),Q=require("@mysten/sui/cryptography"),K=H.create({timeout:2e4});K.interceptors.response.use(function(r){if(r.data.err)throw new Error(r.data.err);if(r.data.error)throw new Error(r.data.error.message);return r},function(r){return Promise.reject(r)});class V{constructor(t){this.requestId=0,this.rpcUrl=t}async request(t){return this.requestId+=1,(await K.post(this.rpcUrl,{jsonrpc:"2.0",id:this.requestId,method:t.method,params:t.params})).data.result}async subscribe(){throw new Error("subscribe not implemented.")}}class O{get config(){return this.walletClient?this.walletClient.config(this.name):this.defaultConfig}emit(t,e){this.walletClient?.events.emit(t,e)}install(t){this.walletClient=t}uninstall(){this.walletClient=void 0}}class S{constructor(t){if(t instanceof S)this.balances=JSON.parse(JSON.stringify(t.balances));else{const e={};t?.forEach(n=>{const i=C.normalizeStructTag(n.coinType);let a=e[i];a||(a={coinType:i,amount:b.BigNumber(0),coins:[]},e[i]=a),a.coins.push(n),a.amount=a.amount.plus(n.balance)}),this.balances=e}}getBalance(t){return t=C.normalizeStructTag(t),this.balances[t]||{coinType:t,amount:b.BigNumber(0),coins:[]}}getCoinTypes(){return Object.values(this.balances).map(t=>t.coinType)}balanceOf(t){return t=C.normalizeStructTag(t),this.getBalance(t)?.amount||b.BigNumber(0)}clone(){const t=JSON.parse(JSON.stringify(this.balances)),e=new S;return e.balances=t,e}}class Y extends O{constructor(){super(...arguments),this.name="balance",this.defaultConfig={coinPollingInterval:6e3,disableCoinPolling:!1},this.updatePortfolio=s.withSingleton(async()=>{if(!this.walletClient)throw new Error("Wallet client not found");this._coins=await s.getCoins(this.walletClient.address,{client:this.walletClient.client}),this._portfolio=new S(this._coins),this.emit("balance:portfolio-updated",{})}),this._coins=[],this._portfolio=new S,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(t,e,n,i){return this.sendCoinBatch(t,[e],[n],i)}async sendCoinBatch(t,e,n,i){if(!this.walletClient)throw new Error("Wallet client not found");if(e.length!==n.length)throw new Error("Recipients and amounts must have the same length");await this.waitForUpdate();const a=this.portfolio.getBalance(t),l=n.reduce((p,g)=>p.plus(g),b(0));if(a.amount.lt(l))throw new Error("Insufficient balance");const o=new f.Transaction;let c=o.gas;C.normalizeStructTag(t)!==C.normalizeStructTag("0x2::sui::SUI")&&(c=s.mergeCoinsPTB(o,a.coins,{balance:l.toNumber()}));const h=o.splitCoins(c,n);return e.forEach((p,g)=>{o.transferObjects([h[g]],p)}),await this.walletClient.signExecuteTransaction({transaction:o,dryRun:i?.dryRun??!1})}async transferObject(t,e,n){return this.transferObjectBatch([t],[e],n)}async transferObjectBatch(t,e,n){if(!this.walletClient)throw new Error("Wallet client not found");if(t.length!==e.length)throw new Error("Objects and recipients must have the same length");await this.waitForUpdate();const i=new f.Transaction;return t.forEach((l,o)=>{i.transferObjects([i.object(l)],e[o])}),await this.walletClient.signExecuteTransaction({transaction:i,dryRun:n?.dryRun??!1})}async startPolling(){try{if(this.config.disableCoinPolling)return;await this.updatePortfolio()}catch(t){console.error(t)}finally{this.pollingTimer=setTimeout(this.startPolling,this.config.coinPollingInterval)}}install(t){super.install(t),this.startPolling=this.startPolling.bind(this),this.startPolling(),this._updatePromise=new Promise(e=>{t.events.on("balance:portfolio-updated",()=>{e()})})}uninstall(){super.uninstall(),this.pollingTimer&&(clearTimeout(this.pollingTimer),this.pollingTimer=null)}}async function M(r,t,e,n){if(!this.walletClient)throw new Error("Wallet client not found");const i=await this.getPool(t),a=await this.getPool(e),l=await this.getLendingState(),o=this.walletClient.address,c=n?.protocol??"navi",h=await this.getProtocol(c);if(!h)throw new Error(`Protocol ${c} not found`);const d=await h.getPool(i.coinType);if(console.log("migrateBetweenSupplyPTB",{fromPoolLending:d}),c==="navi"&&d.supplyBalance===0)throw new Error("No supply balance");if(n?.amount&&n.amount>d.supplyBalance)throw new Error("Amount is less than supply balance");const p=n?.slippage??.005,g=n?.amount??Number(d.supplyBalance),m=await s.getPriceFeeds(),u=await Promise.all([i,a]);if(await s.updateOraclePricesPTB(r,s.filterPriceFeeds(m,{lendingState:l,pools:u})),c!=="navi"&&i.id===a.id){const I=await h.withdrawCoinPTB(r,i.suiCoinType,g);return await s.depositCoinPTB(r,a,I,{amount:g}),r}const w=await s.getFlashLoanAsset(a,{env:this.config.env});if(!w)throw new Error(`${a.token.symbol} pool not support flashloan`);const T=await this.walletClient.swap.getQuote(i.suiCoinType,a.suiCoinType,g),B=Number(T.amount_out);if(B<=0)throw new Error("The amount of swapAmountOut must be greater than 0.");const R=Math.floor(B*(1-p)),y=Math.floor(R/(1+w.flashloanFee));if(y<=0)throw new Error("The calculated borrow amount must be positive.");const[v,E]=await s.flashloanPTB(r,a,y),[F]=r.moveCall({target:"0x2::coin::from_balance",arguments:[v],typeArguments:[a.suiCoinType]});await s.depositCoinPTB(r,a,F,{amount:y});const k=await h.withdrawCoinPTB(r,i.suiCoinType,g),x=await A.buildSwapPTBFromQuote(o,r,R,k,T),N=r.moveCall({target:"0x2::coin::into_balance",arguments:[x],typeArguments:[a.suiCoinType]}),[_]=await s.repayFlashLoanPTB(r,a,E,N),[j]=r.moveCall({target:"0x2::coin::from_balance",arguments:[_],typeArguments:[a.suiCoinType]});return await s.depositCoinPTB(r,a,j),r}async function q(r,t,e,n){if(!this.walletClient)throw new Error("Wallet client not found");const i=this.walletClient.address,a=await this.getPool(t),l=await this.getPool(e),o=await this.getLendingState(),c=n?.protocol??"navi",h=await this.getProtocol(c);if(!h)throw new Error(`Protocol ${c} not found`);const d=await h.getPool(a.coinType);if(console.log("migrateBetweenBorrowPTB",{fromPoolLending:d}),d.borrowBalance===0)throw new Error("No borrow balance");if(n?.amount&&n.amount>d.borrowBalance)throw new Error("Amount is more than borrow balance");const p=await s.getPriceFeeds(),g=await Promise.all([a,l]);await s.updateOraclePricesPTB(r,s.filterPriceFeeds(p,{lendingState:o,pools:g}));let m=n?.amount??Number(d.borrowBalance);if(Number(d.borrowBalance)===m){const G=d.borrowAPR/100;m=Math.ceil(new b(m).multipliedBy(G*(60*3)/(365*24*3600)).plus(new b(1).shiftedBy(-a.token.decimals)).plus(m).toNumber())}const u=await s.getFlashLoanAsset(a,{env:this.config.env});if(!u)throw new Error(`${a.token.symbol} pool not support flashloan`);if(!this.walletClient)throw new Error("Wallet client not found");const w=n?.slippage??.005,T=Math.ceil(m*(1+u.flashloanFee)),B=T,R=await this.walletClient.swap.getQuote(a.suiCoinType,l.suiCoinType,B);let y=1+w,v=Math.ceil(Number(R.amount_out)*y),E=await this.walletClient.swap.getQuote(l.suiCoinType,a.suiCoinType,v);for(;Number(E.amount_out)<B;)y=y*Math.max(B/Number(E.amount_out),1.001),v=Math.ceil(Number(R.amount_out)*y),E=await this.walletClient.swap.getQuote(l.suiCoinType,a.suiCoinType,v);const[F,k]=await s.flashloanPTB(r,a,m),[x]=r.moveCall({target:"0x2::coin::from_balance",arguments:[F],typeArguments:[a.suiCoinType]});await h.repayCoinPTB(r,a.suiCoinType,x,m);const N=await s.borrowCoinPTB(r,l,v),_=await A.buildSwapPTBFromQuote(i,r,T,N,E),j=r.moveCall({target:"0x2::coin::into_balance",arguments:[_],typeArguments:[a.suiCoinType]}),[I]=await s.repayFlashLoanPTB(r,a,k,j),[$]=r.moveCall({target:"0x2::coin::from_balance",arguments:[I],typeArguments:[a.suiCoinType]});return r.transferObjects([$],i),r}async function L(r,t,e,n){if(!this.walletClient)throw new Error("Wallet client not found");const i=await s.getCoins(this.walletClient.address,{client:this.walletClient.client,coinType:t}),a=await this.getPool(e),o=new S(i).getBalance(t);if(o.amount.eq(0))throw new Error(`No balance of ${t}`);if(console.log("migrateBalanceToSupplyPTB",{balance:o.amount.toNumber()}),n?.amount&&o.amount.lt(n.amount))throw new Error("Amount is greater than balance");const c=n?.amount??o.amount.toNumber(),h=n?.slippage??.005;let d=await s.mergeCoinsPTB(r,o.coins,{balance:c,useGasCoin:!0});if(C.normalizeStructTag(t)!==C.normalizeStructTag(a.suiCoinType)){const p=await this.walletClient.swap.getQuote(t,a.suiCoinType,c);d=await this.walletClient.swap.buildSwapPTBFromQuote(r,p,d,h)}return await s.depositCoinPTB(r,a,d),r}class X{constructor(t){this.name="navi",this.walletClient=t}async getPool(t){const e=await this.walletClient.lending.getPool(t),i=(await this.walletClient.lending.getLendingState()).find(o=>o.pool.suiCoinType===C.normalizeStructTag(t)),a=i?new b(i.supplyBalance).toNumber():0,l=i?new b(i.borrowBalance).toNumber():0;return{supplyBalance:a,borrowBalance:l,borrowAPR:parseFloat(e.borrowIncentiveApyInfo.apy)}}async depositCoinPTB(t,e,n,i){throw new Error("Not implemented")}async withdrawCoinPTB(t,e,n){return s.withdrawCoinPTB(t,e,n)}async borrowCoinPTB(t,e,n){throw new Error("Not implemented")}async repayCoinPTB(t,e,n,i){s.repayCoinPTB(t,e,n,{amount:i})}}class U{constructor(t,e,n){this.name="suilend",this.walletClient=t,this.obligationOwnerCap=e,this.suilendClient=n}static async create(t){const[e,n]=await Promise.all([P.SuilendClient.initialize(P.LENDING_MARKET_ID,P.LENDING_MARKET_TYPE,t.client),P.SuilendClient.getObligationOwnerCaps(t.address,[P.LENDING_MARKET_TYPE],t.client)]);if(n.length===0)throw new Error("No existing obligations found for wallet address: "+t.address);return new U(t,n[0],e)}async getPool(t){const e=C.normalizeStructTag(t),n=this.suilendClient.lendingMarket.reserves,i=new Set;n.forEach(u=>{i.add(C.normalizeStructTag(u.coinType.name)),u.depositsPoolRewardManager.poolRewards.forEach(w=>{w&&i.add(C.normalizeStructTag(w.coinType.name))}),u.borrowsPoolRewardManager.poolRewards.forEach(w=>{w&&i.add(C.normalizeStructTag(w.coinType.name))})});const a=await W.getCoinMetadataMap(Array.from(i)),o=n.map(u=>P.parseReserve(u,a)).reduce((u,w)=>(u[w.coinType]=w,u),{}),c=await this.suilendClient.getObligation(this.obligationOwnerCap.obligationId),h=P.parseObligation(c,o),d=h.deposits.find(u=>u.coinType===e),p=h.borrows.find(u=>u.coinType===e),g=a[e].decimals;return{cTokenExchangeRate:o[e].cTokenExchangeRate.toNumber(),supplyBalance:d?.depositedAmount.shiftedBy(g).decimalPlaces(0).toNumber()??0,borrowBalance:p?.borrowedAmount.shiftedBy(g).decimalPlaces(0).toNumber()??0,borrowAPR:o[e].borrowAprPercent.toNumber()}}async depositCoinPTB(t,e,n,i){throw new Error("Not implemented")}async withdrawCoinPTB(t,e,n){const i=await this.getPool(e),a=n===i.supplyBalance;return await this.suilendClient.withdraw(this.obligationOwnerCap.id,this.obligationOwnerCap.obligationId,e,a?W.MAX_U64.toString():Math.ceil(n/i.cTokenExchangeRate).toString(),t)}async borrowCoinPTB(t,e,n){throw new Error("Not implemented")}async repayCoinPTB(t,e,n,i){this.suilendClient.repay(this.obligationOwnerCap.obligationId,e,n,t),t.transferObjects([n],t.pure.address(this.walletClient.address))}}class Z extends O{constructor(){super(),this.name="lending",this.defaultConfig={env:"prod",protocols:[]},this._protocols=[],this.migrateBetweenSupplyPTB=M,this.migrateBetweenBorrowPTB=q,this.migrateBalanceToSupplyPTB=L,this.migrateBetweenSupplyPTB=M.bind(this),this.migrateBetweenBorrowPTB=q.bind(this),this.migrateBalanceToSupplyPTB=L.bind(this)}get protocols(){return this._protocols.length>0?this._protocols:this.config.protocols}async getProtocol(t){return(!this.protocols||this.protocols.length===0)&&await this.initializeProtocols(),this.protocols.find(e=>e.name===t)}async getPools(t){return await s.getPools({env:this.config.env,...t})}async getPool(t,e){return await s.getPool(t,{env:this.config.env,...e})}async deposit(t,e,n){if(!this.walletClient)throw new Error("Wallet client not found");const i=await s.getPool(t,{env:this.config.env});await this.walletClient.module("balance").waitForUpdate();const a=new f.Transaction,l=this.walletClient.module("balance").portfolio.getBalance(i.suiCoinType),o=s.mergeCoinsPTB(a,l.coins,{balance:e,useGasCoin:!0});await s.depositCoinPTB(a,i,o,{env:this.config.env,amount:e,accountCap:n?.accountCap});const c=await this.walletClient.signExecuteTransaction({transaction:a,dryRun:n?.dryRun??!1});return!n?.dryRun&&c.effects?.status?.status==="success"&&(this.emit("lending:deposit-success",{identifier:t,amount:e}),this.walletClient.module("balance").updatePortfolio()),c}async withdraw(t,e,n){if(!this.walletClient)throw new Error("Wallet client not found");const i=await s.getPool(t,{env:this.config.env}),a=new f.Transaction;n?.disableUpdateOracle||await this.updateOraclePTB(a,[i]);const l=await s.withdrawCoinPTB(a,i,e,{env:this.config.env,accountCap:n?.accountCap});a.transferObjects([l],this.walletClient.address);const o=await this.walletClient.signExecuteTransaction({transaction:a,dryRun:n?.dryRun??!1});return!n?.dryRun&&o.effects?.status?.status==="success"&&(this.emit("lending:withdraw-success",{identifier:t,amount:e}),this.walletClient.module("balance").updatePortfolio()),o}async borrow(t,e,n){if(!this.walletClient)throw new Error("Wallet client not found");const i=await s.getPool(t,{env:this.config.env}),a=new f.Transaction;n?.disableUpdateOracle||await this.updateOraclePTB(a,[i]);const l=await s.borrowCoinPTB(a,i,e,{env:this.config.env,accountCap:n?.accountCap});a.transferObjects([l],this.walletClient.address);const o=await this.walletClient.signExecuteTransaction({transaction:a,dryRun:n?.dryRun??!1});return!n?.dryRun&&o.effects?.status?.status==="success"&&(this.emit("lending:borrow-success",{identifier:t,amount:e}),this.walletClient.module("balance").updatePortfolio()),o}async repay(t,e,n){if(!this.walletClient)throw new Error("Wallet client not found");await this.walletClient.module("balance").waitForUpdate();const i=await s.getPool(t,{env:this.config.env}),a=new f.Transaction,l=this.walletClient.module("balance").portfolio.getBalance(i.suiCoinType),o=s.mergeCoinsPTB(a,l.coins,{balance:e,useGasCoin:!0});await s.repayCoinPTB(a,i,o,{env:this.config.env,amount:e,accountCap:n?.accountCap});const c=await this.walletClient.signExecuteTransaction({transaction:a,dryRun:n?.dryRun??!1});return!n?.dryRun&&c.effects?.status?.status==="success"&&(this.emit("lending:repay-success",{identifier:t,amount:e}),this.walletClient.module("balance").updatePortfolio()),c}async getHealthFactor(){if(!this.walletClient)throw new Error("Wallet client not found");const t=this.walletClient.address;return await s.getHealthFactor(t,{env:this.config.env,client:this.walletClient.client})}async liquidate(t,e,n,i,a){if(!this.walletClient)throw new Error("Wallet client not found");const l=await s.getPool(t,{env:this.config.env}),o=await s.getPool(n,{env:this.config.env}),c=new f.Transaction,h=this.walletClient.module("balance").portfolio.getBalance(l.suiCoinType),d=s.mergeCoinsPTB(c,h.coins,{balance:e,useGasCoin:!0}),[p,g]=await s.liquidatePTB(c,l,d,o,i,{env:this.config.env}),[m]=c.moveCall({target:"0x2::coin::from_balance",arguments:[p],typeArguments:[o.suiCoinType]}),[u]=c.moveCall({target:"0x2::coin::from_balance",arguments:[g],typeArguments:[l.suiCoinType]});c.transferObjects([m,u],this.walletClient.address);const w=await this.walletClient.signExecuteTransaction({transaction:c,dryRun:a?.dryRun??!1});return!a?.dryRun&&w.effects?.status?.status==="success"&&(this.emit("lending:liquidate-success",{payIdentifier:t,payAmount:e,collateralIdentifier:n,liquidationAddress:i}),this.walletClient.module("balance").updatePortfolio()),w}async getAvailableRewards(t){if(!this.walletClient)throw new Error("Wallet client not found");return s.getUserAvailableLendingRewards(this.walletClient.address,{...t,env:this.config.env})}async getClaimedRewardHistory(t){if(!this.walletClient)throw new Error("Wallet client not found");return s.getUserClaimedRewardHistory(this.walletClient.address,{...t})}async claimAllRewards(t){if(!this.walletClient)throw new Error("Wallet client not found");const e=new f.Transaction,n=await s.getUserAvailableLendingRewards(this.walletClient.address,{env:this.config.env});await s.claimLendingRewardsPTB(e,n,{env:this.config.env,accountCap:t?.accountCap});const i=await this.walletClient.signExecuteTransaction({transaction:e,dryRun:t?.dryRun??!1});return!t?.dryRun&&i.effects?.status?.status==="success"&&(this.emit("lending:claim-rewards-success",{rewards:n}),this.walletClient.module("balance").updatePortfolio()),i}async updateOraclePTB(t,e){const n=await s.getPriceFeeds({env:this.config.env}),i=await this.getLendingState({cacheTime:60*1e3}),a=s.filterPriceFeeds(n,{lendingState:i,pools:e});await s.updateOraclePricesPTB(t,a,{env:this.config.env,updatePythPriceFeeds:!0})}async updateOracle(t){if(!this.walletClient)throw new Error("Wallet client not found");const e=new f.Transaction;return await this.updateOraclePTB(e,t?.pools),await this.walletClient.signExecuteTransaction({transaction:e,dryRun:t?.dryRun??!1})}async getLendingState(t){if(!this.walletClient)throw new Error("Wallet client not found");return await s.getLendingState(this.walletClient.address,{env:this.config.env,...t,client:this.walletClient.client})}async createAccountCap(t){if(!this.walletClient)throw new Error("Wallet client not found");const e=new f.Transaction,n=await s.createAccountCapPTB(e);return e.transferObjects([n],this.walletClient.address),await this.walletClient.signExecuteTransaction({transaction:e,dryRun:t?.dryRun??!1})}async initializeProtocols(){if(!this.walletClient){console.warn("Wallet client not available during protocol initialization");return}const t=[];t.push(new X(this.walletClient));try{t.push(await U.create(this.walletClient))}catch(e){console.warn("Failed to initialize SuilendProtocol:",e)}this._protocols=t}}class tt extends O{constructor(){super(...arguments),this.name="volo",this.defaultConfig={packageId:"0x68d22cf8bdbcd11ecba1e094922873e4080d4d11133e2443fddda0bfd11dae20",poolId:"0x2d914e23d82fedef1b5f56a32d5c64bdcc3087ccfea2b4d6ea51a71f587840e5",metadataId:"0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60",coinType:"0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT"},this.getStats=s.withCache(s.withSingleton(async()=>(await fetch("https://open-api.naviprotocol.io/api/volo/stats").then(e=>e.json())).data))}async stakePTB(t,e){const[n]=t.moveCall({target:`${this.config.packageId}::stake_pool::stake`,arguments:[t.object(this.config.poolId),t.object(this.config.metadataId),t.object("0x05"),s.parseTxValue(e,t.object)],typeArguments:[]});return n}async unstakePTB(t,e){const[n]=t.moveCall({target:`${this.config.packageId}::stake_pool::unstake`,arguments:[t.object(this.config.poolId),t.object(this.config.metadataId),t.object("0x05"),s.parseTxValue(e,t.object)],typeArguments:[]});return n}async stake(t,e){if(!this.walletClient)throw new Error("Wallet client not found");if(t<1e9)throw new Error("Stake amount should be greater than 1Sui");const n=new f.Transaction;await this.walletClient.module("balance").waitForUpdate();const i=this.walletClient.module("balance").portfolio.getBalance("0x2::sui::SUI"),a=s.mergeCoinsPTB(n,i.coins,{balance:t,useGasCoin:!0}),l=await this.stakePTB(n,a);n.transferObjects([l],this.walletClient.address);const o=await this.walletClient.signExecuteTransaction({transaction:n,dryRun:e?.dryRun??!1});return!e?.dryRun&&o.effects?.status?.status==="success"&&(this.emit("volo:stake-success",{suiAmount:t}),this.walletClient.module("balance").updatePortfolio()),o}async unstake(t,e){if(!this.walletClient)throw new Error("Wallet client not found");if(t<1e9)throw new Error("Unstake amount should >= 1vSui");await this.walletClient.module("balance").waitForUpdate();const n=new f.Transaction,i=this.walletClient.module("balance").portfolio.getBalance(this.config.coinType),a=s.mergeCoinsPTB(n,i.coins,{balance:t}),l=await this.unstakePTB(n,a);n.transferObjects([l],this.walletClient.address);const o=await this.walletClient.signExecuteTransaction({transaction:n,dryRun:e?.dryRun??!1});return!e?.dryRun&&o.effects?.status?.status==="success"&&(this.emit("volo:unstake-success",{vSuiAmount:t}),this.walletClient.module("balance").updatePortfolio()),o}}class et extends O{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?A.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(t,e,n){return A.getQuote(t,e,n,this.config.apiKey,this.swapOptions)}async buildSwapPTBFromQuote(t,e,n,i){if(!this.walletClient)throw new Error("Wallet client not found");const a=new b(e.amount_out).multipliedBy(1-i).toFixed(0);return await A.buildSwapPTBFromQuote(this.walletClient.address,t,Number(a),n,e,this.referral,!1,this.config.apiKey,this.swapOptions)}async swap(t,e,n,i,a){if(!this.walletClient)throw new Error("Wallet client not found");await this.walletClient.module("balance").waitForUpdate();const l=this.walletClient.module("balance").portfolio.getBalance(t),o=new f.Transaction,c=s.mergeCoinsPTB(o,l.coins,{balance:n,useGasCoin:!0}),h=await this.getQuote(t,e,n),d=await this.buildSwapPTBFromQuote(o,h,c,i);if(o.transferObjects([d],this.walletClient.address),o.setSender(this.walletClient.address),a?.dryRun)return await this.walletClient.signExecuteTransaction({transaction:o,dryRun:!0});const p=await o.build({client:this.walletClient.client}),g=await this.walletClient.signer.signTransaction(p),m=[g.signature];try{await J.executeAuction(g.bytes,m)}catch(w){console.error(w)}const u=await this.walletClient.client.executeTransactionBlock({transactionBlock:g.bytes,signature:m,options:{showEffects:!0,showEvents:!0,showBalanceChanges:!0}});if(u.effects?.status?.status==="success"){const w=u.events?.find(T=>T.type.includes("::slippage::SwapEvent"));w&&this.emit("swap:swap-success",{fromCoinType:t,toCoinType:e,fromAmount:n,slippage:i,toAmount:Number(w.parsedJson.amount_out)}),this.walletClient.module("balance").updatePortfolio()}return u}}class nt extends O{constructor(){super(...arguments),this.name="haedal",this.defaultConfig={packageId:"0x19e6ea7f5ced4f090e20da794cc80349a03e638940ddb95155a4e301f5f4967c",configId:"0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca",coinType:"0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI"},this.getApy=s.withCache(s.withSingleton(async()=>(await fetch("https://open-api.naviprotocol.io/api/haedal/stats").then(e=>e.json())).data.apy))}async stakePTB(t,e){const[n]=t.moveCall({target:`${this.config.packageId}::staking::request_stake_coin`,arguments:[t.object("0x05"),t.object(this.config.configId),s.parseTxValue(e,t.object),t.pure.address("0x0000000000000000000000000000000000000000000000000000000000000000")],typeArguments:[]});return n}async unstakePTB(t,e){const[n]=t.moveCall({target:`${this.config.packageId}::staking::request_unstake_instant_coin`,arguments:[t.object("0x05"),t.object(this.config.configId),s.parseTxValue(e,t.object)],typeArguments:[]});return n}async stake(t,e){if(!this.walletClient)throw new Error("Wallet client not found");const n=new f.Transaction;await this.walletClient.module("balance").waitForUpdate();const i=this.walletClient.module("balance").portfolio.getBalance("0x2::sui::SUI"),a=s.mergeCoinsPTB(n,i.coins,{balance:t,useGasCoin:!0}),l=await this.stakePTB(n,a);n.transferObjects([l],this.walletClient.address);const o=await this.walletClient.signExecuteTransaction({transaction:n,dryRun:e?.dryRun??!1});return!e?.dryRun&&o.effects?.status?.status==="success"&&(this.emit("haedal:stake-success",{suiAmount:t}),this.walletClient.module("balance").updatePortfolio()),o}async unstake(t,e){if(!this.walletClient)throw new Error("Wallet client not found");await this.walletClient.module("balance").waitForUpdate();const n=new f.Transaction,i=this.walletClient.module("balance").portfolio.getBalance(this.config.coinType),a=s.mergeCoinsPTB(n,i.coins,{balance:t}),l=await this.unstakePTB(n,a);n.transferObjects([l],this.walletClient.address);const o=await this.walletClient.signExecuteTransaction({transaction:n,dryRun:e?.dryRun??!1});return!e?.dryRun&&o.effects?.status?.status==="success"&&(this.emit("haedal:unstake-success",{haSUIAmount:t}),this.walletClient.module("balance").updatePortfolio()),o}}const at={balance:new Y,lending:new Z,volo:new tt,swap:new et,haedal:new nt},it={url:z.getFullnodeUrl("mainnet")};class st{constructor(t){this.modules=at,this.userConfigs={},this.events=D();const e={...it,...t.client};e.transport=e.transport||new V(e.url),this.client=new z.SuiClient(e),this.signer=t.signer,this.userConfigs=t.configs||{},Object.entries(this.modules).forEach(([n,i])=>{if(n!==i.name)throw new Error(`Module name ${n} does not match module name ${i.name}`);i.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(t){const{dryRun:e=!1,...n}=t;if(e){let i;return t.transaction instanceof f.Transaction?(t.transaction.setSenderIfNotSet(this.address),i=await t.transaction.build({client:this.client})):i=t.transaction,this.client.dryRunTransactionBlock({transactionBlock:i})}return this.client.signAndExecuteTransaction({...n,signer:this.signer})}get address(){return this.signer.getPublicKey().toSuiAddress()}module(t){return this.modules[t]}config(t){return{...this.modules[t].defaultConfig,...this.userConfigs[t]}}hasModule(t){return t in this.modules}}class ot extends Q.Signer{constructor(t){super(),this.address=t}async sign(t){return Promise.resolve(new Uint8Array(0))}getPublicKey(){return{toSuiAddress:()=>this.address,toBytes:()=>new Uint8Array(32),toRawBytes:()=>new Uint8Array(32),flag:0,verify:async()=>!1}}getKeyScheme(){return"ed25519"}async signAndExecuteTransaction({transaction:t,client:e}){return{}}}class rt extends Q.Signer{constructor(t){super(),this.address=t}async sign(t){return Promise.resolve(new Uint8Array(0))}getPublicKey(){return{toSuiAddress:()=>this.address,toBytes:()=>new Uint8Array(32),toRawBytes:()=>new Uint8Array(32),flag:0,verify:async()=>!1}}getKeyScheme(){return"ed25519"}}exports.WalletClient=st;exports.WatchSigner=ot;exports.WebSigner=rt;
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|