@scallop-io/scallop-deepbook-kit 1.0.0 → 1.0.1
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 +2 -2
- package/dist/index.js +2 -2
- package/package.json +1 -1
- package/src/toolkit/DeepBookMarginPool.ts +8 -6
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var grpc=require('@mysten/sui/grpc'),ed25519=require('@mysten/sui/keypairs/ed25519'),transactions=require('@mysten/sui/transactions'),deepbookV3=require('@mysten/deepbook-v3'),cryptography=require('@mysten/sui/cryptography'),bcs$1=require('@mysten/bcs'),bcs=require('@mysten/sui/bcs'),bignumber_js=require('bignumber.js');var U=a=>/^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(a),O=a=>/^[a-zA-Z0-9+/]+={0,2}$/g.test(a),R=a=>{if(U(a))return bcs$1.fromHex(a);if(O(a))return bcs$1.fromBase64(a);throw new Error("The string is not a valid hex or base64 string.")},w=a=>{if(a.length===cryptography.LEGACY_PRIVATE_KEY_SIZE)return a.slice(0,cryptography.PRIVATE_KEY_SIZE);if(a.length===cryptography.PRIVATE_KEY_SIZE+1&&a[0]===0)return a.slice(1);if(a.length===cryptography.PRIVATE_KEY_SIZE)return a;throw new Error("invalid secret key")};function h(a){switch(a){case "mainnet":return "https://fullnode.mainnet.sui.io:443";case "testnet":return "https://fullnode.testnet.sui.io:443";default:throw new Error(`Unknown network: ${a}`)}}var b=class{suiClient;keypair;address;marginPoolContract;supplierCapId;dbConfig;supplierCapPackageId;constructor({network:t,fullnodeUrl:
|
|
2
|
-
exports.DeepBookMarginPool=
|
|
1
|
+
'use strict';var grpc=require('@mysten/sui/grpc'),ed25519=require('@mysten/sui/keypairs/ed25519'),transactions=require('@mysten/sui/transactions'),deepbookV3=require('@mysten/deepbook-v3'),cryptography=require('@mysten/sui/cryptography'),bcs$1=require('@mysten/bcs'),bcs=require('@mysten/sui/bcs'),bignumber_js=require('bignumber.js');var U=a=>/^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(a),O=a=>/^[a-zA-Z0-9+/]+={0,2}$/g.test(a),R=a=>{if(U(a))return bcs$1.fromHex(a);if(O(a))return bcs$1.fromBase64(a);throw new Error("The string is not a valid hex or base64 string.")},w=a=>{if(a.length===cryptography.LEGACY_PRIVATE_KEY_SIZE)return a.slice(0,cryptography.PRIVATE_KEY_SIZE);if(a.length===cryptography.PRIVATE_KEY_SIZE+1&&a[0]===0)return a.slice(1);if(a.length===cryptography.PRIVATE_KEY_SIZE)return a;throw new Error("invalid secret key")};function h(a){switch(a){case "mainnet":return "https://fullnode.mainnet.sui.io:443";case "testnet":return "https://fullnode.testnet.sui.io:443";default:throw new Error(`Unknown network: ${a}`)}}var b=class{suiClient;keypair;address;marginPoolContract;supplierCapId;dbConfig;supplierCapPackageId;constructor({network:t,fullnodeUrl:e,supplierCapId:r,privateKey:i,supplierCapPackageId:o,dbConfig:n}){let s=e??h(t);this.suiClient=new grpc.SuiGrpcClient({baseUrl:s,network:t}),this.keypair=this.#r(i),this.address=this.keypair.getPublicKey().toSuiAddress(),this.supplierCapId=r,this.dbConfig=n??new deepbookV3.DeepBookConfig({network:t,address:this.address}),this.marginPoolContract=new deepbookV3.MarginPoolContract(this.dbConfig),this.supplierCapPackageId=o??this.dbConfig.MARGIN_PACKAGE_ID;}#r(t){if(t.startsWith(cryptography.SUI_PRIVATE_KEY_PREFIX)){let{secretKey:e}=cryptography.decodeSuiPrivateKey(t);return ed25519.Ed25519Keypair.fromSecretKey(w(e))}return ed25519.Ed25519Keypair.fromSecretKey(w(R(t)))}async#t(t,e={}){let r=await t.build({client:this.suiClient}),{signature:i}=await this.keypair.signTransaction(r),o=await this.suiClient.core.executeTransaction({transaction:r,signatures:[i],include:{effects:true,objectTypes:e.includeObjectTypes,balanceChanges:e.includeBalanceChanges}}),n=o.$kind==="Transaction"?o.Transaction:o.FailedTransaction;if(!n?.effects.status.success)throw new Error(`Transaction failed: ${n?.effects.status.error||"Unknown error"}`);return n}#i(t,e){if(!t.effects.changedObjects)return null;for(let r of t.effects.changedObjects){let i=t.objectTypes?.[r.objectId];if(!r.inputDigest&&i?.includes(e))return r.objectId}return null}#e(){if(!this.supplierCapId)throw new Error("Supplier Cap not initialized. Call initialize() first.");return this.supplierCapId}async#o(){let t=`${this.dbConfig.MARGIN_PACKAGE_ID}::margin_pool::SupplierCap`;return (await this.suiClient.core.listOwnedObjects({owner:this.address,type:t})).objects?.[0]?.objectId}async initialize(){if(this.supplierCapId)return this.supplierCapId;let t=await this.#o();if(t)return this.supplierCapId=t,t;let e=await this.createSupplierCap();if(!e)throw new Error("Failed to create Supplier Cap");return this.supplierCapId=e,e}async createSupplierCap(){try{let t=new transactions.Transaction;t.setSender(this.address);let e=t.moveCall({target:`${this.supplierCapPackageId}::margin_pool::mint_supplier_cap`,arguments:[t.object(this.dbConfig.MARGIN_REGISTRY_ID),t.object.clock()]});t.transferObjects([e],t.pure.address(this.address));let r=await this.#t(t,{includeObjectTypes:!0});return this.#i(r,"SupplierCap")}catch(t){throw new Error(`Failed to create Supplier Cap: ${t.message||t}`)}}async createSupplyReferral(t){try{let e=new transactions.Transaction;e.setSender(this.address);let r=this.dbConfig.getMarginPool(t);if(!r)throw new Error(`Margin pool configuration not found for coin: ${t}`);e.moveCall({target:`${this.dbConfig.MARGIN_PACKAGE_ID}::margin_pool::mint_supply_referral`,arguments:[e.object(r.address),e.object(this.dbConfig.MARGIN_REGISTRY_ID),e.object.clock()],typeArguments:[r.type]});let i=await this.#t(e,{includeObjectTypes:!0});return this.#i(i,"SupplyReferral")}catch(e){throw new Error(`Failed to create Supply Referral: ${e.message||e}`)}}async supplyToMarginPool(t,e,r){try{let i=this.#e(),o=new transactions.Transaction;o.setSender(this.address);let n=o.object(i);return o.add(this.marginPoolContract.supplyToMarginPool(t,n,e,r)),await this.#t(o),!0}catch(i){throw new Error(`Failed to supply to margin pool: ${i.message||i}`)}}async withdrawFromMarginPool(t,e){try{let r=this.#e(),i=new transactions.Transaction;i.setSender(this.address);let o=i.object(r),s=this.marginPoolContract.withdrawFromMarginPool(t,o,e)(i);return i.transferObjects([s],this.address),await this.#t(i),!0}catch(r){throw new Error(`Failed to withdraw from margin pool: ${r.message||r}`)}}async withdrawReferralFees(t,e){try{let r=new transactions.Transaction;return r.setSender(this.address),r.add(this.marginPoolContract.withdrawReferralFees(t,e)),await this.#t(r,{includeBalanceChanges:!0}),!0}catch(r){throw new Error(`Failed to withdraw referral fees: ${r.message||r}`)}}async getBalance(t){try{let e=this.#e(),r=new transactions.Transaction;r.setSender(this.address),r.add(this.marginPoolContract.userSupplyAmount(t,e));let i=await r.build({client:this.suiClient}),o=await this.suiClient.core.simulateTransaction({transaction:i,include:{commandResults:!0}}),n=this.dbConfig.getCoin(t),s=0,p=o.commandResults;if(p&&p[0]){let d=p[0].returnValues?.[0];if(d?.bcs){let f=Buffer.from(d.bcs).readBigUInt64LE();s=Number(f)/n.scalar;}}let l=await this.suiClient.core.getBalance({owner:this.address,coinType:n.type}),c=Number(l.balance)/n.scalar;return {userSupplyAmount:s,walletBalance:c}}catch(e){throw new Error(`Failed to get balance: ${e.message||e}`)}}getSupplierCapId(){return this.supplierCapId}getAddress(){return this.address}};var S=["supplyCap","maxUtilizationRate","protocolSpread","minBorrow","interestRate","totalSupply","supplyShares","totalBorrow","borrowShares","lastUpdateTimestamp"],P=["userSupplyShares","userSupplyAmount"],I={supplyCap:"U64",maxUtilizationRate:"U64",protocolSpread:"U64",minBorrow:"U64",interestRate:"U64",totalSupply:"U64",supplyShares:"U64",totalBorrow:"U64",borrowShares:"U64",lastUpdateTimestamp:"U64",userSupplyShares:"U64",userSupplyAmount:"U64"};var m=(a,t)=>a*t/BigInt(deepbookV3.FLOAT_SCALAR),u=a=>Number(a)/deepbookV3.FLOAT_SCALAR;var Y=new Set(P),D=a=>Y.has(a),A=class{marginPoolContract;dbConfig;suiClient;constructor({network:t,address:e="",suiClient:r,dbConfig:i}={}){let o=t??i?.network??"mainnet";if(this.dbConfig=i??new deepbookV3.DeepBookConfig({network:o,address:e}),this.suiClient=r??new grpc.SuiGrpcClient({baseUrl:h(o),network:o}),this.marginPoolContract=new deepbookV3.MarginPoolContract(this.dbConfig),t!==void 0&&i!==void 0&&t!==i.network)throw new Error(`Mismatch between provided network (${t}) and dbConfig network (${i.network}).`)}get network(){return this.dbConfig.network}#r(t,e,r,i){if(D(e)){let o=this.marginPoolContract[e];if(i==null)throw new Error(`supplierCap is required for '${e}'.`);t.add(o(r,i));}else {let o=this.marginPoolContract[e];t.add(o(r));}}parseInspectResultToBcsStructs(t,e){let r=t.commandResults;if(!r)throw new Error("No results found in simulateTransaction output.");return e.reduce((i,o,n)=>{let s=r[n]?.returnValues?.[0]?.bcs;if(!s)return i;let p=bcs.bcs[I[o]];return i[o]=p.parse(new Uint8Array(s)),i},{})}formatResult(t,e){let r=this.dbConfig.getCoin(e),i={supplyCap:0,maxUtilizationRate:0,protocolSpread:0,minBorrow:0,interestRate:0,totalSupply:0,supplyShares:0,totalBorrow:0,borrowShares:0,lastUpdateTimestamp:0,userSupplyShares:0,userSupplyAmount:0,decimals:r.scalar.toString().length-1,highKink:0,baseBorrowApr:0,borrowAprOnHighKink:0,maxBorrowApr:0,supplyApr:0,utilizationRate:0,...r};if(!r)return i;let o=new Set(["interestRate","maxUtilizationRate","protocolSpread"]);for(let[n,s]of Object.entries(t))n==="lastUpdateTimestamp"?i[n]=Number(s):o.has(n)?i[n]=new bignumber_js.BigNumber(s).dividedBy(deepbookV3.FLOAT_SCALAR).toNumber():i[n]=new bignumber_js.BigNumber(s).dividedBy(r.scalar).toNumber();return i}computeBorrowAprAtUtil(t,e){let r=BigInt(e.base_rate),i=BigInt(e.base_slope),o=BigInt(e.excess_slope),n=BigInt(e.optimal_utilization);return t<n?r+m(t,i):r+m(n,i)+m(t-n,o)}calculateKinksAndRate(t,e,r,i){let o=BigInt(t.optimal_utilization),n=BigInt(e.max_utilization_rate),s=this.computeBorrowAprAtUtil(o,t),p=this.computeBorrowAprAtUtil(n,t),l=BigInt(bignumber_js.BigNumber(r.total_borrow).dividedBy(r.total_supply).shiftedBy(9).decimalPlaces(0).toString()),c=m(m(i,l),BigInt(deepbookV3.FLOAT_SCALAR)-BigInt(e.protocol_spread));return {raw:{baseBorrowApr:t.base_rate,highKink:o,borrowAprOnHighKink:s,maxBorrowApr:p,supplyApr:c,utilizationRate:l},normalized:{baseBorrowApr:u(BigInt(t.base_rate)),highKink:u(o),borrowAprOnHighKink:u(s),maxBorrowApr:u(p),supplyApr:u(c),utilizationRate:u(l)}}}async#t(t,e){let{address:r}=this.dbConfig.getMarginPool(t),o=(await this.suiClient.core.getObject({objectId:r,include:{json:true}})).object?.json,n=o?.config,s=n?.interest_config,p=n?.margin_pool_config,l=o?.state,{normalized:c}=this.calculateKinksAndRate(s,p,l,e);return c}async getPoolParameters(t,e,r=new transactions.Transaction,i=true){if(S.forEach(y=>this.#r(r,y,t)),e&&P.forEach(y=>this.#r(r,y,t,e)),!i)return r;let o=[...S,...P],n=this.dbConfig.address||"0x0000000000000000000000000000000000000000000000000000000000000000";r.setSender(n),r.setGasBudget(50000000000n),r.setGasPayment([]);let s=await r.build({client:this.suiClient}),p=await this.suiClient.core.simulateTransaction({transaction:s,include:{commandResults:true}}),l=this.parseInspectResultToBcsStructs(p,o),c=this.formatResult(l,t),d=BigInt(l.interestRate??0),f=await this.#t(t,d);return {...c,...f}}};
|
|
2
|
+
exports.DeepBookMarginPool=A;exports.DeepBookMarginToolkit=b;
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {SuiGrpcClient}from'@mysten/sui/grpc';import {Ed25519Keypair}from'@mysten/sui/keypairs/ed25519';import {Transaction}from'@mysten/sui/transactions';import {DeepBookConfig,MarginPoolContract,FLOAT_SCALAR}from'@mysten/deepbook-v3';import {SUI_PRIVATE_KEY_PREFIX,decodeSuiPrivateKey,LEGACY_PRIVATE_KEY_SIZE,PRIVATE_KEY_SIZE}from'@mysten/sui/cryptography';import {fromHex,fromBase64}from'@mysten/bcs';import {bcs}from'@mysten/sui/bcs';import {BigNumber}from'bignumber.js';var U=a=>/^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(a),O=a=>/^[a-zA-Z0-9+/]+={0,2}$/g.test(a),R=a=>{if(U(a))return fromHex(a);if(O(a))return fromBase64(a);throw new Error("The string is not a valid hex or base64 string.")},w=a=>{if(a.length===LEGACY_PRIVATE_KEY_SIZE)return a.slice(0,PRIVATE_KEY_SIZE);if(a.length===PRIVATE_KEY_SIZE+1&&a[0]===0)return a.slice(1);if(a.length===PRIVATE_KEY_SIZE)return a;throw new Error("invalid secret key")};function h(a){switch(a){case "mainnet":return "https://fullnode.mainnet.sui.io:443";case "testnet":return "https://fullnode.testnet.sui.io:443";default:throw new Error(`Unknown network: ${a}`)}}var b=class{suiClient;keypair;address;marginPoolContract;supplierCapId;dbConfig;supplierCapPackageId;constructor({network:t,fullnodeUrl:
|
|
2
|
-
export{
|
|
1
|
+
import {SuiGrpcClient}from'@mysten/sui/grpc';import {Ed25519Keypair}from'@mysten/sui/keypairs/ed25519';import {Transaction}from'@mysten/sui/transactions';import {DeepBookConfig,MarginPoolContract,FLOAT_SCALAR}from'@mysten/deepbook-v3';import {SUI_PRIVATE_KEY_PREFIX,decodeSuiPrivateKey,LEGACY_PRIVATE_KEY_SIZE,PRIVATE_KEY_SIZE}from'@mysten/sui/cryptography';import {fromHex,fromBase64}from'@mysten/bcs';import {bcs}from'@mysten/sui/bcs';import {BigNumber}from'bignumber.js';var U=a=>/^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(a),O=a=>/^[a-zA-Z0-9+/]+={0,2}$/g.test(a),R=a=>{if(U(a))return fromHex(a);if(O(a))return fromBase64(a);throw new Error("The string is not a valid hex or base64 string.")},w=a=>{if(a.length===LEGACY_PRIVATE_KEY_SIZE)return a.slice(0,PRIVATE_KEY_SIZE);if(a.length===PRIVATE_KEY_SIZE+1&&a[0]===0)return a.slice(1);if(a.length===PRIVATE_KEY_SIZE)return a;throw new Error("invalid secret key")};function h(a){switch(a){case "mainnet":return "https://fullnode.mainnet.sui.io:443";case "testnet":return "https://fullnode.testnet.sui.io:443";default:throw new Error(`Unknown network: ${a}`)}}var b=class{suiClient;keypair;address;marginPoolContract;supplierCapId;dbConfig;supplierCapPackageId;constructor({network:t,fullnodeUrl:e,supplierCapId:r,privateKey:i,supplierCapPackageId:o,dbConfig:n}){let s=e??h(t);this.suiClient=new SuiGrpcClient({baseUrl:s,network:t}),this.keypair=this.#r(i),this.address=this.keypair.getPublicKey().toSuiAddress(),this.supplierCapId=r,this.dbConfig=n??new DeepBookConfig({network:t,address:this.address}),this.marginPoolContract=new MarginPoolContract(this.dbConfig),this.supplierCapPackageId=o??this.dbConfig.MARGIN_PACKAGE_ID;}#r(t){if(t.startsWith(SUI_PRIVATE_KEY_PREFIX)){let{secretKey:e}=decodeSuiPrivateKey(t);return Ed25519Keypair.fromSecretKey(w(e))}return Ed25519Keypair.fromSecretKey(w(R(t)))}async#t(t,e={}){let r=await t.build({client:this.suiClient}),{signature:i}=await this.keypair.signTransaction(r),o=await this.suiClient.core.executeTransaction({transaction:r,signatures:[i],include:{effects:true,objectTypes:e.includeObjectTypes,balanceChanges:e.includeBalanceChanges}}),n=o.$kind==="Transaction"?o.Transaction:o.FailedTransaction;if(!n?.effects.status.success)throw new Error(`Transaction failed: ${n?.effects.status.error||"Unknown error"}`);return n}#i(t,e){if(!t.effects.changedObjects)return null;for(let r of t.effects.changedObjects){let i=t.objectTypes?.[r.objectId];if(!r.inputDigest&&i?.includes(e))return r.objectId}return null}#e(){if(!this.supplierCapId)throw new Error("Supplier Cap not initialized. Call initialize() first.");return this.supplierCapId}async#o(){let t=`${this.dbConfig.MARGIN_PACKAGE_ID}::margin_pool::SupplierCap`;return (await this.suiClient.core.listOwnedObjects({owner:this.address,type:t})).objects?.[0]?.objectId}async initialize(){if(this.supplierCapId)return this.supplierCapId;let t=await this.#o();if(t)return this.supplierCapId=t,t;let e=await this.createSupplierCap();if(!e)throw new Error("Failed to create Supplier Cap");return this.supplierCapId=e,e}async createSupplierCap(){try{let t=new Transaction;t.setSender(this.address);let e=t.moveCall({target:`${this.supplierCapPackageId}::margin_pool::mint_supplier_cap`,arguments:[t.object(this.dbConfig.MARGIN_REGISTRY_ID),t.object.clock()]});t.transferObjects([e],t.pure.address(this.address));let r=await this.#t(t,{includeObjectTypes:!0});return this.#i(r,"SupplierCap")}catch(t){throw new Error(`Failed to create Supplier Cap: ${t.message||t}`)}}async createSupplyReferral(t){try{let e=new Transaction;e.setSender(this.address);let r=this.dbConfig.getMarginPool(t);if(!r)throw new Error(`Margin pool configuration not found for coin: ${t}`);e.moveCall({target:`${this.dbConfig.MARGIN_PACKAGE_ID}::margin_pool::mint_supply_referral`,arguments:[e.object(r.address),e.object(this.dbConfig.MARGIN_REGISTRY_ID),e.object.clock()],typeArguments:[r.type]});let i=await this.#t(e,{includeObjectTypes:!0});return this.#i(i,"SupplyReferral")}catch(e){throw new Error(`Failed to create Supply Referral: ${e.message||e}`)}}async supplyToMarginPool(t,e,r){try{let i=this.#e(),o=new Transaction;o.setSender(this.address);let n=o.object(i);return o.add(this.marginPoolContract.supplyToMarginPool(t,n,e,r)),await this.#t(o),!0}catch(i){throw new Error(`Failed to supply to margin pool: ${i.message||i}`)}}async withdrawFromMarginPool(t,e){try{let r=this.#e(),i=new Transaction;i.setSender(this.address);let o=i.object(r),s=this.marginPoolContract.withdrawFromMarginPool(t,o,e)(i);return i.transferObjects([s],this.address),await this.#t(i),!0}catch(r){throw new Error(`Failed to withdraw from margin pool: ${r.message||r}`)}}async withdrawReferralFees(t,e){try{let r=new Transaction;return r.setSender(this.address),r.add(this.marginPoolContract.withdrawReferralFees(t,e)),await this.#t(r,{includeBalanceChanges:!0}),!0}catch(r){throw new Error(`Failed to withdraw referral fees: ${r.message||r}`)}}async getBalance(t){try{let e=this.#e(),r=new Transaction;r.setSender(this.address),r.add(this.marginPoolContract.userSupplyAmount(t,e));let i=await r.build({client:this.suiClient}),o=await this.suiClient.core.simulateTransaction({transaction:i,include:{commandResults:!0}}),n=this.dbConfig.getCoin(t),s=0,p=o.commandResults;if(p&&p[0]){let d=p[0].returnValues?.[0];if(d?.bcs){let f=Buffer.from(d.bcs).readBigUInt64LE();s=Number(f)/n.scalar;}}let l=await this.suiClient.core.getBalance({owner:this.address,coinType:n.type}),c=Number(l.balance)/n.scalar;return {userSupplyAmount:s,walletBalance:c}}catch(e){throw new Error(`Failed to get balance: ${e.message||e}`)}}getSupplierCapId(){return this.supplierCapId}getAddress(){return this.address}};var S=["supplyCap","maxUtilizationRate","protocolSpread","minBorrow","interestRate","totalSupply","supplyShares","totalBorrow","borrowShares","lastUpdateTimestamp"],P=["userSupplyShares","userSupplyAmount"],I={supplyCap:"U64",maxUtilizationRate:"U64",protocolSpread:"U64",minBorrow:"U64",interestRate:"U64",totalSupply:"U64",supplyShares:"U64",totalBorrow:"U64",borrowShares:"U64",lastUpdateTimestamp:"U64",userSupplyShares:"U64",userSupplyAmount:"U64"};var m=(a,t)=>a*t/BigInt(FLOAT_SCALAR),u=a=>Number(a)/FLOAT_SCALAR;var Y=new Set(P),D=a=>Y.has(a),A=class{marginPoolContract;dbConfig;suiClient;constructor({network:t,address:e="",suiClient:r,dbConfig:i}={}){let o=t??i?.network??"mainnet";if(this.dbConfig=i??new DeepBookConfig({network:o,address:e}),this.suiClient=r??new SuiGrpcClient({baseUrl:h(o),network:o}),this.marginPoolContract=new MarginPoolContract(this.dbConfig),t!==void 0&&i!==void 0&&t!==i.network)throw new Error(`Mismatch between provided network (${t}) and dbConfig network (${i.network}).`)}get network(){return this.dbConfig.network}#r(t,e,r,i){if(D(e)){let o=this.marginPoolContract[e];if(i==null)throw new Error(`supplierCap is required for '${e}'.`);t.add(o(r,i));}else {let o=this.marginPoolContract[e];t.add(o(r));}}parseInspectResultToBcsStructs(t,e){let r=t.commandResults;if(!r)throw new Error("No results found in simulateTransaction output.");return e.reduce((i,o,n)=>{let s=r[n]?.returnValues?.[0]?.bcs;if(!s)return i;let p=bcs[I[o]];return i[o]=p.parse(new Uint8Array(s)),i},{})}formatResult(t,e){let r=this.dbConfig.getCoin(e),i={supplyCap:0,maxUtilizationRate:0,protocolSpread:0,minBorrow:0,interestRate:0,totalSupply:0,supplyShares:0,totalBorrow:0,borrowShares:0,lastUpdateTimestamp:0,userSupplyShares:0,userSupplyAmount:0,decimals:r.scalar.toString().length-1,highKink:0,baseBorrowApr:0,borrowAprOnHighKink:0,maxBorrowApr:0,supplyApr:0,utilizationRate:0,...r};if(!r)return i;let o=new Set(["interestRate","maxUtilizationRate","protocolSpread"]);for(let[n,s]of Object.entries(t))n==="lastUpdateTimestamp"?i[n]=Number(s):o.has(n)?i[n]=new BigNumber(s).dividedBy(FLOAT_SCALAR).toNumber():i[n]=new BigNumber(s).dividedBy(r.scalar).toNumber();return i}computeBorrowAprAtUtil(t,e){let r=BigInt(e.base_rate),i=BigInt(e.base_slope),o=BigInt(e.excess_slope),n=BigInt(e.optimal_utilization);return t<n?r+m(t,i):r+m(n,i)+m(t-n,o)}calculateKinksAndRate(t,e,r,i){let o=BigInt(t.optimal_utilization),n=BigInt(e.max_utilization_rate),s=this.computeBorrowAprAtUtil(o,t),p=this.computeBorrowAprAtUtil(n,t),l=BigInt(BigNumber(r.total_borrow).dividedBy(r.total_supply).shiftedBy(9).decimalPlaces(0).toString()),c=m(m(i,l),BigInt(FLOAT_SCALAR)-BigInt(e.protocol_spread));return {raw:{baseBorrowApr:t.base_rate,highKink:o,borrowAprOnHighKink:s,maxBorrowApr:p,supplyApr:c,utilizationRate:l},normalized:{baseBorrowApr:u(BigInt(t.base_rate)),highKink:u(o),borrowAprOnHighKink:u(s),maxBorrowApr:u(p),supplyApr:u(c),utilizationRate:u(l)}}}async#t(t,e){let{address:r}=this.dbConfig.getMarginPool(t),o=(await this.suiClient.core.getObject({objectId:r,include:{json:true}})).object?.json,n=o?.config,s=n?.interest_config,p=n?.margin_pool_config,l=o?.state,{normalized:c}=this.calculateKinksAndRate(s,p,l,e);return c}async getPoolParameters(t,e,r=new Transaction,i=true){if(S.forEach(y=>this.#r(r,y,t)),e&&P.forEach(y=>this.#r(r,y,t,e)),!i)return r;let o=[...S,...P],n=this.dbConfig.address||"0x0000000000000000000000000000000000000000000000000000000000000000";r.setSender(n),r.setGasBudget(50000000000n),r.setGasPayment([]);let s=await r.build({client:this.suiClient}),p=await this.suiClient.core.simulateTransaction({transaction:s,include:{commandResults:true}}),l=this.parseInspectResultToBcsStructs(p,o),c=this.formatResult(l,t),d=BigInt(l.interestRate??0),f=await this.#t(t,d);return {...c,...f}}};
|
|
2
|
+
export{A as DeepBookMarginPool,b as DeepBookMarginToolkit};
|
package/package.json
CHANGED
|
@@ -321,12 +321,12 @@ export class DeepBookMarginPool {
|
|
|
321
321
|
json: true,
|
|
322
322
|
},
|
|
323
323
|
});
|
|
324
|
-
|
|
325
|
-
const
|
|
326
|
-
const config =
|
|
327
|
-
const interestConfig = config
|
|
328
|
-
const marginPoolConfig = config
|
|
329
|
-
const statePoolConfig =
|
|
324
|
+
// gRPC returns Move object fields directly in json (no .fields wrapper)
|
|
325
|
+
const json = response.object?.json as any;
|
|
326
|
+
const config = json?.config;
|
|
327
|
+
const interestConfig = config?.interest_config as RawInterestConfig;
|
|
328
|
+
const marginPoolConfig = config?.margin_pool_config as RawMarginPoolConfig;
|
|
329
|
+
const statePoolConfig = json?.state as RawStatePoolConfig;
|
|
330
330
|
|
|
331
331
|
const { normalized } = this.calculateKinksAndRate(
|
|
332
332
|
interestConfig,
|
|
@@ -402,6 +402,8 @@ export class DeepBookMarginPool {
|
|
|
402
402
|
const sender =
|
|
403
403
|
this.dbConfig.address || '0x0000000000000000000000000000000000000000000000000000000000000000';
|
|
404
404
|
tx.setSender(sender);
|
|
405
|
+
tx.setGasBudget(50_000_000_000n);
|
|
406
|
+
tx.setGasPayment([]);
|
|
405
407
|
const txBytes = await tx.build({ client: this.suiClient });
|
|
406
408
|
const inspectResult = await this.suiClient.core.simulateTransaction({
|
|
407
409
|
transaction: txBytes,
|